path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
ajax/libs/react-router/0.11.4/react-router.js | Amomo/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=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){
/**
* Actions that modify the URL.
*/
var LocationActions = {
/**
* Indicates a new location is being pushed to the history stack.
*/
PUSH: 'push',
/**
* Indicates the current location should be replaced.
*/
REPLACE: 'replace',
/**
* Indicates the most recent entry should be removed from the history stack.
*/
POP: 'pop'
};
module.exports = LocationActions;
},{}],2:[function(_dereq_,module,exports){
var LocationActions = _dereq_('../actions/LocationActions');
/**
* A scroll behavior that attempts to imitate the default behavior
* of modern browsers.
*/
var ImitateBrowserBehavior = {
updateScrollPosition: function (position, actionType) {
switch (actionType) {
case LocationActions.PUSH:
case LocationActions.REPLACE:
window.scrollTo(0, 0);
break;
case LocationActions.POP:
if (position) {
window.scrollTo(position.x, position.y);
} else {
window.scrollTo(0, 0);
}
break;
}
}
};
module.exports = ImitateBrowserBehavior;
},{"../actions/LocationActions":1}],3:[function(_dereq_,module,exports){
/**
* A scroll behavior that always scrolls to the top of the page
* after a transition.
*/
var ScrollToTopBehavior = {
updateScrollPosition: function () {
window.scrollTo(0, 0);
}
};
module.exports = ScrollToTopBehavior;
},{}],4:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var FakeNode = _dereq_('../mixins/FakeNode');
var PropTypes = _dereq_('../utils/PropTypes');
/**
* A <DefaultRoute> component is a special kind of <Route> that
* renders when its parent matches but none of its siblings do.
* Only one such route may be used at any given level in the
* route hierarchy.
*/
var DefaultRoute = React.createClass({
displayName: 'DefaultRoute',
mixins: [ FakeNode ],
propTypes: {
name: React.PropTypes.string,
path: PropTypes.falsy,
handler: React.PropTypes.func.isRequired
}
});
module.exports = DefaultRoute;
},{"../mixins/FakeNode":14,"../utils/PropTypes":23}],5:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var classSet = _dereq_('react/lib/cx');
var assign = _dereq_('react/lib/Object.assign');
var Navigation = _dereq_('../mixins/Navigation');
var State = _dereq_('../mixins/State');
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* <Link> components are used to create an <a> element that links to a route.
* When that route is active, the link gets an "active" class name (or the
* value of its `activeClassName` prop).
*
* For example, assuming you have the following route:
*
* <Route name="showPost" path="/posts/:postID" handler={Post}/>
*
* You could use the following component to link to that route:
*
* <Link to="showPost" params={{ postID: "123" }} />
*
* In addition to params, links may pass along query string parameters
* using the `query` prop.
*
* <Link to="showPost" params={{ postID: "123" }} query={{ show:true }}/>
*/
var Link = React.createClass({
displayName: 'Link',
mixins: [ Navigation, State ],
propTypes: {
activeClassName: React.PropTypes.string.isRequired,
to: React.PropTypes.string.isRequired,
params: React.PropTypes.object,
query: React.PropTypes.object,
onClick: React.PropTypes.func
},
getDefaultProps: function () {
return {
activeClassName: 'active'
};
},
handleClick: function (event) {
var allowTransition = true;
var clickResult;
if (this.props.onClick)
clickResult = this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return;
if (clickResult === false || event.defaultPrevented === true)
allowTransition = false;
event.preventDefault();
if (allowTransition)
this.transitionTo(this.props.to, this.props.params, this.props.query);
},
/**
* Returns the value of the "href" attribute to use on the DOM element.
*/
getHref: function () {
return this.makeHref(this.props.to, this.props.params, this.props.query);
},
/**
* Returns the value of the "class" attribute to use on the DOM element, which contains
* the value of the activeClassName property when this <Link> is active.
*/
getClassName: function () {
var classNames = {};
if (this.props.className)
classNames[this.props.className] = true;
if (this.isActive(this.props.to, this.props.params, this.props.query))
classNames[this.props.activeClassName] = true;
return classSet(classNames);
},
render: function () {
var props = assign({}, this.props, {
href: this.getHref(),
className: this.getClassName(),
onClick: this.handleClick
});
return React.DOM.a(props, this.props.children);
}
});
module.exports = Link;
},{"../mixins/Navigation":15,"../mixins/State":18,"react/lib/Object.assign":38,"react/lib/cx":39}],6:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var FakeNode = _dereq_('../mixins/FakeNode');
var PropTypes = _dereq_('../utils/PropTypes');
/**
* A <NotFoundRoute> is a special kind of <Route> that
* renders when the beginning of its parent's path matches
* but none of its siblings do, including any <DefaultRoute>.
* Only one such route may be used at any given level in the
* route hierarchy.
*/
var NotFoundRoute = React.createClass({
displayName: 'NotFoundRoute',
mixins: [ FakeNode ],
propTypes: {
name: React.PropTypes.string,
path: PropTypes.falsy,
handler: React.PropTypes.func.isRequired
}
});
module.exports = NotFoundRoute;
},{"../mixins/FakeNode":14,"../utils/PropTypes":23}],7:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var FakeNode = _dereq_('../mixins/FakeNode');
var PropTypes = _dereq_('../utils/PropTypes');
/**
* A <Redirect> component is a special kind of <Route> that always
* redirects to another route when it matches.
*/
var Redirect = React.createClass({
displayName: 'Redirect',
mixins: [ FakeNode ],
propTypes: {
path: React.PropTypes.string,
from: React.PropTypes.string, // Alias for path.
to: React.PropTypes.string,
handler: PropTypes.falsy
}
});
module.exports = Redirect;
},{"../mixins/FakeNode":14,"../utils/PropTypes":23}],8:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var FakeNode = _dereq_('../mixins/FakeNode');
/**
* <Route> components specify components that are rendered to the page when the
* URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is requested,
* the tree is searched depth-first to find a route whose path matches the URL.
* When one is found, all routes in the tree that lead to it are considered
* "active" and their components are rendered into the DOM, nested in the same
* order as they are in the tree.
*
* The preferred way to configure a router is using JSX. The XML-like syntax is
* a great way to visualize how routes are laid out in an application.
*
* var routes = [
* <Route handler={App}>
* <Route name="login" handler={Login}/>
* <Route name="logout" handler={Logout}/>
* <Route name="about" handler={About}/>
* </Route>
* ];
*
* Router.run(routes, function (Handler) {
* React.render(<Handler/>, document.body);
* });
*
* Handlers for Route components that contain children can render their active
* child route using a <RouteHandler> element.
*
* var App = React.createClass({
* render: function () {
* return (
* <div class="application">
* <RouteHandler/>
* </div>
* );
* }
* });
*/
var Route = React.createClass({
displayName: 'Route',
mixins: [ FakeNode ],
propTypes: {
name: React.PropTypes.string,
path: React.PropTypes.string,
handler: React.PropTypes.func.isRequired,
ignoreScrollBehavior: React.PropTypes.bool
}
});
module.exports = Route;
},{"../mixins/FakeNode":14}],9:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
/**
* A <RouteHandler> component renders the active child route handler
* when routes are nested.
*/
var RouteHandler = React.createClass({
displayName: 'RouteHandler',
getDefaultProps: function () {
return {
ref: '__routeHandler__'
};
},
contextTypes: {
getRouteAtDepth: React.PropTypes.func.isRequired,
getRouteComponents: React.PropTypes.func.isRequired,
routeHandlers: React.PropTypes.array.isRequired
},
childContextTypes: {
routeHandlers: React.PropTypes.array.isRequired
},
getChildContext: function () {
return {
routeHandlers: this.context.routeHandlers.concat([ this ])
};
},
getRouteDepth: function () {
return this.context.routeHandlers.length - 1;
},
componentDidMount: function () {
this._updateRouteComponent();
},
componentDidUpdate: function () {
this._updateRouteComponent();
},
_updateRouteComponent: function () {
var depth = this.getRouteDepth();
var components = this.context.getRouteComponents();
components[depth] = this.refs[this.props.ref];
},
render: function () {
var route = this.context.getRouteAtDepth(this.getRouteDepth());
return route ? React.createElement(route.handler, this.props) : null;
}
});
module.exports = RouteHandler;
},{}],10:[function(_dereq_,module,exports){
exports.DefaultRoute = _dereq_('./components/DefaultRoute');
exports.Link = _dereq_('./components/Link');
exports.NotFoundRoute = _dereq_('./components/NotFoundRoute');
exports.Redirect = _dereq_('./components/Redirect');
exports.Route = _dereq_('./components/Route');
exports.RouteHandler = _dereq_('./components/RouteHandler');
exports.HashLocation = _dereq_('./locations/HashLocation');
exports.HistoryLocation = _dereq_('./locations/HistoryLocation');
exports.RefreshLocation = _dereq_('./locations/RefreshLocation');
exports.ImitateBrowserBehavior = _dereq_('./behaviors/ImitateBrowserBehavior');
exports.ScrollToTopBehavior = _dereq_('./behaviors/ScrollToTopBehavior');
exports.Navigation = _dereq_('./mixins/Navigation');
exports.State = _dereq_('./mixins/State');
exports.create = _dereq_('./utils/createRouter');
exports.run = _dereq_('./utils/runRouter');
},{"./behaviors/ImitateBrowserBehavior":2,"./behaviors/ScrollToTopBehavior":3,"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/RouteHandler":9,"./locations/HashLocation":11,"./locations/HistoryLocation":12,"./locations/RefreshLocation":13,"./mixins/Navigation":15,"./mixins/State":18,"./utils/createRouter":26,"./utils/runRouter":30}],11:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM;
var LocationActions = _dereq_('../actions/LocationActions');
var Path = _dereq_('../utils/Path');
/**
* Returns the current URL path from `window.location.hash`, including query string
*/
function getHashPath() {
invariant(
canUseDOM,
'getHashPath needs a DOM'
);
return Path.decode(
window.location.hash.substr(1)
);
}
var _actionType;
function ensureSlash() {
var path = getHashPath();
if (path.charAt(0) === '/')
return true;
HashLocation.replace('/' + path);
return false;
}
var _changeListeners = [];
function notifyChange(type) {
var change = {
path: getHashPath(),
type: type
};
_changeListeners.forEach(function (listener) {
listener(change);
});
}
var _isListening = false;
function onHashChange() {
if (ensureSlash()) {
// If we don't have an _actionType then all we know is the hash
// changed. It was probably caused by the user clicking the Back
// button, but may have also been the Forward button or manual
// manipulation. So just guess 'pop'.
notifyChange(_actionType || LocationActions.POP);
_actionType = null;
}
}
/**
* A Location that uses `window.location.hash`.
*/
var HashLocation = {
addChangeListener: function (listener) {
_changeListeners.push(listener);
// Do this BEFORE listening for hashchange.
ensureSlash();
if (_isListening)
return;
if (window.addEventListener) {
window.addEventListener('hashchange', onHashChange, false);
} else {
window.attachEvent('onhashchange', onHashChange);
}
_isListening = true;
},
push: function (path) {
_actionType = LocationActions.PUSH;
window.location.hash = Path.encode(path);
},
replace: function (path) {
_actionType = LocationActions.REPLACE;
window.location.replace(window.location.pathname + '#' + Path.encode(path));
},
pop: function () {
_actionType = LocationActions.POP;
window.history.back();
},
getCurrentPath: getHashPath,
toString: function () {
return '<HashLocation>';
}
};
module.exports = HashLocation;
},{"../actions/LocationActions":1,"../utils/Path":21,"react/lib/ExecutionEnvironment":37,"react/lib/invariant":41}],12:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM;
var LocationActions = _dereq_('../actions/LocationActions');
var Path = _dereq_('../utils/Path');
/**
* Returns the current URL path from `window.location`, including query string
*/
function getWindowPath() {
invariant(
canUseDOM,
'getWindowPath needs a DOM'
);
return Path.decode(
window.location.pathname + window.location.search
);
}
var _changeListeners = [];
function notifyChange(type) {
var change = {
path: getWindowPath(),
type: type
};
_changeListeners.forEach(function (listener) {
listener(change);
});
}
var _isListening = false;
function onPopState() {
notifyChange(LocationActions.POP);
}
/**
* A Location that uses HTML5 history.
*/
var HistoryLocation = {
addChangeListener: function (listener) {
_changeListeners.push(listener);
if (_isListening)
return;
if (window.addEventListener) {
window.addEventListener('popstate', onPopState, false);
} else {
window.attachEvent('popstate', onPopState);
}
_isListening = true;
},
push: function (path) {
window.history.pushState({ path: path }, '', Path.encode(path));
notifyChange(LocationActions.PUSH);
},
replace: function (path) {
window.history.replaceState({ path: path }, '', Path.encode(path));
notifyChange(LocationActions.REPLACE);
},
pop: function () {
window.history.back();
},
getCurrentPath: getWindowPath,
toString: function () {
return '<HistoryLocation>';
}
};
module.exports = HistoryLocation;
},{"../actions/LocationActions":1,"../utils/Path":21,"react/lib/ExecutionEnvironment":37,"react/lib/invariant":41}],13:[function(_dereq_,module,exports){
var HistoryLocation = _dereq_('./HistoryLocation');
var Path = _dereq_('../utils/Path');
/**
* A Location that uses full page refreshes. This is used as
* the fallback for HistoryLocation in browsers that do not
* support the HTML5 history API.
*/
var RefreshLocation = {
push: function (path) {
window.location = Path.encode(path);
},
replace: function (path) {
window.location.replace(Path.encode(path));
},
pop: function () {
window.history.back();
},
getCurrentPath: HistoryLocation.getCurrentPath,
toString: function () {
return '<RefreshLocation>';
}
};
module.exports = RefreshLocation;
},{"../utils/Path":21,"./HistoryLocation":12}],14:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var FakeNode = {
render: function () {
invariant(
false,
'%s elements should not be rendered',
this.constructor.displayName
);
}
};
module.exports = FakeNode;
},{"react/lib/invariant":41}],15:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
/**
* A mixin for components that modify the URL.
*
* Example:
*
* var MyLink = React.createClass({
* mixins: [ Router.Navigation ],
* handleClick: function (event) {
* event.preventDefault();
* this.transitionTo('aRoute', { the: 'params' }, { the: 'query' });
* },
* render: function () {
* return (
* <a onClick={this.handleClick}>Click me!</a>
* );
* }
* });
*/
var Navigation = {
contextTypes: {
makePath: React.PropTypes.func.isRequired,
makeHref: React.PropTypes.func.isRequired,
transitionTo: React.PropTypes.func.isRequired,
replaceWith: React.PropTypes.func.isRequired,
goBack: React.PropTypes.func.isRequired
},
/**
* Returns an absolute URL path created from the given route
* name, URL parameters, and query values.
*/
makePath: function (to, params, query) {
return this.context.makePath(to, params, query);
},
/**
* Returns a string that may safely be used as the href of a
* link to the route with the given name.
*/
makeHref: function (to, params, query) {
return this.context.makeHref(to, params, query);
},
/**
* Transitions to the URL specified in the arguments by pushing
* a new URL onto the history stack.
*/
transitionTo: function (to, params, query) {
this.context.transitionTo(to, params, query);
},
/**
* Transitions to the URL specified in the arguments by replacing
* the current URL in the history stack.
*/
replaceWith: function (to, params, query) {
this.context.replaceWith(to, params, query);
},
/**
* Transitions to the previous URL.
*/
goBack: function () {
this.context.goBack();
}
};
module.exports = Navigation;
},{}],16:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
/**
* Provides the router with context for Router.Navigation.
*/
var NavigationContext = {
childContextTypes: {
makePath: React.PropTypes.func.isRequired,
makeHref: React.PropTypes.func.isRequired,
transitionTo: React.PropTypes.func.isRequired,
replaceWith: React.PropTypes.func.isRequired,
goBack: React.PropTypes.func.isRequired
},
getChildContext: function () {
return {
makePath: this.constructor.makePath,
makeHref: this.constructor.makeHref,
transitionTo: this.constructor.transitionTo,
replaceWith: this.constructor.replaceWith,
goBack: this.constructor.goBack
};
}
};
module.exports = NavigationContext;
},{}],17:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM;
var getWindowScrollPosition = _dereq_('../utils/getWindowScrollPosition');
function shouldUpdateScroll(state, prevState) {
if (!prevState)
return true;
// Don't update scroll position when only the query has changed.
if (state.pathname === prevState.pathname)
return false;
var routes = state.routes;
var prevRoutes = prevState.routes;
var sharedAncestorRoutes = routes.filter(function (route) {
return prevRoutes.indexOf(route) !== -1;
});
return !sharedAncestorRoutes.some(function (route) {
return route.ignoreScrollBehavior;
});
}
/**
* Provides the router with the ability to manage window scroll position
* according to its scroll behavior.
*/
var Scrolling = {
statics: {
/**
* Records curent scroll position as the last known position for the given URL path.
*/
recordScrollPosition: function (path) {
if (!this.scrollHistory)
this.scrollHistory = {};
this.scrollHistory[path] = getWindowScrollPosition();
},
/**
* Returns the last known scroll position for the given URL path.
*/
getScrollPosition: function (path) {
if (!this.scrollHistory)
this.scrollHistory = {};
return this.scrollHistory[path] || null;
}
},
componentWillMount: function () {
invariant(
this.getScrollBehavior() == null || canUseDOM,
'Cannot use scroll behavior without a DOM'
);
},
componentDidMount: function () {
this._updateScroll();
},
componentDidUpdate: function (prevProps, prevState) {
this._updateScroll(prevState);
},
_updateScroll: function (prevState) {
if (!shouldUpdateScroll(this.state, prevState))
return;
var scrollBehavior = this.getScrollBehavior();
if (scrollBehavior)
scrollBehavior.updateScrollPosition(
this.constructor.getScrollPosition(this.state.path),
this.state.action
);
}
};
module.exports = Scrolling;
},{"../utils/getWindowScrollPosition":28,"react/lib/ExecutionEnvironment":37,"react/lib/invariant":41}],18:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
/**
* A mixin for components that need to know the path, routes, URL
* params and query that are currently active.
*
* Example:
*
* var AboutLink = React.createClass({
* mixins: [ Router.State ],
* render: function () {
* var className = this.props.className;
*
* if (this.isActive('about'))
* className += ' is-active';
*
* return React.DOM.a({ className: className }, this.props.children);
* }
* });
*/
var State = {
contextTypes: {
getCurrentPath: React.PropTypes.func.isRequired,
getCurrentRoutes: React.PropTypes.func.isRequired,
getCurrentPathname: React.PropTypes.func.isRequired,
getCurrentParams: React.PropTypes.func.isRequired,
getCurrentQuery: React.PropTypes.func.isRequired,
isActive: React.PropTypes.func.isRequired
},
/**
* Returns the current URL path.
*/
getPath: function () {
return this.context.getCurrentPath();
},
/**
* Returns an array of the routes that are currently active.
*/
getRoutes: function () {
return this.context.getCurrentRoutes();
},
/**
* Returns the current URL path without the query string.
*/
getPathname: function () {
return this.context.getCurrentPathname();
},
/**
* Returns an object of the URL params that are currently active.
*/
getParams: function () {
return this.context.getCurrentParams();
},
/**
* Returns an object of the query params that are currently active.
*/
getQuery: function () {
return this.context.getCurrentQuery();
},
/**
* A helper method to determine if a given route, params, and query
* are active.
*/
isActive: function (to, params, query) {
return this.context.isActive(to, params, query);
}
};
module.exports = State;
},{}],19:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var assign = _dereq_('react/lib/Object.assign');
var Path = _dereq_('../utils/Path');
function routeIsActive(activeRoutes, routeName) {
return activeRoutes.some(function (route) {
return route.name === routeName;
});
}
function paramsAreActive(activeParams, params) {
for (var property in params)
if (String(activeParams[property]) !== String(params[property]))
return false;
return true;
}
function queryIsActive(activeQuery, query) {
for (var property in query)
if (String(activeQuery[property]) !== String(query[property]))
return false;
return true;
}
/**
* Provides the router with context for Router.State.
*/
var StateContext = {
/**
* Returns the current URL path + query string.
*/
getCurrentPath: function () {
return this.state.path;
},
/**
* Returns a read-only array of the currently active routes.
*/
getCurrentRoutes: function () {
return this.state.routes.slice(0);
},
/**
* Returns the current URL path without the query string.
*/
getCurrentPathname: function () {
return this.state.pathname;
},
/**
* Returns a read-only object of the currently active URL parameters.
*/
getCurrentParams: function () {
return assign({}, this.state.params);
},
/**
* Returns a read-only object of the currently active query parameters.
*/
getCurrentQuery: function () {
return assign({}, this.state.query);
},
/**
* Returns true if the given route, params, and query are active.
*/
isActive: function (to, params, query) {
if (Path.isAbsolute(to))
return to === this.state.path;
return routeIsActive(this.state.routes, to) &&
paramsAreActive(this.state.params, params) &&
(query == null || queryIsActive(this.state.query, query));
},
childContextTypes: {
getCurrentPath: React.PropTypes.func.isRequired,
getCurrentRoutes: React.PropTypes.func.isRequired,
getCurrentPathname: React.PropTypes.func.isRequired,
getCurrentParams: React.PropTypes.func.isRequired,
getCurrentQuery: React.PropTypes.func.isRequired,
isActive: React.PropTypes.func.isRequired
},
getChildContext: function () {
return {
getCurrentPath: this.getCurrentPath,
getCurrentRoutes: this.getCurrentRoutes,
getCurrentPathname: this.getCurrentPathname,
getCurrentParams: this.getCurrentParams,
getCurrentQuery: this.getCurrentQuery,
isActive: this.isActive
};
}
};
module.exports = StateContext;
},{"../utils/Path":21,"react/lib/Object.assign":38}],20:[function(_dereq_,module,exports){
/**
* Represents a cancellation caused by navigating away
* before the previous transition has fully resolved.
*/
function Cancellation() { }
module.exports = Cancellation;
},{}],21:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var merge = _dereq_('qs/lib/utils').merge;
var qs = _dereq_('qs');
var paramCompileMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g;
var paramInjectMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g;
var paramInjectTrailingSlashMatcher = /\/\/\?|\/\?/g;
var queryMatcher = /\?(.+)/;
var _compiledPatterns = {};
function compilePattern(pattern) {
if (!(pattern in _compiledPatterns)) {
var paramNames = [];
var source = pattern.replace(paramCompileMatcher, function (match, paramName) {
if (paramName) {
paramNames.push(paramName);
return '([^/?#]+)';
} else if (match === '*') {
paramNames.push('splat');
return '(.*?)';
} else {
return '\\' + match;
}
});
_compiledPatterns[pattern] = {
matcher: new RegExp('^' + source + '$', 'i'),
paramNames: paramNames
};
}
return _compiledPatterns[pattern];
}
var Path = {
/**
* Safely decodes special characters in the given URL path.
*/
decode: function (path) {
return decodeURI(path.replace(/\+/g, ' '));
},
/**
* Safely encodes special characters in the given URL path.
*/
encode: function (path) {
return encodeURI(path).replace(/%20/g, '+');
},
/**
* Returns an array of the names of all parameters in the given pattern.
*/
extractParamNames: function (pattern) {
return compilePattern(pattern).paramNames;
},
/**
* Extracts the portions of the given URL path that match the given pattern
* and returns an object of param name => value pairs. Returns null if the
* pattern does not match the given path.
*/
extractParams: function (pattern, path) {
var object = compilePattern(pattern);
var match = path.match(object.matcher);
if (!match)
return null;
var params = {};
object.paramNames.forEach(function (paramName, index) {
params[paramName] = match[index + 1];
});
return params;
},
/**
* Returns a version of the given route path with params interpolated. Throws
* if there is a dynamic segment of the route path for which there is no param.
*/
injectParams: function (pattern, params) {
params = params || {};
var splatIndex = 0;
return pattern.replace(paramInjectMatcher, function (match, paramName) {
paramName = paramName || 'splat';
// If param is optional don't check for existence
if (paramName.slice(-1) !== '?') {
invariant(
params[paramName] != null,
'Missing "' + paramName + '" parameter for path "' + pattern + '"'
);
} else {
paramName = paramName.slice(0, -1);
if (params[paramName] == null)
return '';
}
var segment;
if (paramName === 'splat' && Array.isArray(params[paramName])) {
segment = params[paramName][splatIndex++];
invariant(
segment != null,
'Missing splat # ' + splatIndex + ' for path "' + pattern + '"'
);
} else {
segment = params[paramName];
}
return segment;
}).replace(paramInjectTrailingSlashMatcher, '/');
},
/**
* Returns an object that is the result of parsing any query string contained
* in the given path, null if the path contains no query string.
*/
extractQuery: function (path) {
var match = path.match(queryMatcher);
return match && qs.parse(match[1]);
},
/**
* Returns a version of the given path without the query string.
*/
withoutQuery: function (path) {
return path.replace(queryMatcher, '');
},
/**
* Returns a version of the given path with the parameters in the given
* query merged into the query string.
*/
withQuery: function (path, query) {
var existingQuery = Path.extractQuery(path);
if (existingQuery)
query = query ? merge(existingQuery, query) : existingQuery;
var queryString = query && qs.stringify(query);
if (queryString)
return Path.withoutQuery(path) + '?' + queryString;
return path;
},
/**
* Returns true if the given path is absolute.
*/
isAbsolute: function (path) {
return path.charAt(0) === '/';
},
/**
* Returns a normalized version of the given path.
*/
normalize: function (path, parentRoute) {
return path.replace(/^\/*/, '/');
},
/**
* Joins two URL paths together.
*/
join: function (a, b) {
return a.replace(/\/*$/, '/') + b;
}
};
module.exports = Path;
},{"qs":32,"qs/lib/utils":36,"react/lib/invariant":41}],22:[function(_dereq_,module,exports){
var Promise = _dereq_('when/lib/Promise');
// TODO: Use process.env.NODE_ENV check + envify to enable
// when's promise monitor here when in dev.
module.exports = Promise;
},{"when/lib/Promise":43}],23:[function(_dereq_,module,exports){
var PropTypes = {
/**
* Requires that the value of a prop be falsy.
*/
falsy: function (props, propName, elementName) {
if (props[propName])
return new Error('<' + elementName + '> may not have a "' + propName + '" prop');
}
};
module.exports = PropTypes;
},{}],24:[function(_dereq_,module,exports){
/**
* Encapsulates a redirect to the given route.
*/
function Redirect(to, params, query) {
this.to = to;
this.params = params;
this.query = query;
}
module.exports = Redirect;
},{}],25:[function(_dereq_,module,exports){
var assign = _dereq_('react/lib/Object.assign');
var reversedArray = _dereq_('./reversedArray');
var Redirect = _dereq_('./Redirect');
var Promise = _dereq_('./Promise');
/**
* Runs all hook functions serially and calls callback(error) when finished.
* A hook may return a promise if it needs to execute asynchronously.
*/
function runHooks(hooks, callback) {
try {
var promise = hooks.reduce(function (promise, hook) {
// The first hook to use transition.wait makes the rest
// of the transition async from that point forward.
return promise ? promise.then(hook) : hook();
}, null);
} catch (error) {
return callback(error); // Sync error.
}
if (promise) {
// Use setTimeout to break the promise chain.
promise.then(function () {
setTimeout(callback);
}, function (error) {
setTimeout(function () {
callback(error);
});
});
} else {
callback();
}
}
/**
* Calls the willTransitionFrom hook of all handlers in the given matches
* serially in reverse with the transition object and the current instance of
* the route's handler, so that the deepest nested handlers are called first.
* Calls callback(error) when finished.
*/
function runTransitionFromHooks(transition, routes, components, callback) {
components = reversedArray(components);
var hooks = reversedArray(routes).map(function (route, index) {
return function () {
var handler = route.handler;
if (!transition.isAborted && handler.willTransitionFrom)
return handler.willTransitionFrom(transition, components[index]);
var promise = transition._promise;
transition._promise = null;
return promise;
};
});
runHooks(hooks, callback);
}
/**
* Calls the willTransitionTo hook of all handlers in the given matches
* serially with the transition object and any params that apply to that
* handler. Calls callback(error) when finished.
*/
function runTransitionToHooks(transition, routes, params, query, callback) {
var hooks = routes.map(function (route) {
return function () {
var handler = route.handler;
if (!transition.isAborted && handler.willTransitionTo)
handler.willTransitionTo(transition, params, query);
var promise = transition._promise;
transition._promise = null;
return promise;
};
});
runHooks(hooks, callback);
}
/**
* Encapsulates a transition to a given path.
*
* The willTransitionTo and willTransitionFrom handlers receive
* an instance of this class as their first argument.
*/
function Transition(path, retry) {
this.path = path;
this.abortReason = null;
this.isAborted = false;
this.retry = retry.bind(this);
this._promise = null;
}
assign(Transition.prototype, {
abort: function (reason) {
if (this.isAborted) {
// First abort wins.
return;
}
this.abortReason = reason;
this.isAborted = true;
},
redirect: function (to, params, query) {
this.abort(new Redirect(to, params, query));
},
wait: function (value) {
this._promise = Promise.resolve(value);
},
from: function (routes, components, callback) {
return runTransitionFromHooks(this, routes, components, callback);
},
to: function (routes, params, query, callback) {
return runTransitionToHooks(this, routes, params, query, callback);
}
});
module.exports = Transition;
},{"./Promise":22,"./Redirect":24,"./reversedArray":29,"react/lib/Object.assign":38}],26:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var warning = _dereq_('react/lib/warning');
var invariant = _dereq_('react/lib/invariant');
var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM;
var ImitateBrowserBehavior = _dereq_('../behaviors/ImitateBrowserBehavior');
var RouteHandler = _dereq_('../components/RouteHandler');
var LocationActions = _dereq_('../actions/LocationActions');
var HashLocation = _dereq_('../locations/HashLocation');
var HistoryLocation = _dereq_('../locations/HistoryLocation');
var RefreshLocation = _dereq_('../locations/RefreshLocation');
var NavigationContext = _dereq_('../mixins/NavigationContext');
var StateContext = _dereq_('../mixins/StateContext');
var Scrolling = _dereq_('../mixins/Scrolling');
var createRoutesFromChildren = _dereq_('./createRoutesFromChildren');
var supportsHistory = _dereq_('./supportsHistory');
var Transition = _dereq_('./Transition');
var PropTypes = _dereq_('./PropTypes');
var Redirect = _dereq_('./Redirect');
var Cancellation = _dereq_('./Cancellation');
var Path = _dereq_('./Path');
/**
* The default location for new routers.
*/
var DEFAULT_LOCATION = canUseDOM ? HashLocation : '/';
/**
* The default scroll behavior for new routers.
*/
var DEFAULT_SCROLL_BEHAVIOR = canUseDOM ? ImitateBrowserBehavior : null;
/**
* The default error handler for new routers.
*/
function defaultErrorHandler(error) {
// Throw so we don't silently swallow async errors.
throw error; // This error probably originated in a transition hook.
}
/**
* The default aborted transition handler for new routers.
*/
function defaultAbortHandler(abortReason, location) {
if (typeof location === 'string')
throw new Error('Unhandled aborted transition! Reason: ' + abortReason);
if (abortReason instanceof Cancellation) {
return;
} else if (abortReason instanceof Redirect) {
location.replace(this.makePath(abortReason.to, abortReason.params, abortReason.query));
} else {
location.pop();
}
}
function findMatch(pathname, routes, defaultRoute, notFoundRoute) {
var match, route, params;
for (var i = 0, len = routes.length; i < len; ++i) {
route = routes[i];
// Check the subtree first to find the most deeply-nested match.
match = findMatch(pathname, route.childRoutes, route.defaultRoute, route.notFoundRoute);
if (match != null) {
match.routes.unshift(route);
return match;
}
// No routes in the subtree matched, so check this route.
params = Path.extractParams(route.path, pathname);
if (params)
return createMatch(route, params);
}
// No routes matched, so try the default route if there is one.
if (defaultRoute && (params = Path.extractParams(defaultRoute.path, pathname)))
return createMatch(defaultRoute, params);
// Last attempt: does the "not found" route match?
if (notFoundRoute && (params = Path.extractParams(notFoundRoute.path, pathname)))
return createMatch(notFoundRoute, params);
return match;
}
function createMatch(route, params) {
return { routes: [ route ], params: params };
}
function hasMatch(routes, route, prevParams, nextParams) {
return routes.some(function (r) {
if (r !== route)
return false;
var paramNames = route.paramNames;
var paramName;
for (var i = 0, len = paramNames.length; i < len; ++i) {
paramName = paramNames[i];
if (nextParams[paramName] !== prevParams[paramName])
return false;
}
return true;
});
}
/**
* Creates and returns a new router using the given options. A router
* is a ReactComponent class that knows how to react to changes in the
* URL and keep the contents of the page in sync.
*
* Options may be any of the following:
*
* - routes (required) The route config
* - location The location to use. Defaults to HashLocation when
* the DOM is available, "/" otherwise
* - scrollBehavior The scroll behavior to use. Defaults to ImitateBrowserBehavior
* when the DOM is available, null otherwise
* - onError A function that is used to handle errors
* - onAbort A function that is used to handle aborted transitions
*
* When rendering in a server-side environment, the location should simply
* be the URL path that was used in the request, including the query string.
*/
function createRouter(options) {
options = options || {};
if (typeof options === 'function') {
options = { routes: options }; // Router.create(<Route>)
} else if (Array.isArray(options)) {
options = { routes: options }; // Router.create([ <Route>, <Route> ])
}
var routes = [];
var namedRoutes = {};
var components = [];
var location = options.location || DEFAULT_LOCATION;
var scrollBehavior = options.scrollBehavior || DEFAULT_SCROLL_BEHAVIOR;
var onError = options.onError || defaultErrorHandler;
var onAbort = options.onAbort || defaultAbortHandler;
var state = {};
var nextState = {};
var pendingTransition = null;
function updateState() {
state = nextState;
nextState = {};
}
// Automatically fall back to full page refreshes in
// browsers that don't support the HTML history API.
if (location === HistoryLocation && !supportsHistory())
location = RefreshLocation;
var router = React.createClass({
displayName: 'Router',
mixins: [ NavigationContext, StateContext, Scrolling ],
statics: {
defaultRoute: null,
notFoundRoute: null,
/**
* Adds routes to this router from the given children object (see ReactChildren).
*/
addRoutes: function (children) {
routes.push.apply(routes, createRoutesFromChildren(children, this, namedRoutes));
},
/**
* Returns an absolute URL path created from the given route
* name, URL parameters, and query.
*/
makePath: function (to, params, query) {
var path;
if (Path.isAbsolute(to)) {
path = Path.normalize(to);
} else {
var route = namedRoutes[to];
invariant(
route,
'Unable to find <Route name="%s">',
to
);
path = route.path;
}
return Path.withQuery(Path.injectParams(path, params), query);
},
/**
* Returns a string that may safely be used as the href of a link
* to the route with the given name, URL parameters, and query.
*/
makeHref: function (to, params, query) {
var path = this.makePath(to, params, query);
return (location === HashLocation) ? '#' + path : path;
},
/**
* Transitions to the URL specified in the arguments by pushing
* a new URL onto the history stack.
*/
transitionTo: function (to, params, query) {
invariant(
typeof location !== 'string',
'You cannot use transitionTo with a static location'
);
var path = this.makePath(to, params, query);
if (pendingTransition) {
// Replace so pending location does not stay in history.
location.replace(path);
} else {
location.push(path);
}
},
/**
* Transitions to the URL specified in the arguments by replacing
* the current URL in the history stack.
*/
replaceWith: function (to, params, query) {
invariant(
typeof location !== 'string',
'You cannot use replaceWith with a static location'
);
location.replace(this.makePath(to, params, query));
},
/**
* Transitions to the previous URL.
*/
goBack: function () {
invariant(
typeof location !== 'string',
'You cannot use goBack with a static location'
);
location.pop();
},
/**
* Performs a match of the given pathname against this router and returns an object
* with the { routes, params } that match. Returns null if no match can be made.
*/
match: function (pathname) {
return findMatch(pathname, routes, this.defaultRoute, this.notFoundRoute) || null;
},
/**
* Performs a transition to the given path and calls callback(error, abortReason)
* when the transition is finished. If both arguments are null the router's state
* was updated. Otherwise the transition did not complete.
*
* In a transition, a router first determines which routes are involved by beginning
* with the current route, up the route tree to the first parent route that is shared
* with the destination route, and back down the tree to the destination route. The
* willTransitionFrom hook is invoked on all route handlers we're transitioning away
* from, in reverse nesting order. Likewise, the willTransitionTo hook is invoked on
* all route handlers we're transitioning to.
*
* Both willTransitionFrom and willTransitionTo hooks may either abort or redirect the
* transition. To resolve asynchronously, they may use transition.wait(promise). If no
* hooks wait, the transition is fully synchronous.
*/
dispatch: function (path, action, callback) {
if (pendingTransition) {
pendingTransition.abort(new Cancellation);
pendingTransition = null;
}
var prevPath = state.path;
if (prevPath === path)
return; // Nothing to do!
// Record the scroll position as early as possible to
// get it before browsers try update it automatically.
if (prevPath && action !== LocationActions.REPLACE)
this.recordScrollPosition(prevPath);
var pathname = Path.withoutQuery(path);
var match = this.match(pathname);
warning(
match != null,
'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your routes',
path, path
);
if (match == null)
match = {};
var prevRoutes = state.routes || [];
var prevParams = state.params || {};
var nextRoutes = match.routes || [];
var nextParams = match.params || {};
var nextQuery = Path.extractQuery(path) || {};
var fromRoutes, toRoutes;
if (prevRoutes.length) {
fromRoutes = prevRoutes.filter(function (route) {
return !hasMatch(nextRoutes, route, prevParams, nextParams);
});
toRoutes = nextRoutes.filter(function (route) {
return !hasMatch(prevRoutes, route, prevParams, nextParams);
});
} else {
fromRoutes = [];
toRoutes = nextRoutes;
}
var transition = new Transition(path, this.replaceWith.bind(this, path));
pendingTransition = transition;
transition.from(fromRoutes, components, function (error) {
if (error || transition.isAborted)
return callback.call(router, error, transition);
transition.to(toRoutes, nextParams, nextQuery, function (error) {
if (error || transition.isAborted)
return callback.call(router, error, transition);
nextState.path = path;
nextState.action = action;
nextState.pathname = pathname;
nextState.routes = nextRoutes;
nextState.params = nextParams;
nextState.query = nextQuery;
callback.call(router, null, transition);
});
});
},
/**
* Starts this router and calls callback(router, state) when the route changes.
*
* If the router's location is static (i.e. a URL path in a server environment)
* the callback is called only once. Otherwise, the location should be one of the
* Router.*Location objects (e.g. Router.HashLocation or Router.HistoryLocation).
*/
run: function (callback) {
function dispatchHandler(error, transition) {
pendingTransition = null;
if (error) {
onError.call(router, error);
} else if (transition.isAborted) {
onAbort.call(router, transition.abortReason, location);
} else {
callback.call(router, router, nextState);
}
}
if (typeof location === 'string') {
warning(
!canUseDOM || "production" === 'test',
'You should not use a static location in a DOM environment because ' +
'the router will not be kept in sync with the current URL'
);
// Dispatch the location.
router.dispatch(location, null, dispatchHandler);
} else {
invariant(
canUseDOM,
'You cannot use %s in a non-DOM environment',
location
);
// Listen for changes to the location.
function changeListener(change) {
router.dispatch(change.path, change.type, dispatchHandler);
}
if (location.addChangeListener)
location.addChangeListener(changeListener);
// Bootstrap using the current path.
router.dispatch(location.getCurrentPath(), null, dispatchHandler);
}
}
},
propTypes: {
children: PropTypes.falsy
},
getLocation: function () {
return location;
},
getScrollBehavior: function () {
return scrollBehavior;
},
getRouteAtDepth: function (depth) {
var routes = this.state.routes;
return routes && routes[depth];
},
getRouteComponents: function () {
return components;
},
getInitialState: function () {
updateState();
return state;
},
componentWillReceiveProps: function () {
updateState();
this.setState(state);
},
render: function () {
return this.getRouteAtDepth(0) ? React.createElement(RouteHandler, this.props) : null;
},
childContextTypes: {
getRouteAtDepth: React.PropTypes.func.isRequired,
getRouteComponents: React.PropTypes.func.isRequired,
routeHandlers: React.PropTypes.array.isRequired
},
getChildContext: function () {
return {
getRouteComponents: this.getRouteComponents,
getRouteAtDepth: this.getRouteAtDepth,
routeHandlers: [ this ]
};
}
});
if (options.routes)
router.addRoutes(options.routes);
return router;
}
module.exports = createRouter;
},{"../actions/LocationActions":1,"../behaviors/ImitateBrowserBehavior":2,"../components/RouteHandler":9,"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../mixins/NavigationContext":16,"../mixins/Scrolling":17,"../mixins/StateContext":19,"./Cancellation":20,"./Path":21,"./PropTypes":23,"./Redirect":24,"./Transition":25,"./createRoutesFromChildren":27,"./supportsHistory":31,"react/lib/ExecutionEnvironment":37,"react/lib/invariant":41,"react/lib/warning":42}],27:[function(_dereq_,module,exports){
var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null);
var warning = _dereq_('react/lib/warning');
var invariant = _dereq_('react/lib/invariant');
var DefaultRoute = _dereq_('../components/DefaultRoute');
var NotFoundRoute = _dereq_('../components/NotFoundRoute');
var Redirect = _dereq_('../components/Redirect');
var Route = _dereq_('../components/Route');
var Path = _dereq_('./Path');
var CONFIG_ELEMENT_TYPES = [
DefaultRoute.type,
NotFoundRoute.type,
Redirect.type,
Route.type
];
function createRedirectHandler(to, _params, _query) {
return React.createClass({
statics: {
willTransitionTo: function (transition, params, query) {
transition.redirect(to, _params || params, _query || query);
}
},
render: function () {
return null;
}
});
}
function checkPropTypes(componentName, propTypes, props) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, componentName);
if (error instanceof Error)
warning(false, error.message);
}
}
}
function createRoute(element, parentRoute, namedRoutes) {
var type = element.type;
var props = element.props;
var componentName = (type && type.displayName) || 'UnknownComponent';
invariant(
CONFIG_ELEMENT_TYPES.indexOf(type) !== -1,
'Unrecognized route configuration element "<%s>"',
componentName
);
if (type.propTypes)
checkPropTypes(componentName, type.propTypes, props);
var route = { name: props.name };
if (props.ignoreScrollBehavior) {
route.ignoreScrollBehavior = true;
}
if (type === Redirect.type) {
route.handler = createRedirectHandler(props.to, props.params, props.query);
props.path = props.path || props.from || '*';
} else {
route.handler = props.handler;
}
var parentPath = (parentRoute && parentRoute.path) || '/';
if ((props.path || props.name) && type !== DefaultRoute.type && type !== NotFoundRoute.type) {
var path = props.path || props.name;
// Relative paths extend their parent.
if (!Path.isAbsolute(path))
path = Path.join(parentPath, path);
route.path = Path.normalize(path);
} else {
route.path = parentPath;
if (type === NotFoundRoute.type)
route.path += '*';
}
route.paramNames = Path.extractParamNames(route.path);
// Make sure the route's path has all params its parent needs.
if (parentRoute && Array.isArray(parentRoute.paramNames)) {
parentRoute.paramNames.forEach(function (paramName) {
invariant(
route.paramNames.indexOf(paramName) !== -1,
'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',
route.path, paramName, parentRoute.path
);
});
}
// Make sure the route can be looked up by <Link>s.
if (props.name) {
invariant(
namedRoutes[props.name] == null,
'You cannot use the name "%s" for more than one route',
props.name
);
namedRoutes[props.name] = route;
}
// Handle <NotFoundRoute>.
if (type === NotFoundRoute.type) {
invariant(
parentRoute,
'<NotFoundRoute> must have a parent <Route>'
);
invariant(
parentRoute.notFoundRoute == null,
'You may not have more than one <NotFoundRoute> per <Route>'
);
parentRoute.notFoundRoute = route;
return null;
}
// Handle <DefaultRoute>.
if (type === DefaultRoute.type) {
invariant(
parentRoute,
'<DefaultRoute> must have a parent <Route>'
);
invariant(
parentRoute.defaultRoute == null,
'You may not have more than one <DefaultRoute> per <Route>'
);
parentRoute.defaultRoute = route;
return null;
}
route.childRoutes = createRoutesFromChildren(props.children, route, namedRoutes);
return route;
}
/**
* Creates and returns an array of route objects from the given ReactChildren.
*/
function createRoutesFromChildren(children, parentRoute, namedRoutes) {
var routes = [];
React.Children.forEach(children, function (child) {
// Exclude <DefaultRoute>s and <NotFoundRoute>s.
if (child = createRoute(child, parentRoute, namedRoutes))
routes.push(child);
});
return routes;
}
module.exports = createRoutesFromChildren;
},{"../components/DefaultRoute":4,"../components/NotFoundRoute":6,"../components/Redirect":7,"../components/Route":8,"./Path":21,"react/lib/invariant":41,"react/lib/warning":42}],28:[function(_dereq_,module,exports){
var invariant = _dereq_('react/lib/invariant');
var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM;
/**
* Returns the current scroll position of the window as { x, y }.
*/
function getWindowScrollPosition() {
invariant(
canUseDOM,
'Cannot get current scroll position without a DOM'
);
return {
x: window.scrollX,
y: window.scrollY
};
}
module.exports = getWindowScrollPosition;
},{"react/lib/ExecutionEnvironment":37,"react/lib/invariant":41}],29:[function(_dereq_,module,exports){
function reversedArray(array) {
return array.slice(0).reverse();
}
module.exports = reversedArray;
},{}],30:[function(_dereq_,module,exports){
var createRouter = _dereq_('./createRouter');
/**
* A high-level convenience method that creates, configures, and
* runs a router in one shot. The method signature is:
*
* Router.run(routes[, location ], callback);
*
* Using `window.location.hash` to manage the URL, you could do:
*
* Router.run(routes, function (Handler) {
* React.render(<Handler/>, document.body);
* });
*
* Using HTML5 history and a custom "cursor" prop:
*
* Router.run(routes, Router.HistoryLocation, function (Handler) {
* React.render(<Handler cursor={cursor}/>, document.body);
* });
*
* Returns the newly created router.
*
* Note: If you need to specify further options for your router such
* as error/abort handling or custom scroll behavior, use Router.create
* instead.
*
* var router = Router.create(options);
* router.run(function (Handler) {
* // ...
* });
*/
function runRouter(routes, location, callback) {
if (typeof location === 'function') {
callback = location;
location = null;
}
var router = createRouter({
routes: routes,
location: location
});
router.run(callback);
return router;
}
module.exports = runRouter;
},{"./createRouter":26}],31:[function(_dereq_,module,exports){
function supportsHistory() {
/*! taken from modernizr
* https://github.com/Modernizr/Modernizr/blob/master/LICENSE
* https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js
*/
var ua = navigator.userAgent;
if ((ua.indexOf('Android 2.') !== -1 ||
(ua.indexOf('Android 4.0') !== -1)) &&
ua.indexOf('Mobile Safari') !== -1 &&
ua.indexOf('Chrome') === -1) {
return false;
}
return (window.history && 'pushState' in window.history);
}
module.exports = supportsHistory;
},{}],32:[function(_dereq_,module,exports){
module.exports = _dereq_('./lib');
},{"./lib":33}],33:[function(_dereq_,module,exports){
// Load modules
var Stringify = _dereq_('./stringify');
var Parse = _dereq_('./parse');
// Declare internals
var internals = {};
module.exports = {
stringify: Stringify,
parse: Parse
};
},{"./parse":34,"./stringify":35}],34:[function(_dereq_,module,exports){
// Load modules
var Utils = _dereq_('./utils');
// Declare internals
var internals = {
delimiter: '&',
depth: 5,
arrayLimit: 20,
parameterLimit: 1000
};
internals.parseValues = function (str, options) {
var obj = {};
var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit);
for (var i = 0, il = parts.length; i < il; ++i) {
var part = parts[i];
var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1;
if (pos === -1) {
obj[Utils.decode(part)] = '';
}
else {
var key = Utils.decode(part.slice(0, pos));
var val = Utils.decode(part.slice(pos + 1));
if (!obj[key]) {
obj[key] = val;
}
else {
obj[key] = [].concat(obj[key]).concat(val);
}
}
}
return obj;
};
internals.parseObject = function (chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj = {};
if (root === '[]') {
obj = [];
obj = obj.concat(internals.parseObject(chain, val, options));
}
else {
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 &&
index <= options.arrayLimit) {
obj = [];
obj[index] = internals.parseObject(chain, val, options);
}
else {
obj[cleanRoot] = internals.parseObject(chain, val, options);
}
}
return obj;
};
internals.parseKeys = function (key, val, options) {
if (!key) {
return;
}
// The regex chunks
var parent = /^([^\[\]]*)/;
var child = /(\[[^\[\]]*\])/g;
// Get the parent
var segment = parent.exec(key);
// Don't allow them to overwrite object prototype properties
if (Object.prototype.hasOwnProperty(segment[1])) {
return;
}
// Stash the parent if it exists
var keys = [];
if (segment[1]) {
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;
if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) {
keys.push(segment[1]);
}
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return internals.parseObject(keys, val, options);
};
module.exports = function (str, options) {
if (str === '' ||
str === null ||
typeof str === 'undefined') {
return {};
}
options = options || {};
options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : internals.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit;
var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str;
var obj = {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0, il = keys.length; i < il; ++i) {
var key = keys[i];
var newObj = internals.parseKeys(key, tempObj[key], options);
obj = Utils.merge(obj, newObj);
}
return Utils.compact(obj);
};
},{"./utils":36}],35:[function(_dereq_,module,exports){
// Load modules
var Utils = _dereq_('./utils');
// Declare internals
var internals = {
delimiter: '&'
};
internals.stringify = function (obj, prefix) {
if (Utils.isBuffer(obj)) {
obj = obj.toString();
}
else if (obj instanceof Date) {
obj = obj.toISOString();
}
else if (obj === null) {
obj = '';
}
if (typeof obj === 'string' ||
typeof obj === 'number' ||
typeof obj === 'boolean') {
return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)];
}
var values = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']'));
}
}
return values;
};
module.exports = function (obj, options) {
options = options || {};
var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter;
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys = keys.concat(internals.stringify(obj[key], key));
}
}
return keys.join(delimiter);
};
},{"./utils":36}],36:[function(_dereq_,module,exports){
// Load modules
// Declare internals
var internals = {};
exports.arrayToObject = function (source) {
var obj = {};
for (var i = 0, il = source.length; i < il; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source) {
if (!source) {
return target;
}
if (Array.isArray(source)) {
for (var i = 0, il = source.length; i < il; ++i) {
if (typeof source[i] !== 'undefined') {
if (typeof target[i] === 'object') {
target[i] = exports.merge(target[i], source[i]);
}
else {
target[i] = source[i];
}
}
}
return target;
}
if (Array.isArray(target)) {
if (typeof source !== 'object') {
target.push(source);
return target;
}
else {
target = exports.arrayToObject(target);
}
}
var keys = Object.keys(source);
for (var k = 0, kl = keys.length; k < kl; ++k) {
var key = keys[k];
var value = source[key];
if (value &&
typeof value === 'object') {
if (!target[key]) {
target[key] = value;
}
else {
target[key] = exports.merge(target[key], value);
}
}
else {
target[key] = value;
}
}
return target;
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.compact = function (obj, refs) {
if (typeof obj !== 'object' ||
obj === null) {
return obj;
}
refs = refs || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0, l = obj.length; i < l; ++i) {
if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
for (var i = 0, il = keys.length; i < il; ++i) {
var key = keys[i];
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 (typeof Buffer !== 'undefined') {
return Buffer.isBuffer(obj);
}
else {
return false;
}
};
},{}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
/*jslint evil: true */
"use strict";
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners:
canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],38:[function(_dereq_,module,exports){
/**
* Copyright 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
};
module.exports = assign;
},{}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule cx
*/
/**
* This function is used to mark string literals representing CSS class names
* so that they can be transformed statically. This allows for modularization
* and minification of CSS class names.
*
* In static_upstream, this function is actually implemented, but it should
* eventually be replaced with something more descriptive, and the transform
* that is used in the main stack should be ported for use elsewhere.
*
* @param string|object className to modularize, or an object of key/values.
* In the object case, the values are conditions that
* determine if the className keys should be included.
* @param [string ...] Variable list of classNames in the string case.
* @return string Renderable space-separated CSS className.
*/
function cx(classNames) {
if (typeof classNames == 'object') {
return Object.keys(classNames).filter(function(className) {
return classNames[className];
}).join(' ');
} else {
return Array.prototype.join.call(arguments, ' ');
}
}
module.exports = cx;
},{}],40:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule emptyFunction
*/
function makeEmptyFunction(arg) {
return function() {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
function emptyFunction() {}
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function() { return this; };
emptyFunction.thatReturnsArgument = function(arg) { return arg; };
module.exports = emptyFunction;
},{}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
"use strict";
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if ("production" !== "production") {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
'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;
},{}],42:[function(_dereq_,module,exports){
/**
* Copyright 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule warning
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("production" !== "production") {
warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
var argIndex = 0;
console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}));
}
};
}
module.exports = warning;
},{"./emptyFunction":40}],43:[function(_dereq_,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function (_dereq_) {
var makePromise = _dereq_('./makePromise');
var Scheduler = _dereq_('./Scheduler');
var async = _dereq_('./async');
return makePromise({
scheduler: new Scheduler(async)
});
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); });
},{"./Scheduler":45,"./async":46,"./makePromise":47}],44:[function(_dereq_,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
/**
* Circular queue
* @param {number} capacityPow2 power of 2 to which this queue's capacity
* will be set initially. eg when capacityPow2 == 3, queue capacity
* will be 8.
* @constructor
*/
function Queue(capacityPow2) {
this.head = this.tail = this.length = 0;
this.buffer = new Array(1 << capacityPow2);
}
Queue.prototype.push = function(x) {
if(this.length === this.buffer.length) {
this._ensureCapacity(this.length * 2);
}
this.buffer[this.tail] = x;
this.tail = (this.tail + 1) & (this.buffer.length - 1);
++this.length;
return this.length;
};
Queue.prototype.shift = function() {
var x = this.buffer[this.head];
this.buffer[this.head] = void 0;
this.head = (this.head + 1) & (this.buffer.length - 1);
--this.length;
return x;
};
Queue.prototype._ensureCapacity = function(capacity) {
var head = this.head;
var buffer = this.buffer;
var newBuffer = new Array(capacity);
var i = 0;
var len;
if(head === 0) {
len = this.length;
for(; i<len; ++i) {
newBuffer[i] = buffer[i];
}
} else {
capacity = buffer.length;
len = this.tail;
for(; head<capacity; ++i, ++head) {
newBuffer[i] = buffer[head];
}
for(head=0; head<len; ++i, ++head) {
newBuffer[i] = buffer[head];
}
}
this.buffer = newBuffer;
this.head = 0;
this.tail = this.length;
};
return Queue;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}],45:[function(_dereq_,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(_dereq_) {
var Queue = _dereq_('./Queue');
// Credit to Twisol (https://github.com/Twisol) for suggesting
// this type of extensible queue + trampoline approach for next-tick conflation.
/**
* Async task scheduler
* @param {function} async function to schedule a single async function
* @constructor
*/
function Scheduler(async) {
this._async = async;
this._queue = new Queue(15);
this._afterQueue = new Queue(5);
this._running = false;
var self = this;
this.drain = function() {
self._drain();
};
}
/**
* Enqueue a task
* @param {{ run:function }} task
*/
Scheduler.prototype.enqueue = function(task) {
this._add(this._queue, task);
};
/**
* Enqueue a task to run after the main task queue
* @param {{ run:function }} task
*/
Scheduler.prototype.afterQueue = function(task) {
this._add(this._afterQueue, task);
};
/**
* Drain the handler queue entirely, and then the after queue
*/
Scheduler.prototype._drain = function() {
runQueue(this._queue);
this._running = false;
runQueue(this._afterQueue);
};
/**
* Add a task to the q, and schedule drain if not already scheduled
* @param {Queue} queue
* @param {{run:function}} task
* @private
*/
Scheduler.prototype._add = function(queue, task) {
queue.push(task);
if(!this._running) {
this._running = true;
this._async(this.drain);
}
};
/**
* Run all the tasks in the q
* @param queue
*/
function runQueue(queue) {
while(queue.length > 0) {
queue.shift().run();
}
}
return Scheduler;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); }));
},{"./Queue":44}],46:[function(_dereq_,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(_dereq_) {
// Sniff "best" async scheduling option
// Prefer process.nextTick or MutationObserver, then check for
// vertx and finally fall back to setTimeout
/*jshint maxcomplexity:6*/
/*global process,document,setTimeout,MutationObserver,WebKitMutationObserver*/
var nextTick, MutationObs;
if (typeof process !== 'undefined' && process !== null &&
typeof process.nextTick === 'function') {
nextTick = function(f) {
process.nextTick(f);
};
} else if (MutationObs =
(typeof MutationObserver === 'function' && MutationObserver) ||
(typeof WebKitMutationObserver === 'function' && WebKitMutationObserver)) {
nextTick = (function (document, MutationObserver) {
var scheduled;
var el = document.createElement('div');
var o = new MutationObserver(run);
o.observe(el, { attributes: true });
function run() {
var f = scheduled;
scheduled = void 0;
f();
}
return function (f) {
scheduled = f;
el.setAttribute('class', 'x');
};
}(document, MutationObs));
} else {
nextTick = (function(cjsRequire) {
var vertx;
try {
// vert.x 1.x || 2.x
vertx = cjsRequire('vertx');
} catch (ignore) {}
if (vertx) {
if (typeof vertx.runOnLoop === 'function') {
return vertx.runOnLoop;
}
if (typeof vertx.runOnContext === 'function') {
return vertx.runOnContext;
}
}
// capture setTimeout to avoid being caught by fake timers
// used in time based tests
var capturedSetTimeout = setTimeout;
return function (t) {
capturedSetTimeout(t, 0);
};
}(_dereq_));
}
return nextTick;
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); }));
},{}],47:[function(_dereq_,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function() {
return function makePromise(environment) {
var tasks = environment.scheduler;
var objectCreate = Object.create ||
function(proto) {
function Child() {}
Child.prototype = proto;
return new Child();
};
/**
* Create a promise whose fate is determined by resolver
* @constructor
* @returns {Promise} promise
* @name Promise
*/
function Promise(resolver, handler) {
this._handler = resolver === Handler ? handler : init(resolver);
}
/**
* Run the supplied resolver
* @param resolver
* @returns {Pending}
*/
function init(resolver) {
var handler = new Pending();
try {
resolver(promiseResolve, promiseReject, promiseNotify);
} catch (e) {
promiseReject(e);
}
return handler;
/**
* Transition from pre-resolution state to post-resolution state, notifying
* all listeners of the ultimate fulfillment or rejection
* @param {*} x resolution value
*/
function promiseResolve (x) {
handler.resolve(x);
}
/**
* Reject this promise with reason, which will be used verbatim
* @param {Error|*} reason rejection reason, strongly suggested
* to be an Error type
*/
function promiseReject (reason) {
handler.reject(reason);
}
/**
* Issue a progress event, notifying all progress listeners
* @param {*} x progress event payload to pass to all listeners
*/
function promiseNotify (x) {
handler.notify(x);
}
}
// Creation
Promise.resolve = resolve;
Promise.reject = reject;
Promise.never = never;
Promise._defer = defer;
Promise._handler = getHandler;
/**
* Returns a trusted promise. If x is already a trusted promise, it is
* returned, otherwise returns a new trusted Promise which follows x.
* @param {*} x
* @return {Promise} promise
*/
function resolve(x) {
return isPromise(x) ? x
: new Promise(Handler, new Async(getHandler(x)));
}
/**
* Return a reject promise with x as its reason (x is used verbatim)
* @param {*} x
* @returns {Promise} rejected promise
*/
function reject(x) {
return new Promise(Handler, new Async(new Rejected(x)));
}
/**
* Return a promise that remains pending forever
* @returns {Promise} forever-pending promise.
*/
function never() {
return foreverPendingPromise; // Should be frozen
}
/**
* Creates an internal {promise, resolver} pair
* @private
* @returns {Promise}
*/
function defer() {
return new Promise(Handler, new Pending());
}
// Transformation and flow control
/**
* Transform this promise's fulfillment value, returning a new Promise
* for the transformed result. If the promise cannot be fulfilled, onRejected
* is called with the reason. onProgress *may* be called with updates toward
* this promise's fulfillment.
* @param {function=} onFulfilled fulfillment handler
* @param {function=} onRejected rejection handler
* @deprecated @param {function=} onProgress progress handler
* @return {Promise} new promise
*/
Promise.prototype.then = function(onFulfilled, onRejected) {
var parent = this._handler;
var state = parent.join().state();
if ((typeof onFulfilled !== 'function' && state > 0) ||
(typeof onRejected !== 'function' && state < 0)) {
// Short circuit: value will not change, simply share handler
return new this.constructor(Handler, parent);
}
var p = this._beget();
var child = p._handler;
parent.chain(child, parent.receiver, onFulfilled, onRejected,
arguments.length > 2 ? arguments[2] : void 0);
return p;
};
/**
* If this promise cannot be fulfilled due to an error, call onRejected to
* handle the error. Shortcut for .then(undefined, onRejected)
* @param {function?} onRejected
* @return {Promise}
*/
Promise.prototype['catch'] = function(onRejected) {
return this.then(void 0, onRejected);
};
/**
* Creates a new, pending promise of the same type as this promise
* @private
* @returns {Promise}
*/
Promise.prototype._beget = function() {
var parent = this._handler;
var child = new Pending(parent.receiver, parent.join().context);
return new this.constructor(Handler, child);
};
// Array combinators
Promise.all = all;
Promise.race = race;
/**
* Return a promise that will fulfill when all promises in the
* input array have fulfilled, or will reject when one of the
* promises rejects.
* @param {array} promises array of promises
* @returns {Promise} promise for array of fulfillment values
*/
function all(promises) {
/*jshint maxcomplexity:8*/
var resolver = new Pending();
var pending = promises.length >>> 0;
var results = new Array(pending);
var i, h, x, s;
for (i = 0; i < promises.length; ++i) {
x = promises[i];
if (x === void 0 && !(i in promises)) {
--pending;
continue;
}
if (maybeThenable(x)) {
h = getHandlerMaybeThenable(x);
s = h.state();
if (s === 0) {
h.fold(settleAt, i, results, resolver);
} else if (s > 0) {
results[i] = h.value;
--pending;
} else {
unreportRemaining(promises, i+1, h);
resolver.become(h);
break;
}
} else {
results[i] = x;
--pending;
}
}
if(pending === 0) {
resolver.become(new Fulfilled(results));
}
return new Promise(Handler, resolver);
function settleAt(i, x, resolver) {
/*jshint validthis:true*/
this[i] = x;
if(--pending === 0) {
resolver.become(new Fulfilled(this));
}
}
}
function unreportRemaining(promises, start, rejectedHandler) {
var i, h, x;
for(i=start; i<promises.length; ++i) {
x = promises[i];
if(maybeThenable(x)) {
h = getHandlerMaybeThenable(x);
if(h !== rejectedHandler) {
h.visit(h, void 0, h._unreport);
}
}
}
}
/**
* Fulfill-reject competitive race. Return a promise that will settle
* to the same state as the earliest input promise to settle.
*
* WARNING: The ES6 Promise spec requires that race()ing an empty array
* must return a promise that is pending forever. This implementation
* returns a singleton forever-pending promise, the same singleton that is
* returned by Promise.never(), thus can be checked with ===
*
* @param {array} promises array of promises to race
* @returns {Promise} if input is non-empty, a promise that will settle
* to the same outcome as the earliest input promise to settle. if empty
* is empty, returns a promise that will never settle.
*/
function race(promises) {
// Sigh, race([]) is untestable unless we return *something*
// that is recognizable without calling .then() on it.
if(Object(promises) === promises && promises.length === 0) {
return never();
}
var h = new Pending();
var i, x;
for(i=0; i<promises.length; ++i) {
x = promises[i];
if (x !== void 0 && i in promises) {
getHandler(x).visit(h, h.resolve, h.reject);
}
}
return new Promise(Handler, h);
}
// Promise internals
// Below this, everything is @private
/**
* Get an appropriate handler for x, without checking for cycles
* @param {*} x
* @returns {object} handler
*/
function getHandler(x) {
if(isPromise(x)) {
return x._handler.join();
}
return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
}
/**
* Get a handler for thenable x.
* NOTE: You must only call this if maybeThenable(x) == true
* @param {object|function|Promise} x
* @returns {object} handler
*/
function getHandlerMaybeThenable(x) {
return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
}
/**
* Get a handler for potentially untrusted thenable x
* @param {*} x
* @returns {object} handler
*/
function getHandlerUntrusted(x) {
try {
var untrustedThen = x.then;
return typeof untrustedThen === 'function'
? new Thenable(untrustedThen, x)
: new Fulfilled(x);
} catch(e) {
return new Rejected(e);
}
}
/**
* Handler for a promise that is pending forever
* @constructor
*/
function Handler() {}
Handler.prototype.when
= Handler.prototype.become
= Handler.prototype.notify
= Handler.prototype.fail
= Handler.prototype._unreport
= Handler.prototype._report
= noop;
Handler.prototype._state = 0;
Handler.prototype.state = function() {
return this._state;
};
/**
* Recursively collapse handler chain to find the handler
* nearest to the fully resolved value.
* @returns {object} handler nearest the fully resolved value
*/
Handler.prototype.join = function() {
var h = this;
while(h.handler !== void 0) {
h = h.handler;
}
return h;
};
Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
this.when({
resolver: to,
receiver: receiver,
fulfilled: fulfilled,
rejected: rejected,
progress: progress
});
};
Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
};
Handler.prototype.fold = function(f, z, c, to) {
this.visit(to, function(x) {
f.call(c, z, x, this);
}, to.reject, to.notify);
};
/**
* Handler that invokes fail() on any handler it becomes
* @constructor
*/
function FailIfRejected() {}
inherit(Handler, FailIfRejected);
FailIfRejected.prototype.become = function(h) {
h.fail();
};
var failIfRejected = new FailIfRejected();
/**
* Handler that manages a queue of consumers waiting on a pending promise
* @constructor
*/
function Pending(receiver, inheritedContext) {
Promise.createContext(this, inheritedContext);
this.consumers = void 0;
this.receiver = receiver;
this.handler = void 0;
this.resolved = false;
}
inherit(Handler, Pending);
Pending.prototype._state = 0;
Pending.prototype.resolve = function(x) {
this.become(getHandler(x));
};
Pending.prototype.reject = function(x) {
if(this.resolved) {
return;
}
this.become(new Rejected(x));
};
Pending.prototype.join = function() {
if (!this.resolved) {
return this;
}
var h = this;
while (h.handler !== void 0) {
h = h.handler;
if (h === this) {
return this.handler = cycle();
}
}
return h;
};
Pending.prototype.run = function() {
var q = this.consumers;
var handler = this.join();
this.consumers = void 0;
for (var i = 0; i < q.length; ++i) {
handler.when(q[i]);
}
};
Pending.prototype.become = function(handler) {
if(this.resolved) {
return;
}
this.resolved = true;
this.handler = handler;
if(this.consumers !== void 0) {
tasks.enqueue(this);
}
if(this.context !== void 0) {
handler._report(this.context);
}
};
Pending.prototype.when = function(continuation) {
if(this.resolved) {
tasks.enqueue(new ContinuationTask(continuation, this.handler));
} else {
if(this.consumers === void 0) {
this.consumers = [continuation];
} else {
this.consumers.push(continuation);
}
}
};
Pending.prototype.notify = function(x) {
if(!this.resolved) {
tasks.enqueue(new ProgressTask(x, this));
}
};
Pending.prototype.fail = function(context) {
var c = typeof context === 'undefined' ? this.context : context;
this.resolved && this.handler.join().fail(c);
};
Pending.prototype._report = function(context) {
this.resolved && this.handler.join()._report(context);
};
Pending.prototype._unreport = function() {
this.resolved && this.handler.join()._unreport();
};
/**
* Wrap another handler and force it into a future stack
* @param {object} handler
* @constructor
*/
function Async(handler) {
this.handler = handler;
}
inherit(Handler, Async);
Async.prototype.when = function(continuation) {
tasks.enqueue(new ContinuationTask(continuation, this));
};
Async.prototype._report = function(context) {
this.join()._report(context);
};
Async.prototype._unreport = function() {
this.join()._unreport();
};
/**
* Handler that wraps an untrusted thenable and assimilates it in a future stack
* @param {function} then
* @param {{then: function}} thenable
* @constructor
*/
function Thenable(then, thenable) {
Pending.call(this);
tasks.enqueue(new AssimilateTask(then, thenable, this));
}
inherit(Pending, Thenable);
/**
* Handler for a fulfilled promise
* @param {*} x fulfillment value
* @constructor
*/
function Fulfilled(x) {
Promise.createContext(this);
this.value = x;
}
inherit(Handler, Fulfilled);
Fulfilled.prototype._state = 1;
Fulfilled.prototype.fold = function(f, z, c, to) {
runContinuation3(f, z, this, c, to);
};
Fulfilled.prototype.when = function(cont) {
runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
};
var errorId = 0;
/**
* Handler for a rejected promise
* @param {*} x rejection reason
* @constructor
*/
function Rejected(x) {
Promise.createContext(this);
this.id = ++errorId;
this.value = x;
this.handled = false;
this.reported = false;
this._report();
}
inherit(Handler, Rejected);
Rejected.prototype._state = -1;
Rejected.prototype.fold = function(f, z, c, to) {
to.become(this);
};
Rejected.prototype.when = function(cont) {
if(typeof cont.rejected === 'function') {
this._unreport();
}
runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
};
Rejected.prototype._report = function(context) {
tasks.afterQueue(new ReportTask(this, context));
};
Rejected.prototype._unreport = function() {
this.handled = true;
tasks.afterQueue(new UnreportTask(this));
};
Rejected.prototype.fail = function(context) {
Promise.onFatalRejection(this, context === void 0 ? this.context : context);
};
function ReportTask(rejection, context) {
this.rejection = rejection;
this.context = context;
}
ReportTask.prototype.run = function() {
if(!this.rejection.handled) {
this.rejection.reported = true;
Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
}
};
function UnreportTask(rejection) {
this.rejection = rejection;
}
UnreportTask.prototype.run = function() {
if(this.rejection.reported) {
Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
}
};
// Unhandled rejection hooks
// By default, everything is a noop
// TODO: Better names: "annotate"?
Promise.createContext
= Promise.enterContext
= Promise.exitContext
= Promise.onPotentiallyUnhandledRejection
= Promise.onPotentiallyUnhandledRejectionHandled
= Promise.onFatalRejection
= noop;
// Errors and singletons
var foreverPendingHandler = new Handler();
var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
function cycle() {
return new Rejected(new TypeError('Promise cycle'));
}
// Task runners
/**
* Run a single consumer
* @constructor
*/
function ContinuationTask(continuation, handler) {
this.continuation = continuation;
this.handler = handler;
}
ContinuationTask.prototype.run = function() {
this.handler.join().when(this.continuation);
};
/**
* Run a queue of progress handlers
* @constructor
*/
function ProgressTask(value, handler) {
this.handler = handler;
this.value = value;
}
ProgressTask.prototype.run = function() {
var q = this.handler.consumers;
if(q === void 0) {
return;
}
for (var c, i = 0; i < q.length; ++i) {
c = q[i];
runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
}
};
/**
* Assimilate a thenable, sending it's value to resolver
* @param {function} then
* @param {object|function} thenable
* @param {object} resolver
* @constructor
*/
function AssimilateTask(then, thenable, resolver) {
this._then = then;
this.thenable = thenable;
this.resolver = resolver;
}
AssimilateTask.prototype.run = function() {
var h = this.resolver;
tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
function _resolve(x) { h.resolve(x); }
function _reject(x) { h.reject(x); }
function _notify(x) { h.notify(x); }
};
function tryAssimilate(then, thenable, resolve, reject, notify) {
try {
then.call(thenable, resolve, reject, notify);
} catch (e) {
reject(e);
}
}
// Other helpers
/**
* @param {*} x
* @returns {boolean} true iff x is a trusted Promise
*/
function isPromise(x) {
return x instanceof Promise;
}
/**
* Test just enough to rule out primitives, in order to take faster
* paths in some code
* @param {*} x
* @returns {boolean} false iff x is guaranteed *not* to be a thenable
*/
function maybeThenable(x) {
return (typeof x === 'object' || typeof x === 'function') && x !== null;
}
function runContinuation1(f, h, receiver, next) {
if(typeof f !== 'function') {
return next.become(h);
}
Promise.enterContext(h);
tryCatchReject(f, h.value, receiver, next);
Promise.exitContext();
}
function runContinuation3(f, x, h, receiver, next) {
if(typeof f !== 'function') {
return next.become(h);
}
Promise.enterContext(h);
tryCatchReject3(f, x, h.value, receiver, next);
Promise.exitContext();
}
function runNotify(f, x, h, receiver, next) {
if(typeof f !== 'function') {
return next.notify(x);
}
Promise.enterContext(h);
tryCatchReturn(f, x, receiver, next);
Promise.exitContext();
}
/**
* Return f.call(thisArg, x), or if it throws return a rejected promise for
* the thrown exception
*/
function tryCatchReject(f, x, thisArg, next) {
try {
next.become(getHandler(f.call(thisArg, x)));
} catch(e) {
next.become(new Rejected(e));
}
}
/**
* Same as above, but includes the extra argument parameter.
*/
function tryCatchReject3(f, x, y, thisArg, next) {
try {
f.call(thisArg, x, y, next);
} catch(e) {
next.become(new Rejected(e));
}
}
/**
* Return f.call(thisArg, x), or if it throws, *return* the exception
*/
function tryCatchReturn(f, x, thisArg, next) {
try {
next.notify(f.call(thisArg, x));
} catch(e) {
next.notify(e);
}
}
function inherit(Parent, Child) {
Child.prototype = objectCreate(Parent.prototype);
Child.prototype.constructor = Child;
}
function noop() {}
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
},{}]},{},[10])
(10)
}); |
build/webpack.config.server.js | leviluo/oneToone | import webpackConfig from './webpack.config'
import clone from 'clone'
import config from '../config'
import _debug from 'debug'
import fs from 'fs'
const debug = _debug('app:webpack:config')
const paths = config.utils_paths
debug('Create server configuration.')
const webpackConfigServer = clone(webpackConfig)
webpackConfigServer.name = 'server'
webpackConfigServer.target = 'node'
webpackConfigServer.externals = fs.readdirSync(paths.base('node_modules'))
.concat([
'react-dom/server', 'react/addons'
]).reduce(function (ext, mod) {
ext[mod] = 'commonjs ' + mod
return ext
}, {})
// ------------------------------------
// Entry Points
// ------------------------------------
webpackConfigServer.entry = [
'babel-polyfill',
paths.src(config.entry_server)
]
// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfigServer.output = {
filename: 'server.js',
path: paths.dist(),
library: 'server',
libraryTarget: 'umd',
umdNamedDefine: true
}
export default webpackConfigServer
|
examples/shopping-cart/src/containers/App.js | roth1002/redux | import React from 'react'
import ProductsContainer from './ProductsContainer'
import CartContainer from './CartContainer'
const App = () => (
<div>
<h2>Shopping Cart Example</h2>
<hr/>
<ProductsContainer />
<hr/>
<CartContainer />
</div>
)
export default App
|
src/main/app/src/component/AddMicroservice/AddServiceFields.js | p632-sp-2017/microservice-catalog-frontend | import React from 'react';
import { Field } from 'redux-form';
import FontAwesome from "react-fontawesome";
import './AddService.css';
const setError = (fieldObj, errObj, msg)=>{
if(!fieldObj) {
errObj = "Required";
} else {
errObj = msg;
}
return errObj;
};
/**
* A helper function to validate the various form fields
* @param {Object} values - A object that comprises of the values of the details entered in the add new Microservice form.
* @return {Object} - A Object that specifies all the different errors that are discovered while performing validations.
*/
export const validate = values=>{
const errors = {}
errors.title = setError(values.title, errors.title);
errors.email = setError(values.email, errors.email);
errors.description = setError(values.description, errors.description);
errors.url = setError(values.url, errors.url);
if (values.title !== undefined && values.title.length > 50) {
errors.title = setError(values.title, errors.title, 'Enter 50 characters or less');
}
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = setError(values.email, errors.email, "Invalid email address");
}
if (values.description !== undefined && values.description.length > 250) {
errors.description = setError(values.description, errors.description, "Must be 250 characters or less");
}
return errors
}
/**
* React component for rendering Field
* @param {[type]} props [description]
* @return {[type]} [description]
*/
const renderField = (props) => {
let control = <input {...props.input} className="fieldText" placeholder={props.placeholder} type={props.type} />;
let type=props.input.name.toUpperCase();
if(type === "URL" || type === "DESCRIPTION")
{
control = <textarea {...props.input} className="fieldText" placeholder={props.placeholder} type={props.type} ></textarea>;
}
return <div className="FieldControl"> {control}{props.meta.touched && props.meta.error && <span className="Error">*{props.meta.error}</span>}</div>;
}
/**
* A array that comprises of all the different fields of a Microservice that can be added while creating a new Microservice
* @type {Array}
*/
export let formFieldsData = [
{
serviceData:[
{
name:'title',
placeholder: 'Title',
tooltip: 'Enter 1-50 characters'
},
{
name:'url',
placeholder: 'URL',
tooltip: 'Comma separated URL(s)'
},
{
name:'email',
placeholder: 'Email',
tooltip: 'Valid Email Address'
},
{
name:'description',
placeholder: 'Description',
tooltip: 'Enter 1-250 characters'
}
]}
]
export let fieldHeading = formFieldsData[0].serviceData.map((data, i)=>{
return <div key={i} className='FieldHeading'> {data.placeholder} </div>
})
export let formFields = formFieldsData.map((service,i)=>{
return service.serviceData.map((field)=>{
return <div className="fieldContainer"><div key={i} className='FieldHeading'> {field.placeholder} <sup> <FontAwesome title={field.tooltip} name="question" /> </sup> </div>
<Field name={field.name} type="text" component={renderField} placeholder={field.placeholder} /></div>
})
})
|
scenes/change-account.js | APU-Flow/FlowApp | // change-account.js
// Flow
'use strict';
import React, { Component } from 'react';
import { StyleSheet, Text, Alert, View, TouchableHighlight } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import ModalDropdown from 'react-native-modal-dropdown';
export default class ChangeAccount extends Component {
constructor(props) {
super(props);
// Initialize state variables
this.state = {
// TODO: Populate these with real data
switchableAccounts: ['Jim', 'Bill'],
settingsOptions: ['I', 'Am', 'Unsure', 'What', 'Should', 'Be', 'Here']
};
this.dropdownRenderRow = this.dropdownRenderRow.bind(this);
this.confirmDeleteAccount = this.confirmDeleteAccount.bind(this);
}
render() {
return (
<KeyboardAwareScrollView style={styles.container}>
<Text style={styles.title}>Change Account</Text>
<Text style={styles.text}>You're currently logged in as...</Text>
<ModalDropdown style={styles.dropdown}
options={this.state.switchableAccounts}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Switch to Which Account?'
renderRow={this.dropdownRenderRow}
/>
<ModalDropdown style={styles.dropdown}
options={this.state.settingsOptions}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Account Settings'
renderRow={this.dropdownRenderRow}
/>
<TouchableHighlight onPress={this.confirmDeleteAccount}>
<View style={styles.dropdown}>
<Text style={styles.dropdownText}>Delete My Account</Text>
</View>
</TouchableHighlight>
</KeyboardAwareScrollView>
);
}
dropdownRenderRow(rowData, rowID, highlighted) {
let evenRow = rowID % 2;
return (
<TouchableHighlight underlayColor='#6495ED'>
<View style={[styles.dropdownRow, {backgroundColor: evenRow ? '#87CEEB' : '#87CEFA'}]}>
<Text style={styles.dropdownRowText}>{rowData}</Text>
</View>
</TouchableHighlight>
);
}
confirmDeleteAccount() {
Alert.alert(
'Delete Account',
'Are you sure you want to delete your account?',
[
{text: 'Cancel', onPress: null, style: 'cancel' },
{text: 'Yes, Delete my account', onPress: null},
],
{ cancelable: false }
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
flex: 1,
backgroundColor:'rgb(52,152,219)',
},
title: {
textAlign: 'center',
color: 'white',
marginTop: 25,
fontSize: 20,
fontWeight: '400',
marginBottom: 15
},
text: {
textAlign: 'center',
color: 'white',
marginTop: 5,
fontSize: 18,
fontWeight: '400',
marginBottom: 15
},
dropdown: {
margin: 8,
borderColor: 'rgb(31,58,147)',
backgroundColor: 'rgb(31,58,147)',
borderWidth: 1,
borderRadius: 1,
},
dropdownText: {
marginVertical: 10,
marginHorizontal: 6,
fontSize: 18,
color: 'white',
textAlign: 'center',
textAlignVertical: 'center',
},
dropdownDropdown: {
margin: 8,
width: 320,
height: 100,
borderColor: 'rgb(31,58,147)',
borderWidth: 2,
borderRadius: 3,
backgroundColor: 'rgb(31,58,147)',
},
dropdownRow: {
flexDirection: 'row',
height: 40,
alignItems: 'center',
backgroundColor: 'rgb(31,58,147)'
},
dropdownRowText: {
marginHorizontal: 4,
fontSize: 16,
color: 'white',
textAlignVertical: 'center',
textAlign: 'center',
}
});
|
node_modules/react-icons/fa/mars.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaMars = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m35.9 2.9q0.5 0 1 0.4t0.4 1v9.3q0 0.3-0.2 0.5t-0.5 0.2h-1.5q-0.3 0-0.5-0.2t-0.2-0.5v-5.9l-8.5 8.6q2.8 3.5 2.8 8 0 2.6-1 5t-2.7 4.1-4.2 2.7-4.9 1-5-1-4.1-2.7-2.8-4.1-1-5 1-5 2.8-4.1 4.1-2.8 5-1q4.5 0 8 2.8l8.5-8.5h-5.8q-0.3 0-0.5-0.2t-0.2-0.5v-1.4q0-0.3 0.2-0.5t0.5-0.2h9.3z m-20 31.4q4.1 0 7-2.9t3-7.1-3-7.1-7-2.9-7.1 2.9-2.9 7.1 2.9 7.1 7.1 2.9z"/></g>
</Icon>
)
export default FaMars
|
blueocean-material-icons/src/js/components/svg-icons/action/settings-phone.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSettingsPhone = (props) => (
<SvgIcon {...props}>
<path d="M13 9h-2v2h2V9zm4 0h-2v2h2V9zm3 6.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 9v2h2V9h-2z"/>
</SvgIcon>
);
ActionSettingsPhone.displayName = 'ActionSettingsPhone';
ActionSettingsPhone.muiName = 'SvgIcon';
export default ActionSettingsPhone;
|
library/src/pivotal-ui-react/table/table.js | sjolicoeur/pivotal-ui | import classnames from 'classnames';
import {Icon} from 'pui-react-iconography';
import {mergeProps} from 'pui-react-helpers';
import PropTypes from 'prop-types';
import React from 'react';
import sortBy from 'lodash.sortby';
import 'pui-css-tables';
import {FlexTableHeader} from './flex-table-header';
export {FlexTableHeader} from './flex-table-header';
import {FlexTableCell} from './flex-table-cell';
export {FlexTableCell} from './flex-table-cell';
import {FlexTableRow} from './flex-table-row';
export {FlexTableRow} from './flex-table-row';
import {TableHeader} from './table-header';
export {TableHeader} from './table-header';
import {TableCell} from './table-cell';
export {TableCell} from './table-cell';
import {TableRow} from './table-row';
export {TableRow} from './table-row';
const SORT_ORDER = {
asc: 0,
desc: 1,
none: 2
};
export class Table extends React.Component {
static propTypes = {
bodyRowClassName: PropTypes.string,
columns: PropTypes.array.isRequired,
CustomRow: PropTypes.func,
data: PropTypes.array.isRequired,
defaultSort: PropTypes.string,
rowProps: PropTypes.object
};
constructor(props, context) {
super(props, context);
const {columns, defaultSort} = props;
const sortColumn = columns.find(({sortable, attribute}) => {
return defaultSort ? attribute === defaultSort : sortable;
});
this.state = {sortColumn, sortOrder: SORT_ORDER.asc};
this.defaultCell = TableCell;
this.defaultRow = TableRow;
this.defaultHeader = TableHeader;
}
componentWillReceiveProps({columns, defaultSort}) {
if (columns) {
const sortColumn = columns.find(({sortable, attribute}) => {
return defaultSort ? attribute === defaultSort : sortable;
});
this.setState({sortColumn, sortOrder: SORT_ORDER.asc});
}
}
updateSort = (sortColumn, isSortColumn) => {
if (isSortColumn) {
return this.setState({sortOrder: ++this.state.sortOrder % Object.keys(SORT_ORDER).length});
}
this.setState({sortColumn, sortOrder: SORT_ORDER.asc});
};
sortedRows = data => {
const {sortColumn, sortOrder} = this.state;
if (sortOrder === SORT_ORDER.none) return this.rows(data);
const sortedData = sortBy(data, datum => {
const rankFunction = sortColumn.sortBy || (i => i);
return rankFunction(datum[sortColumn.attribute]);
});
if (sortOrder === SORT_ORDER.desc) sortedData.reverse();
return this.rows(sortedData);
};
rows = data => {
const {bodyRowClassName, columns, CustomRow, rowProps} = this.props;
return data.map((rowDatum, rowKey) => {
const cells = columns.map((opts, key) => {
const {attribute, CustomCell, width} = opts;
let style, {cellClass} = opts;
if (width) {
style = {width};
opts.cellClass = classnames(cellClass, 'col-fixed');
}
const Cell = CustomCell || this.defaultCell;
const cellProps = {
key,
index: rowKey,
value: rowDatum[attribute],
rowDatum,
style,
...opts
};
return (<Cell {...cellProps}>{rowDatum[attribute]}</Cell>);
});
const Row = CustomRow || this.defaultRow;
return (<Row key={rowKey} index={rowKey} {...{
key: rowKey,
index: rowKey,
className: bodyRowClassName,
rowDatum,
...rowProps
}}
>{cells}</Row>);
});
};
renderHeaders = () => {
const {sortColumn, sortOrder} = this.state;
return this.props.columns.map((column, index) => {
let {attribute, sortable, displayName, cellClass, headerProps = {}, width} = column;
const isSortColumn = column === sortColumn;
let className, icon;
if (isSortColumn) {
className = ['sorted-asc', 'sorted-desc', ''][sortOrder];
icon = [<Icon verticalAlign="baseline" src="arrow_drop_up"/>,
<Icon verticalAlign="baseline" src="arrow_drop_down"/>, null][sortOrder];
}
className = classnames(className, headerProps.className, cellClass);
headerProps = {
...headerProps,
className,
sortable,
key: index,
onSortableTableHeaderClick: () => this.updateSort(column, isSortColumn)
};
if (width) {
headerProps = {
...headerProps,
className: classnames(className, 'col-fixed'),
style: {width}
};
}
const Header = this.defaultHeader;
return (<Header {...headerProps}>
<div>{displayName || attribute}{icon}</div>
</Header>);
});
};
render() {
const {sortColumn} = this.state;
let {columns, CustomRow, data, defaultSort, ...props} = this.props;
props = mergeProps(props, {className: ['table', 'table-sortable', 'table-data']});
const rows = sortColumn ? this.sortedRows(data) : this.rows(data);
return (<table {...props}>
<thead>
<tr>{this.renderHeaders()}</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>);
}
}
export class FlexTable extends Table {
static propTypes = {
bodyRowClassName: PropTypes.string,
columns: PropTypes.array.isRequired,
CustomRow: PropTypes.func,
data: PropTypes.array.isRequired,
defaultSort: PropTypes.string,
headerRowClassName: PropTypes.string,
hideHeaderRow: PropTypes.bool,
rowProps: PropTypes.object
};
constructor(props, context) {
super(props, context);
const {columns, defaultSort} = props;
const sortColumn = columns.find(({sortable, attribute}) => {
return defaultSort ? attribute === defaultSort : sortable;
});
this.state = {sortColumn, sortOrder: SORT_ORDER.asc};
this.defaultCell = FlexTableCell;
this.defaultRow = FlexTableRow;
this.defaultHeader = FlexTableHeader;
}
render() {
const {sortColumn} = this.state;
let {bodyRowClassName, columns, CustomRow, data, defaultSort, headerRowClassName, hideHeaderRow, rowProps, ...props} = this.props;
props = mergeProps(props, {className: ['table', 'table-sortable', 'table-data']});
let header;
if (!hideHeaderRow) {
header = (
<div className={classnames('tr', 'grid', headerRowClassName)}>
{this.renderHeaders()}
</div>
);
}
const rows = sortColumn ? this.sortedRows(data) : this.rows(data);
return (<div {...props}>
{header}
{rows}
</div>);
}
} |
packages/material-ui/src/ListItem/ListItem.js | lgollut/material-ui | import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import ButtonBase from '../ButtonBase';
import isMuiElement from '../utils/isMuiElement';
import useForkRef from '../utils/useForkRef';
import ListContext from '../List/ListContext';
import * as ReactDOM from 'react-dom';
export const styles = (theme) => ({
/* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
root: {
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
position: 'relative',
textDecoration: 'none',
width: '100%',
boxSizing: 'border-box',
textAlign: 'left',
paddingTop: 8,
paddingBottom: 8,
'&$focusVisible': {
backgroundColor: theme.palette.action.selected,
},
'&$selected, &$selected:hover': {
backgroundColor: theme.palette.action.selected,
},
'&$disabled': {
opacity: 0.5,
},
},
/* Styles applied to the `container` element if `children` includes `ListItemSecondaryAction`. */
container: {
position: 'relative',
},
/* Pseudo-class applied to the `component`'s `focusVisibleClassName` prop if `button={true}`. */
focusVisible: {},
/* Styles applied to the `component` element if dense. */
dense: {
paddingTop: 4,
paddingBottom: 4,
},
/* Styles applied to the `component` element if `alignItems="flex-start"`. */
alignItemsFlexStart: {
alignItems: 'flex-start',
},
/* Pseudo-class applied to the inner `component` element if `disabled={true}`. */
disabled: {},
/* Styles applied to the inner `component` element if `divider={true}`. */
divider: {
borderBottom: `1px solid ${theme.palette.divider}`,
backgroundClip: 'padding-box',
},
/* Styles applied to the inner `component` element if `disableGutters={false}`. */
gutters: {
paddingLeft: 16,
paddingRight: 16,
},
/* Styles applied to the inner `component` element if `button={true}`. */
button: {
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest,
}),
'&:hover': {
textDecoration: 'none',
backgroundColor: theme.palette.action.hover,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent',
},
},
},
/* Styles applied to the `component` element if `children` includes `ListItemSecondaryAction`. */
secondaryAction: {
// Add some space to avoid collision as `ListItemSecondaryAction`
// is absolutely positioned.
paddingRight: 48,
},
/* Pseudo-class applied to the root element if `selected={true}`. */
selected: {},
});
const useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
/**
* Uses an additional container component if `ListItemSecondaryAction` is the last child.
*/
const ListItem = React.forwardRef(function ListItem(props, ref) {
const {
alignItems = 'center',
autoFocus = false,
button = false,
children: childrenProp,
classes,
className,
component: componentProp,
ContainerComponent = 'li',
ContainerProps: { className: ContainerClassName, ...ContainerProps } = {},
dense = false,
disabled = false,
disableGutters = false,
divider = false,
focusVisibleClassName,
selected = false,
...other
} = props;
const context = React.useContext(ListContext);
const childContext = {
dense: dense || context.dense || false,
alignItems,
};
const listItemRef = React.useRef(null);
useEnhancedEffect(() => {
if (autoFocus) {
if (listItemRef.current) {
listItemRef.current.focus();
} else if (process.env.NODE_ENV !== 'production') {
console.error(
'Material-UI: Unable to set focus to a ListItem whose component has not been rendered.',
);
}
}
}, [autoFocus]);
const children = React.Children.toArray(childrenProp);
const hasSecondaryAction =
children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']);
const handleOwnRef = React.useCallback((instance) => {
// #StrictMode ready
listItemRef.current = ReactDOM.findDOMNode(instance);
}, []);
const handleRef = useForkRef(handleOwnRef, ref);
const componentProps = {
className: clsx(
classes.root,
{
[classes.dense]: childContext.dense,
[classes.gutters]: !disableGutters,
[classes.divider]: divider,
[classes.disabled]: disabled,
[classes.button]: button,
[classes.alignItemsFlexStart]: alignItems === 'flex-start',
[classes.secondaryAction]: hasSecondaryAction,
[classes.selected]: selected,
},
className,
),
disabled,
...other,
};
let Component = componentProp || 'li';
if (button) {
componentProps.component = componentProp || 'div';
componentProps.focusVisibleClassName = clsx(classes.focusVisible, focusVisibleClassName);
Component = ButtonBase;
}
if (hasSecondaryAction) {
// Use div by default.
Component = !componentProps.component && !componentProp ? 'div' : Component;
// Avoid nesting of li > li.
if (ContainerComponent === 'li') {
if (Component === 'li') {
Component = 'div';
} else if (componentProps.component === 'li') {
componentProps.component = 'div';
}
}
return (
<ListContext.Provider value={childContext}>
<ContainerComponent
className={clsx(classes.container, ContainerClassName)}
ref={handleRef}
{...ContainerProps}
>
<Component {...componentProps}>{children}</Component>
{children.pop()}
</ContainerComponent>
</ListContext.Provider>
);
}
return (
<ListContext.Provider value={childContext}>
<Component ref={handleRef} {...componentProps}>
{children}
</Component>
</ListContext.Provider>
);
});
ListItem.propTypes = {
/**
* Defines the `align-items` style property.
*/
alignItems: PropTypes.oneOf(['flex-start', 'center']),
/**
* If `true`, the list item will be focused during the first mount.
* Focus will also be triggered if the value changes from false to true.
*/
autoFocus: PropTypes.bool,
/**
* If `true`, the list item will be a button (using `ButtonBase`). Props intended
* for `ButtonBase` can then be applied to `ListItem`.
*/
button: PropTypes.bool,
/**
* The content of the component. If a `ListItemSecondaryAction` is used it must
* be the last child.
*/
children: chainPropTypes(PropTypes.node, (props) => {
const children = React.Children.toArray(props.children);
// React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction)
let secondaryActionIndex = -1;
for (let i = children.length - 1; i >= 0; i -= 1) {
const child = children[i];
if (isMuiElement(child, ['ListItemSecondaryAction'])) {
secondaryActionIndex = i;
break;
}
}
// is ListItemSecondaryAction the last child of ListItem
if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) {
return new Error(
'Material-UI: You used an element after ListItemSecondaryAction. ' +
'For ListItem to detect that it has a secondary action ' +
'you must pass it as the last child to ListItem.',
);
}
return null;
}),
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
* By default, it's a `li` when `button` is `false` and a `div` when `button` is `true`.
*/
component: PropTypes /* @typescript-to-proptypes-ignore */.elementType,
/**
* The container component used when a `ListItemSecondaryAction` is the last child.
*/
ContainerComponent: PropTypes.elementType,
/**
* Props applied to the container component if used.
*/
ContainerProps: PropTypes.object,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input will be used.
*/
dense: PropTypes.bool,
/**
* If `true`, the list item will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the left and right padding is removed.
*/
disableGutters: PropTypes.bool,
/**
* If `true`, a 1px light border is added to the bottom of the list item.
*/
divider: PropTypes.bool,
/**
* @ignore
*/
focusVisibleClassName: PropTypes.string,
/**
* Use to apply selected styling.
*/
selected: PropTypes.bool,
};
export default withStyles(styles, { name: 'MuiListItem' })(ListItem);
|
src/parser/druid/restoration/modules/features/PrematureRejuvenations.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS/index';
import Analyzer from 'parser/core/Analyzer';
import HealingDone from 'parser/shared/modules/throughput/HealingDone';
import StatisticBox from 'interface/others/StatisticBox';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Combatants from 'parser/shared/modules/Combatants';
const debug = false;
const REJUV_DURATION = 15000;
const MS_BUFFER = 200;
const PANDEMIC_THRESHOLD = 0.7;
const FLOURISH_EXTENSION = 8000;
/*
* This module tracks early refreshments of rejuvenation.
* TODO: Extend/refactor this module to include other HoTs/Spells as well such as lifebloom/efflorescence
* TODO: Add this module to checklist
*/
class PrematureRejuvenations extends Analyzer {
static dependencies = {
healingDone: HealingDone,
combatants: Combatants,
};
totalRejuvsCasts = 0;
rejuvenations = [];
earlyRefreshments = 0;
timeLost = 0;
constructor(...args) {
super(...args);
// TODO - Extend this module to also support when using Germination.
this.active = !this.selectedCombatant.hasTalent(SPELLS.GERMINATION_TALENT.id);
}
on_byPlayer_removebuff(event) {
if (event.ability.guid !== SPELLS.REJUVENATION.id) {
return;
}
const target = this.combatants.getEntity(event);
if (!target) {
return; // target wasn't important (a pet probably)
}
// Sanity check - Remove rejuvenation from array if it was removed from target player.
this.rejuvenations = this.rejuvenations.filter(e => e.targetId !== event.targetID);
}
on_byPlayer_cast(event) {
if (event.ability.guid === SPELLS.REJUVENATION.id) {
this.totalRejuvsCasts++;
const oldRejuv = this.rejuvenations.find(e => e.targetId === event.targetID);
if (oldRejuv == null) {
this.rejuvenations.push({ "targetId": event.targetID, "timestamp": event.timestamp });
return;
}
const pandemicTimestamp = oldRejuv.timestamp + ((REJUV_DURATION * PANDEMIC_THRESHOLD) + MS_BUFFER);
if (pandemicTimestamp > event.timestamp) {
this.earlyRefreshments++;
this.timeLost += pandemicTimestamp - event.timestamp;
}
// Account for pandemic time if hot was applied within the pandemic timeframe.
let pandemicTime = 0;
if (event.timestamp >= pandemicTimestamp && event.timestamp <= oldRejuv.timestamp + REJUV_DURATION) {
pandemicTime = (oldRejuv.timestamp + REJUV_DURATION) - event.timestamp;
} else if(event.timestamp <= pandemicTime) {
pandemicTime = REJUV_DURATION - (REJUV_DURATION * PANDEMIC_THRESHOLD);
}
debug && console.log("Extended within pandemic time frame: " + pandemicTime);
// Set the new timestamp
oldRejuv.timestamp = event.timestamp + pandemicTime;
} else if(event.ability.guid === SPELLS.FLOURISH_TALENT.id) {
// TODO - Flourish extends all active rejuvenations within 60 yards by 8 seconds. Add range check possible?
this.rejuvenations = this.rejuvenations.map(o => ({ ...o, timestamp: o.timestamp + FLOURISH_EXTENSION}));
}
}
on_fightend() {
debug && console.log("Finished: %o", this.rejuvenations);
debug && console.log("Early refreshments: "+ this.earlyRefreshments);
debug && console.log("Time lost: " + this.timeLost);
}
get timeLostInSeconds() {
return (this.timeLost/1000).toFixed(2);
}
get timeLostThreshold() {
return {
actual: this.timeLostInSeconds,
isGreaterThan: {
minor: 0,
average: 20,
major: 45,
},
style: 'number',
};
}
suggestions(when) {
when(this.timeLostThreshold)
.addSuggestion((suggest) => {
return suggest(<>Don't refresh <SpellLink id={SPELLS.REJUVENATION.id} /> if it's not within pandemic time frame (4.5s left on buff).</>)
.icon(SPELLS.REJUVENATION.icon)
.actual(`You refreshed early ${this.earlyRefreshments} times which made you waste ${this.timeLostInSeconds} seconds of rejuvenation.`)
.recommended(`0 seconds lost is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.REJUVENATION.id} />}
value={this.earlyRefreshments}
label={`Early rejuvenation refreshments`}
tooltip={`The total time lost from your early refreshments was ${this.timeLostInSeconds} seconds.`}
/>
);
}
}
export default PrematureRejuvenations;
|
6.6.2/examples/syncValidation/dist/bundle.js | erikras/redux-form-docs | !function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/dist/",t(t.s=706)}([function(e,t,n){var r=n(3),o=n(36),i=n(19),a=n(20),u=n(37),s=function(e,t,n){var c,l,f,p,d=e&s.F,h=e&s.G,v=e&s.S,m=e&s.P,y=e&s.B,g=h?r:v?r[t]||(r[t]={}):(r[t]||{}).prototype,b=h?o:o[t]||(o[t]={}),_=b.prototype||(b.prototype={});h&&(n=t);for(c in n)l=!d&&g&&void 0!==g[c],f=(l?g:n)[c],p=y&&l?u(f,r):m&&"function"==typeof f?u(Function.call,f):f,g&&a(g,c,f,e&s.U),b[c]!=f&&i(b,c,p),m&&_[c]!=f&&(_[c]=f)};r.core=o,s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,e.exports=s},function(e,t,n){"use strict";function r(e,t,n,r,i,a,u,s){if(o(t),!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,i,a,u,s],f=0;c=new Error(t.replace(/%s/g,function(){return l[f++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var o=function(e){};e.exports=r},function(e,t,n){var r=n(7);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){"use strict";var r=n(28),o=r;e.exports=o},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){"use strict";function r(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}e.exports=r},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){var r=n(92)("wks"),o=n(55),i=n(3).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var o=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,u,s=r(e),c=1;c<arguments.length;c++){n=Object(arguments[c]);for(var l in n)i.call(n,l)&&(s[l]=n[l]);if(o){u=o(n);for(var f=0;f<u.length;f++)a.call(n,u[f])&&(s[u[f]]=n[u[f]])}}return s}},function(e,t,n){e.exports=!n(5)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(2),o=n(185),i=n(32),a=Object.defineProperty;t.f=n(10)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";function r(e,t){return 1===e.nodeType&&e.getAttribute(h)===String(t)||8===e.nodeType&&e.nodeValue===" react-text: "+t+" "||8===e.nodeType&&e.nodeValue===" react-empty: "+t+" "}function o(e){for(var t;t=e._renderedComponent;)e=t;return e}function i(e,t){var n=o(e);n._hostNode=t,t[m]=n}function a(e){var t=e._hostNode;t&&(delete t[m],e._hostNode=null)}function u(e,t){if(!(e._flags&v.hasCachedChildNodes)){var n=e._renderedChildren,a=t.firstChild;e:for(var u in n)if(n.hasOwnProperty(u)){var s=n[u],c=o(s)._domID;if(0!==c){for(;null!==a;a=a.nextSibling)if(r(a,c)){i(s,a);continue e}f("32",c)}}e._flags|=v.hasCachedChildNodes}}function s(e){if(e[m])return e[m];for(var t=[];!e[m];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[m]);e=t.pop())n=r,t.length&&u(r,e);return n}function c(e){var t=s(e);return null!=t&&t._hostNode===e?t:null}function l(e){if(void 0===e._hostNode&&f("33"),e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent||f("34"),e=e._hostParent;for(;t.length;e=t.pop())u(e,e._hostNode);return e._hostNode}var f=n(6),p=n(66),d=n(233),h=(n(1),p.ID_ATTRIBUTE_NAME),v=d,m="__reactInternalInstance$"+Math.random().toString(36).slice(2),y={getClosestInstanceFromNode:s,getInstanceFromNode:c,getNodeFromInstance:l,precacheChildNodes:u,precacheNode:i,uncacheNode:a};e.exports=y},function(e,t,n){var r=n(45),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(26);e.exports=function(e){return Object(r(e))}},function(e,t,n){"use strict";e.exports=n(69)},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};e.exports=o},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){var r=n(11),o=n(44);e.exports=n(10)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(3),o=n(19),i=n(16),a=n(55)("src"),u=Function.toString,s=(""+u).split("toString");n(36).inspectSource=function(e){return u.call(e)},(e.exports=function(e,t,n,u){var c="function"==typeof n;c&&(i(n,"name")||o(n,"name",t)),e[t]!==n&&(c&&(i(n,a)||o(n,a,e[t]?""+e[t]:s.join(String(t)))),e===r?e[t]=n:u?e[t]?e[t]=n:o(e,t,n):(delete e[t],o(e,t,n)))})(Function.prototype,"toString",function(){return"function"==typeof this&&this[a]||u.call(this)})},function(e,t,n){var r=n(0),o=n(5),i=n(26),a=function(e,t,n,r){var o=String(i(e)),a="<"+t;return""!==n&&(a+=" "+n+'="'+String(r).replace(/"/g,""")+'"'),a+">"+o+"</"+t+">"};e.exports=function(e,t){var n={};n[e]=t(a),r(r.P+r.F*o(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",n)}},function(e,t,n){var r=n(73),o=n(26);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(74),o=n(44),i=n(22),a=n(32),u=n(16),s=n(185),c=Object.getOwnPropertyDescriptor;t.f=n(10)?c:function(e,t){if(e=i(e),t=a(t,!0),s)try{return c(e,t)}catch(e){}if(u(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(16),o=n(14),i=n(127)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(5);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null)})}},function(e,t,n){"use strict";function r(e){return function(){return e}}var o=function(){};o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,n){"use strict";var r=null;e.exports={debugTool:r}},function(e,t,n){var r=n(37),o=n(73),i=n(14),a=n(13),u=n(276);e.exports=function(e,t){var n=1==e,s=2==e,c=3==e,l=4==e,f=6==e,p=5==e||f,d=t||u;return function(t,u,h){for(var v,m,y=i(t),g=o(y),b=r(u,h,3),_=a(g.length),E=0,w=n?d(t,_):s?d(t,0):void 0;_>E;E++)if((p||E in g)&&(v=g[E],m=b(v,E,y),e))if(n)w[E]=m;else if(m)switch(e){case 3:return!0;case 5:return v;case 6:return E;case 2:w.push(v)}else if(l)return!1;return f?-1:c||l?l:w}}},function(e,t,n){var r=n(0),o=n(36),i=n(5);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){var r=n(7);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(219),o="object"==typeof self&&self&&self.Object===Object&&self,i=r.a||o||Function("return this")();t.a=i},function(e,t,n){"use strict";var r=Array.isArray;t.a=r},function(e,t,n){"use strict";function r(){O.ReactReconcileTransaction&&E||l("123")}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=p.getPooled(),this.reconcileTransaction=O.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){return r(),E.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;t!==y.length&&l("124",t,y.length),y.sort(a),g++;for(var n=0;n<t;n++){var r=y[n],o=r._pendingCallbacks;r._pendingCallbacks=null;var i;if(h.logTopLevelRenders){var u=r;r._currentElement.type.isReactTopLevelWrapper&&(u=r._renderedComponent),i="React update: "+u.getName(),console.time(i)}if(v.performUpdateIfNecessary(r,e.reconcileTransaction,g),i&&console.timeEnd(i),o)for(var s=0;s<o.length;s++)e.callbackQueue.enqueue(o[s],r.getPublicInstance())}}function s(e){if(r(),!E.isBatchingUpdates)return void E.batchedUpdates(s,e);y.push(e),null==e._updateBatchNumber&&(e._updateBatchNumber=g+1)}function c(e,t){E.isBatchingUpdates||l("125"),b.enqueue(e,t),_=!0}var l=n(6),f=n(9),p=n(231),d=n(58),h=n(236),v=n(67),m=n(106),y=(n(1),[]),g=0,b=p.getPooled(),_=!1,E=null,w={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),S()):y.length=0}},x={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},C=[w,x];f(o.prototype,m,{getTransactionWrappers:function(){return C},destructor:function(){this.dirtyComponentsLength=null,p.release(this.callbackQueue),this.callbackQueue=null,O.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return m.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),d.addPoolingTo(o);var S=function(){for(;y.length||_;){if(y.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(_){_=!1;var t=b;b=p.getPooled(),t.notifyAll(),p.release(t)}}},P={injectReconcileTransaction:function(e){e||l("126"),O.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e||l("127"),"function"!=typeof e.batchedUpdates&&l("128"),"boolean"!=typeof e.isBatchingUpdates&&l("129"),E=e}},O={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:S,injection:P,asap:c};e.exports=O},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(18);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(201),o=n(0),i=n(92)("metadata"),a=i.store||(i.store=new(n(204))),u=function(e,t,n){var o=a.get(e);if(!o){if(!n)return;a.set(e,o=new r)}var i=o.get(t);if(!i){if(!n)return;o.set(t,i=new r)}return i},s=function(e,t,n){var r=u(t,n,!1);return void 0!==r&&r.has(e)},c=function(e,t,n){var r=u(t,n,!1);return void 0===r?void 0:r.get(e)},l=function(e,t,n,r){u(n,r,!0).set(e,t)},f=function(e,t){var n=u(e,t,!1),r=[];return n&&n.forEach(function(e,t){r.push(t)}),r},p=function(e){return void 0===e||"symbol"==typeof e?e:String(e)},d=function(e){o(o.S,"Reflect",e)};e.exports={store:a,map:u,has:s,get:c,set:l,keys:f,key:p,exp:d}},function(e,t,n){"use strict";if(n(10)){var r=n(48),o=n(3),i=n(5),a=n(0),u=n(93),s=n(134),c=n(37),l=n(47),f=n(44),p=n(19),d=n(52),h=n(45),v=n(13),m=n(54),y=n(32),g=n(16),b=n(198),_=n(72),E=n(7),w=n(14),x=n(119),C=n(49),S=n(24),P=n(50).f,O=n(136),T=n(55),k=n(8),A=n(30),R=n(83),I=n(128),N=n(137),M=n(61),j=n(89),F=n(53),D=n(112),U=n(178),L=n(11),V=n(23),B=L.f,W=V.f,q=o.RangeError,H=o.TypeError,z=o.Uint8Array,Y=Array.prototype,K=s.ArrayBuffer,G=s.DataView,$=A(0),X=A(2),Q=A(3),J=A(4),Z=A(5),ee=A(6),te=R(!0),ne=R(!1),re=N.values,oe=N.keys,ie=N.entries,ae=Y.lastIndexOf,ue=Y.reduce,se=Y.reduceRight,ce=Y.join,le=Y.sort,fe=Y.slice,pe=Y.toString,de=Y.toLocaleString,he=k("iterator"),ve=k("toStringTag"),me=T("typed_constructor"),ye=T("def_constructor"),ge=u.CONSTR,be=u.TYPED,_e=u.VIEW,Ee=A(1,function(e,t){return Oe(I(e,e[ye]),t)}),we=i(function(){return 1===new z(new Uint16Array([1]).buffer)[0]}),xe=!!z&&!!z.prototype.set&&i(function(){new z(1).set({})}),Ce=function(e,t){if(void 0===e)throw H("Wrong length!");var n=+e,r=v(e);if(t&&!b(n,r))throw q("Wrong length!");return r},Se=function(e,t){var n=h(e);if(n<0||n%t)throw q("Wrong offset!");return n},Pe=function(e){if(E(e)&&be in e)return e;throw H(e+" is not a typed array!")},Oe=function(e,t){if(!(E(e)&&me in e))throw H("It is not a typed array constructor!");return new e(t)},Te=function(e,t){return ke(I(e,e[ye]),t)},ke=function(e,t){for(var n=0,r=t.length,o=Oe(e,r);r>n;)o[n]=t[n++];return o},Ae=function(e,t,n){B(e,t,{get:function(){return this._d[n]}})},Re=function(e){var t,n,r,o,i,a,u=w(e),s=arguments.length,l=s>1?arguments[1]:void 0,f=void 0!==l,p=O(u);if(void 0!=p&&!x(p)){for(a=p.call(u),r=[],t=0;!(i=a.next()).done;t++)r.push(i.value);u=r}for(f&&s>2&&(l=c(l,arguments[2],2)),t=0,n=v(u.length),o=Oe(this,n);n>t;t++)o[t]=f?l(u[t],t):u[t];return o},Ie=function(){for(var e=0,t=arguments.length,n=Oe(this,t);t>e;)n[e]=arguments[e++];return n},Ne=!!z&&i(function(){de.call(new z(1))}),Me=function(){return de.apply(Ne?fe.call(Pe(this)):Pe(this),arguments)},je={copyWithin:function(e,t){return U.call(Pe(this),e,t,arguments.length>2?arguments[2]:void 0)},every:function(e){return J(Pe(this),e,arguments.length>1?arguments[1]:void 0)},fill:function(e){return D.apply(Pe(this),arguments)},filter:function(e){return Te(this,X(Pe(this),e,arguments.length>1?arguments[1]:void 0))},find:function(e){return Z(Pe(this),e,arguments.length>1?arguments[1]:void 0)},findIndex:function(e){return ee(Pe(this),e,arguments.length>1?arguments[1]:void 0)},forEach:function(e){$(Pe(this),e,arguments.length>1?arguments[1]:void 0)},indexOf:function(e){return ne(Pe(this),e,arguments.length>1?arguments[1]:void 0)},includes:function(e){return te(Pe(this),e,arguments.length>1?arguments[1]:void 0)},join:function(e){return ce.apply(Pe(this),arguments)},lastIndexOf:function(e){return ae.apply(Pe(this),arguments)},map:function(e){return Ee(Pe(this),e,arguments.length>1?arguments[1]:void 0)},reduce:function(e){return ue.apply(Pe(this),arguments)},reduceRight:function(e){return se.apply(Pe(this),arguments)},reverse:function(){for(var e,t=this,n=Pe(t).length,r=Math.floor(n/2),o=0;o<r;)e=t[o],t[o++]=t[--n],t[n]=e;return t},some:function(e){return Q(Pe(this),e,arguments.length>1?arguments[1]:void 0)},sort:function(e){return le.call(Pe(this),e)},subarray:function(e,t){var n=Pe(this),r=n.length,o=m(e,r);return new(I(n,n[ye]))(n.buffer,n.byteOffset+o*n.BYTES_PER_ELEMENT,v((void 0===t?r:m(t,r))-o))}},Fe=function(e,t){return Te(this,fe.call(Pe(this),e,t))},De=function(e){Pe(this);var t=Se(arguments[1],1),n=this.length,r=w(e),o=v(r.length),i=0;if(o+t>n)throw q("Wrong length!");for(;i<o;)this[t+i]=r[i++]},Ue={entries:function(){return ie.call(Pe(this))},keys:function(){return oe.call(Pe(this))},values:function(){return re.call(Pe(this))}},Le=function(e,t){return E(e)&&e[be]&&"symbol"!=typeof t&&t in e&&String(+t)==String(t)},Ve=function(e,t){return Le(e,t=y(t,!0))?f(2,e[t]):W(e,t)},Be=function(e,t,n){return!(Le(e,t=y(t,!0))&&E(n)&&g(n,"value"))||g(n,"get")||g(n,"set")||n.configurable||g(n,"writable")&&!n.writable||g(n,"enumerable")&&!n.enumerable?B(e,t,n):(e[t]=n.value,e)};ge||(V.f=Ve,L.f=Be),a(a.S+a.F*!ge,"Object",{getOwnPropertyDescriptor:Ve,defineProperty:Be}),i(function(){pe.call({})})&&(pe=de=function(){return ce.call(this)});var We=d({},je);d(We,Ue),p(We,he,Ue.values),d(We,{slice:Fe,set:De,constructor:function(){},toString:pe,toLocaleString:Me}),Ae(We,"buffer","b"),Ae(We,"byteOffset","o"),Ae(We,"byteLength","l"),Ae(We,"length","e"),B(We,ve,{get:function(){return this[be]}}),e.exports=function(e,t,n,s){s=!!s;var c=e+(s?"Clamped":"")+"Array",f="Uint8Array"!=c,d="get"+e,h="set"+e,m=o[c],y=m||{},g=m&&S(m),b=!m||!u.ABV,w={},x=m&&m.prototype,O=function(e,n){var r=e._d;return r.v[d](n*t+r.o,we)},T=function(e,n,r){var o=e._d;s&&(r=(r=Math.round(r))<0?0:r>255?255:255&r),o.v[h](n*t+o.o,r,we)},k=function(e,t){B(e,t,{get:function(){return O(this,t)},set:function(e){return T(this,t,e)},enumerable:!0})};b?(m=n(function(e,n,r,o){l(e,m,c,"_d");var i,a,u,s,f=0,d=0;if(E(n)){if(!(n instanceof K||"ArrayBuffer"==(s=_(n))||"SharedArrayBuffer"==s))return be in n?ke(m,n):Re.call(m,n);i=n,d=Se(r,t);var h=n.byteLength;if(void 0===o){if(h%t)throw q("Wrong length!");if((a=h-d)<0)throw q("Wrong length!")}else if((a=v(o)*t)+d>h)throw q("Wrong length!");u=a/t}else u=Ce(n,!0),a=u*t,i=new K(a);for(p(e,"_d",{b:i,o:d,l:a,e:u,v:new G(i)});f<u;)k(e,f++)}),x=m.prototype=C(We),p(x,"constructor",m)):j(function(e){new m(null),new m(e)},!0)||(m=n(function(e,n,r,o){l(e,m,c);var i;return E(n)?n instanceof K||"ArrayBuffer"==(i=_(n))||"SharedArrayBuffer"==i?void 0!==o?new y(n,Se(r,t),o):void 0!==r?new y(n,Se(r,t)):new y(n):be in n?ke(m,n):Re.call(m,n):new y(Ce(n,f))}),$(g!==Function.prototype?P(y).concat(P(g)):P(y),function(e){e in m||p(m,e,y[e])}),m.prototype=x,r||(x.constructor=m));var A=x[he],R=!!A&&("values"==A.name||void 0==A.name),I=Ue.values;p(m,me,!0),p(x,be,c),p(x,_e,!0),p(x,ye,m),(s?new m(1)[ve]==c:ve in x)||B(x,ve,{get:function(){return c}}),w[c]=m,a(a.G+a.W+a.F*(m!=y),w),a(a.S,c,{BYTES_PER_ELEMENT:t,from:Re,of:Ie}),"BYTES_PER_ELEMENT"in x||p(x,"BYTES_PER_ELEMENT",t),a(a.P,c,je),F(c),a(a.P+a.F*xe,c,{set:De}),a(a.P+a.F*!R,c,Ue),a(a.P+a.F*(x.toString!=pe),c,{toString:pe}),a(a.P+a.F*i(function(){new m(1).slice()}),c,{slice:Fe}),a(a.P+a.F*(i(function(){return[1,2].toLocaleString()!=new m([1,2]).toLocaleString()})||!i(function(){x.toLocaleString.call([1,2])})),c,{toLocaleString:Me}),M[c]=R?A:I,r||R||p(x,he,I)}}else e.exports=function(){}},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var u=o[i];u?this[i]=u(n):"target"===i?this.target=r:this[i]=n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue;return this.isDefaultPrevented=s?a.thatReturnsTrue:a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var o=n(9),i=n(58),a=n(28),u=(n(4),["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),s={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n<u.length;n++)this[u[n]]=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;o(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.fourArgumentPooler)},i.addPoolingTo(r,i.fourArgumentPooler),e.exports=r},function(e,t,n){"use strict";var r={current:null};e.exports=r},function(e,t,n){"use strict";var r=n(694),o=n(691),i=n(693),a=n(689),u=n(690),s=n(692),c={allowsArrayErrors:!0,empty:{},emptyList:[],getIn:o.a,setIn:i.a,deepEqual:a.a,deleteIn:u.a,fromJS:function(e){return e},keys:s.a,size:function(e){return e?e.length:0},splice:r.a,toJS:function(e){return e}};t.a=c},function(e,t,n){var r=n(55)("meta"),o=n(7),i=n(16),a=n(11).f,u=0,s=Object.isExtensible||function(){return!0},c=!n(5)(function(){return s(Object.preventExtensions({}))}),l=function(e){a(e,r,{value:{i:"O"+ ++u,w:{}}})},f=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!s(e))return"F";if(!t)return"E";l(e)}return e[r].i},p=function(e,t){if(!i(e,r)){if(!s(e))return!0;if(!t)return!1;l(e)}return e[r].w},d=function(e){return c&&h.NEED&&s(e)&&!i(e,r)&&l(e),e},h=e.exports={KEY:r,NEED:!1,fastKey:f,getWeak:p,onFreeze:d}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){"use strict";function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}t.a=r},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t){e.exports=!1},function(e,t,n){var r=n(2),o=n(191),i=n(115),a=n(127)("IE_PROTO"),u=function(){},s=function(){var e,t=n(114)("iframe"),r=i.length;for(t.style.display="none",n(117).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("<script>document.F=Object</script>"),e.close(),s=e.F;r--;)delete s.prototype[i[r]];return s()};e.exports=Object.create||function(e,t){var n;return null!==e?(u.prototype=r(e),n=new u,u.prototype=null,n[a]=e):n=s(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(193),o=n(115).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(193),o=n(115);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){var r=n(20);e.exports=function(e,t,n){for(var o in t)r(e,o,t[o],n);return e}},function(e,t,n){"use strict";var r=n(3),o=n(11),i=n(10),a=n(8)("species");e.exports=function(e){var t=r[e];i&&t&&!t[a]&&o.f(t,a,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(45),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t,n){"use strict";function r(e,t){var r=n.i(i.a)(e,t);return n.i(o.a)(r)?r:void 0}var o=n(487),i=n(518);t.a=r},function(e,t,n){"use strict";function r(e){return null!=e&&"object"==typeof e}t.a=r},function(e,t,n){"use strict";var r=n(6),o=(n(1),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},s=function(e){var t=this;e instanceof t||r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=o,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=10),n.release=s,n},f={addPoolingTo:l,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:u};e.exports=f},function(e,t,n){var r=n(8)("unscopables"),o=Array.prototype;void 0==o[r]&&n(19)(o,r,{}),e.exports=function(e){o[r][e]=!0}},function(e,t,n){var r=n(37),o=n(187),i=n(119),a=n(2),u=n(13),s=n(136),c={},l={},t=e.exports=function(e,t,n,f,p){var d,h,v,m,y=p?function(){return e}:s(e),g=r(n,f,t?2:1),b=0;if("function"!=typeof y)throw TypeError(e+" is not iterable!");if(i(y)){for(d=u(e.length);d>b;b++)if((m=t?g(a(h=e[b])[0],h[1]):g(e[b]))===c||m===l)return m}else for(v=y.call(e);!(h=v.next()).done;)if((m=o(v,g,h.value,t))===c||m===l)return m};t.BREAK=c,t.RETURN=l},function(e,t){e.exports={}},function(e,t,n){var r=n(11).f,o=n(16),i=n(8)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(0),o=n(26),i=n(5),a=n(132),u="["+a+"]",s="
",c=RegExp("^"+u+u+"*"),l=RegExp(u+u+"*$"),f=function(e,t,n){var o={},u=i(function(){return!!a[e]()||s[e]()!=s}),c=o[e]=u?t(p):a[e];n&&(o[n]=c),r(r.P+r.F*u,"String",o)},p=f.trim=function(e,t){return e=String(o(e)),1&t&&(e=e.replace(c,"")),2&t&&(e=e.replace(l,"")),e};e.exports=f},function(e,t,n){"use strict";function r(e){return null==e?void 0===e?s:u:c&&c in Object(e)?n.i(i.a)(e):n.i(a.a)(e)}var o=n(95),i=n(515),a=n(544),u="[object Null]",s="[object Undefined]",c=o.a?o.a.toStringTag:void 0;t.a=r},function(e,t,n){"use strict";function r(e){if(h){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)v(t,n[r],null);else null!=e.html?f(t,e.html):null!=e.text&&d(t,e.text)}}function o(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function i(e,t){h?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){h?e.html=t:f(e.node,t)}function u(e,t){h?e.text=t:d(e.node,t)}function s(){return this.node.nodeName}function c(e){return{node:e,children:[],html:null,text:null,toString:s}}var l=n(156),f=n(108),p=n(164),d=n(248),h="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),v=p(function(e,t,n){11===t.node.nodeType||1===t.node.nodeType&&"object"===t.node.nodeName.toLowerCase()&&(null==t.node.namespaceURI||t.node.namespaceURI===l.html)?(r(t),e.insertBefore(t.node,n)):(e.insertBefore(t.node,n),r(t))});c.insertTreeBefore=v,c.replaceChildWithTree=o,c.queueChild=i,c.queueHTML=a,c.queueText=u,e.exports=c},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(6),i=(n(1),{MUST_USE_PROPERTY:1,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},s=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var f in n){u.properties.hasOwnProperty(f)&&o("48",f);var p=f.toLowerCase(),d=n[f],h={attributeName:p,attributeNamespace:null,propertyName:f,mutationMethod:null,mustUseProperty:r(d,t.MUST_USE_PROPERTY),hasBooleanValue:r(d,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(d,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(d,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(d,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(h.hasBooleanValue+h.hasNumericValue+h.hasOverloadedBooleanValue<=1||o("50",f),s.hasOwnProperty(f)){var v=s[f];h.attributeName=v}a.hasOwnProperty(f)&&(h.attributeNamespace=a[f]),c.hasOwnProperty(f)&&(h.propertyName=c[f]),l.hasOwnProperty(f)&&(h.mutationMethod=l[f]),u.properties[f]=h}}}),a=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",u={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:a,ATTRIBUTE_NAME_CHAR:a+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){if((0,u._isCustomAttributeFunctions[t])(e))return!0}return!1},injection:i};e.exports=u},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(604),i=(n(29),n(4),{mountComponent:function(e,t,n,o,i,a){var u=e.mountComponent(t,n,o,i,a);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),u},getHostNode:function(e){return e.getHostNode()},unmountComponent:function(e,t){o.detachRefs(e,e._currentElement),e.unmountComponent(t)},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var u=o.shouldUpdateRefs(a,t);u&&o.detachRefs(e,a),e.receiveComponent(t,n,i),u&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t,n){e._updateBatchNumber===n&&e.performUpdateIfNecessary(t)}});e.exports=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(632),o=n(250),i=n(633);n.d(t,"Provider",function(){return r.a}),n.d(t,"connectAdvanced",function(){return o.a}),n.d(t,"connect",function(){return i.a})},function(e,t,n){"use strict";var r=n(9),o=n(643),i=n(172),a=n(648),u=n(644),s=n(645),c=n(70),l=n(646),f=n(649),p=n(650),d=(n(4),c.createElement),h=c.createFactory,v=c.cloneElement,m=r,y={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:p},Component:i,PureComponent:a,createElement:d,cloneElement:v,isValidElement:c.isValidElement,PropTypes:l,createClass:u.createClass,createFactory:h,createMixin:function(e){return e},DOM:s,version:f,__spread:m};e.exports=y},function(e,t,n){"use strict";function r(e){return void 0!==e.ref}function o(e){return void 0!==e.key}var i=n(9),a=n(41),u=(n(4),n(257),Object.prototype.hasOwnProperty),s=n(255),c={key:!0,ref:!0,__self:!0,__source:!0},l=function(e,t,n,r,o,i,a){var u={$$typeof:s,type:e,key:t,ref:n,props:a,_owner:i};return u};l.createElement=function(e,t,n){var i,s={},f=null,p=null;if(null!=t){r(t)&&(p=t.ref),o(t)&&(f=""+t.key),void 0===t.__self?null:t.__self,void 0===t.__source?null:t.__source;for(i in t)u.call(t,i)&&!c.hasOwnProperty(i)&&(s[i]=t[i])}var d=arguments.length-2;if(1===d)s.children=n;else if(d>1){for(var h=Array(d),v=0;v<d;v++)h[v]=arguments[v+2];s.children=h}if(e&&e.defaultProps){var m=e.defaultProps;for(i in m)void 0===s[i]&&(s[i]=m[i])}return l(e,f,p,0,0,a.current,s)},l.createFactory=function(e){var t=l.createElement.bind(null,e);return t.type=e,t},l.cloneAndReplaceKey=function(e,t){return l(e.type,t,e.ref,e._self,e._source,e._owner,e.props)},l.cloneElement=function(e,t,n){var s,f=i({},e.props),p=e.key,d=e.ref,h=(e._self,e._source,e._owner);if(null!=t){r(t)&&(d=t.ref,h=a.current),o(t)&&(p=""+t.key);var v;e.type&&e.type.defaultProps&&(v=e.type.defaultProps);for(s in t)u.call(t,s)&&!c.hasOwnProperty(s)&&(void 0===t[s]&&void 0!==v?f[s]=v[s]:f[s]=t[s])}var m=arguments.length-2;if(1===m)f.children=n;else if(m>1){for(var y=Array(m),g=0;g<m;g++)y[g]=arguments[g+2];f.children=y}return l(e.type,p,d,0,0,h,f)},l.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===s},e.exports=l},function(e,t,n){"use strict";function r(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}e.exports=r},function(e,t,n){var r=n(25),o=n(8)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,u;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(u=r(t))&&"function"==typeof t.callee?"Arguments":u}},function(e,t,n){var r=n(25);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,u],l=0;s=new Error(t.replace(/%s/g,function(){return c[l++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}};e.exports=r},function(e,t,n){"use strict";function r(e){if("string"==typeof e||n.i(o.a)(e))return e;var t=e+"";return"0"==t&&1/e==-i?"-0":t}var o=n(102),i=1/0;t.a=r},function(e,t,n){"use strict";function r(e,t){return e===t||e!==e&&t!==t}t.a=r},function(e,t,n){"use strict";function r(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function o(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!r(t));default:return!1}}var i=n(6),a=n(157),u=n(158),s=n(162),c=n(242),l=n(243),f=(n(1),{}),p=null,d=function(e,t){e&&(u.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},h=function(e){return d(e,!0)},v=function(e){return d(e,!1)},m=function(e){return"."+e._rootNodeID},y={injection:{injectEventPluginOrder:a.injectEventPluginOrder,injectEventPluginsByName:a.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n&&i("94",t,typeof n);var r=m(e);(f[t]||(f[t]={}))[r]=n;var o=a.registrationNameModules[t];o&&o.didPutListener&&o.didPutListener(e,t,n)},getListener:function(e,t){var n=f[t];if(o(t,e._currentElement.type,e._currentElement.props))return null;var r=m(e);return n&&n[r]},deleteListener:function(e,t){var n=a.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var r=f[t];if(r){delete r[m(e)]}},deleteAllListeners:function(e){var t=m(e);for(var n in f)if(f.hasOwnProperty(n)&&f[n][t]){var r=a.registrationNameModules[n];r&&r.willDeleteListener&&r.willDeleteListener(e,n),delete f[n][t]}},extractEvents:function(e,t,n,r){for(var o,i=a.plugins,u=0;u<i.length;u++){var s=i[u];if(s){var l=s.extractEvents(e,t,n,r);l&&(o=c(o,l))}}return o},enqueueEvents:function(e){e&&(p=c(p,e))},processEventQueue:function(e){var t=p;p=null,e?l(t,h):l(t,v),p&&i("95"),s.rethrowCaughtError()},__purge:function(){f={}},__getListenerBank:function(){return f}};e.exports=y},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=r(e,n,t);o&&(n._dispatchListeners=v(n._dispatchListeners,o),n._dispatchInstances=v(n._dispatchInstances,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.traverseTwoPhase(e._targetInst,o,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?h.getParentInstance(t):null;h.traverseTwoPhase(n,o,e)}}function u(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=v(n._dispatchListeners,o),n._dispatchInstances=v(n._dispatchInstances,e))}}function s(e){e&&e.dispatchConfig.registrationName&&u(e._targetInst,null,e)}function c(e){m(e,i)}function l(e){m(e,a)}function f(e,t,n,r){h.traverseEnterLeave(n,r,u,e,t)}function p(e){m(e,s)}var d=n(79),h=n(158),v=n(242),m=n(243),y=(n(4),d.getListener),g={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:p,accumulateEnterLeaveDispatches:f};e.exports=g},function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i=n(167),a={view:function(e){if(e.view)return e.view;var t=i(e);if(t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e,t,n){var r=n(22),o=n(13),i=n(54);e.exports=function(e){return function(t,n,a){var u,s=r(t),c=o(s.length),l=i(a,c);if(e&&n!=n){for(;c>l;)if((u=s[l++])!=u)return!0}else for(;c>l;l++)if((e||l in s)&&s[l]===n)return e||l||0;return!e&&-1}}},function(e,t,n){"use strict";var r=n(3),o=n(0),i=n(20),a=n(52),u=n(43),s=n(60),c=n(47),l=n(7),f=n(5),p=n(89),d=n(62),h=n(118);e.exports=function(e,t,n,v,m,y){var g=r[e],b=g,_=m?"set":"add",E=b&&b.prototype,w={},x=function(e){var t=E[e];i(E,e,"delete"==e?function(e){return!(y&&!l(e))&&t.call(this,0===e?0:e)}:"has"==e?function(e){return!(y&&!l(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return y&&!l(e)?void 0:t.call(this,0===e?0:e)}:"add"==e?function(e){return t.call(this,0===e?0:e),this}:function(e,n){return t.call(this,0===e?0:e,n),this})};if("function"==typeof b&&(y||E.forEach&&!f(function(){(new b).entries().next()}))){var C=new b,S=C[_](y?{}:-0,1)!=C,P=f(function(){C.has(1)}),O=p(function(e){new b(e)}),T=!y&&f(function(){for(var e=new b,t=5;t--;)e[_](t,t);return!e.has(-0)});O||(b=t(function(t,n){c(t,b,e);var r=h(new g,t,b);return void 0!=n&&s(n,m,r[_],r),r}),b.prototype=E,E.constructor=b),(P||T)&&(x("delete"),x("has"),m&&x("get")),(T||S)&&x(_),y&&E.clear&&delete E.clear}else b=v.getConstructor(t,e,m,_),a(b.prototype,n),u.NEED=!0;return d(b,e),w[e]=b,o(o.G+o.W+o.F*(b!=g),w),y||v.setStrong(b,e,m),b}},function(e,t,n){"use strict";var r=n(19),o=n(20),i=n(5),a=n(26),u=n(8);e.exports=function(e,t,n){var s=u(e),c=n(a,s,""[e]),l=c[0],f=c[1];i(function(){var t={};return t[s]=function(){return 7},7!=""[e](t)})&&(o(String.prototype,e,l),r(RegExp.prototype,s,2==t?function(e,t){return f.call(e,this,t)}:function(e){return f.call(e,this)}))}},function(e,t,n){"use strict";var r=n(2);e.exports=function(){var e=r(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(7),o=n(25),i=n(8)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==o(e))}},function(e,t,n){var r=n(8)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){e.exports=n(48)||!n(5)(function(){var e=Math.random();__defineSetter__.call(null,e,function(){}),delete n(3)[e]})},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(3),o=r["__core-js_shared__"]||(r["__core-js_shared__"]={});e.exports=function(e){return o[e]||(o[e]={})}},function(e,t,n){for(var r,o=n(3),i=n(19),a=n(55),u=a("typed_array"),s=a("view"),c=!(!o.ArrayBuffer||!o.DataView),l=c,f=0,p="Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array".split(",");f<9;)(r=o[p[f++]])?(i(r.prototype,u,!0),i(r.prototype,s,!0)):l=!1;e.exports={ABV:c,CONSTR:l,TYPED:u,VIEW:s}},function(e,t,n){"use strict";function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(529),i=n(530),a=n(531),u=n(532),s=n(533);r.prototype.clear=o.a,r.prototype.delete=i.a,r.prototype.get=a.a,r.prototype.has=u.a,r.prototype.set=s.a,t.a=r},function(e,t,n){"use strict";var r=n(33),o=r.a.Symbol;t.a=o},function(e,t,n){"use strict";function r(e,t){for(var r=e.length;r--;)if(n.i(o.a)(e[r][0],t))return r;return-1}var o=n(78);t.a=r},function(e,t,n){"use strict";function r(e,t,r){"__proto__"==t&&o.a?n.i(o.a)(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var o=n(217);t.a=r},function(e,t,n){"use strict";function r(e,t){var r=e.__data__;return n.i(o.a)(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=n(527);t.a=r},function(e,t,n){"use strict";var r=n(56),o=n.i(r.a)(Object,"create");t.a=o},function(e,t,n){"use strict";function r(e){return null!=e&&n.i(i.a)(e.length)&&!n.i(o.a)(e)}var o=n(150),i=n(151);t.a=r},function(e,t,n){"use strict";function r(e){if(!n.i(a.a)(e)||n.i(o.a)(e)!=u)return!1;var t=n.i(i.a)(e);if(null===t)return!0;var r=f.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&l.call(r)==p}var o=n(64),i=n(220),a=n(57),u="[object Object]",s=Function.prototype,c=Object.prototype,l=s.toString,f=c.hasOwnProperty,p=l.call(Object);t.a=r},function(e,t,n){"use strict";function r(e){return"symbol"==typeof e||n.i(i.a)(e)&&n.i(o.a)(e)==a}var o=n(64),i=n(57),a="[object Symbol]";t.a=r},function(e,t,n){"use strict";function r(e){return n.i(a.a)(e)?n.i(o.a)(e,c.a):n.i(u.a)(e)?[e]:n.i(i.a)(n.i(s.a)(n.i(l.a)(e)))}var o=n(211),i=n(216),a=n(34),u=n(102),s=n(224),c=n(77),l=n(229);t.a=r},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,v)||(e[v]=d++,f[e[v]]={}),f[e[v]]}var o,i=n(9),a=n(157),u=n(596),s=n(241),c=n(629),l=n(168),f={},p=!1,d=0,h={topAbort:"abort",topAnimationEnd:c("animationend")||"animationend",topAnimationIteration:c("animationiteration")||"animationiteration",topAnimationStart:c("animationstart")||"animationstart",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topTransitionEnd:c("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},v="_reactListenersID"+String(Math.random()).slice(2),m=i({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(m.handleTopLevel),m.ReactEventListener=e}},setEnabled:function(e){m.ReactEventListener&&m.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!m.ReactEventListener||!m.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,o=r(n),i=a.registrationNameDependencies[e],u=0;u<i.length;u++){var s=i[u];o.hasOwnProperty(s)&&o[s]||("topWheel"===s?l("wheel")?m.ReactEventListener.trapBubbledEvent("topWheel","wheel",n):l("mousewheel")?m.ReactEventListener.trapBubbledEvent("topWheel","mousewheel",n):m.ReactEventListener.trapBubbledEvent("topWheel","DOMMouseScroll",n):"topScroll"===s?l("scroll",!0)?m.ReactEventListener.trapCapturedEvent("topScroll","scroll",n):m.ReactEventListener.trapBubbledEvent("topScroll","scroll",m.ReactEventListener.WINDOW_HANDLE):"topFocus"===s||"topBlur"===s?(l("focus",!0)?(m.ReactEventListener.trapCapturedEvent("topFocus","focus",n),m.ReactEventListener.trapCapturedEvent("topBlur","blur",n)):l("focusin")&&(m.ReactEventListener.trapBubbledEvent("topFocus","focusin",n),m.ReactEventListener.trapBubbledEvent("topBlur","focusout",n)),o.topBlur=!0,o.topFocus=!0):h.hasOwnProperty(s)&&m.ReactEventListener.trapBubbledEvent(s,h[s],n),o[s]=!0)}},trapBubbledEvent:function(e,t,n){return m.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return m.ReactEventListener.trapCapturedEvent(e,t,n)},supportsEventPageXY:function(){if(!document.createEvent)return!1;var e=document.createEvent("MouseEvent");return null!=e&&"pageX"in e},ensureScrollValueMonitoring:function(){if(void 0===o&&(o=m.supportsEventPageXY()),!o&&!p){var e=s.refreshScrollValues;m.ReactEventListener.monitorScrollValue(e),p=!0}}});e.exports=m},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(82),i=n(241),a=n(166),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,u),e.exports=r},function(e,t,n){"use strict";var r=n(6),o=(n(1),{}),i={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,u,s){this.isInTransaction()&&r("27");var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,n,o,i,a,u,s),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(e){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o)try{this.initializeAll(n+1)}catch(e){}}}},closeAll:function(e){this.isInTransaction()||r("28");for(var t=this.transactionWrappers,n=e;n<t.length;n++){var i,a=t[n],u=this.wrapperInitData[n];try{i=!0,u!==o&&a.close&&a.close.call(this,u),i=!1}finally{if(i)try{this.closeAll(n+1)}catch(e){}}}this.wrapperInitData.length=0}};e.exports=i},function(e,t,n){"use strict";function r(e){var t=""+e,n=i.exec(t);if(!n)return t;var r,o="",a=0,u=0;for(a=n.index;a<t.length;a++){switch(t.charCodeAt(a)){case 34:r=""";break;case 38:r="&";break;case 39:r="'";break;case 60:r="<";break;case 62:r=">";break;default:continue}u!==a&&(o+=t.substring(u,a)),u=a+1,o+=r}return u!==a?o+t.substring(u,a):o}function o(e){return"boolean"==typeof e||"number"==typeof e?""+e:r(e)}var i=/["'&<>]/;e.exports=o},function(e,t,n){"use strict";var r,o=n(17),i=n(156),a=/^[ \r\n\t\f]/,u=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,s=n(164),c=s(function(e,t){if(e.namespaceURI!==i.svg||"innerHTML"in e)e.innerHTML=t;else{r=r||document.createElement("div"),r.innerHTML="<svg>"+t+"</svg>";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}});if(o.canUseDOM){var l=document.createElement("div");l.innerHTML=" ",""===l.innerHTML&&(c=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),a.test(t)||"<"===t[0]&&u.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),l=null}e.exports=c},function(e,t,n){"use strict";function r(e,t){var n=e._reduxForm.sectionPrefix;return n?n+"."+t:t}t.a=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(269),o=n(700),i=n(699),a=n(698),u=n(268);n(270);n.d(t,"createStore",function(){return r.a}),n.d(t,"combineReducers",function(){return o.a}),n.d(t,"bindActionCreators",function(){return i.a}),n.d(t,"applyMiddleware",function(){return a.a}),n.d(t,"compose",function(){return u.a})},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";var r=n(14),o=n(54),i=n(13);e.exports=function(e){for(var t=r(this),n=i(t.length),a=arguments.length,u=o(a>1?arguments[1]:void 0,n),s=a>2?arguments[2]:void 0,c=void 0===s?n:o(s,n);c>u;)t[u++]=e;return t}},function(e,t,n){"use strict";var r=n(11),o=n(44);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(7),o=n(3).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(8)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[r]=!1,!"/./"[e](t)}catch(e){}}return!0}},function(e,t,n){e.exports=n(3).document&&document.documentElement},function(e,t,n){var r=n(7),o=n(126).set;e.exports=function(e,t,n){var i,a=t.constructor;return a!==n&&"function"==typeof a&&(i=a.prototype)!==n.prototype&&r(i)&&o&&o(e,i),e}},function(e,t,n){var r=n(61),o=n(8)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(25);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){"use strict";var r=n(49),o=n(44),i=n(62),a={};n(19)(a,n(8)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){"use strict";var r=n(48),o=n(0),i=n(20),a=n(19),u=n(16),s=n(61),c=n(121),l=n(62),f=n(24),p=n(8)("iterator"),d=!([].keys&&"next"in[].keys()),h=function(){return this};e.exports=function(e,t,n,v,m,y,g){c(n,t,v);var b,_,E,w=function(e){if(!d&&e in P)return P[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},x=t+" Iterator",C="values"==m,S=!1,P=e.prototype,O=P[p]||P["@@iterator"]||m&&P[m],T=O||w(m),k=m?C?w("entries"):T:void 0,A="Array"==t?P.entries||O:O;if(A&&(E=f(A.call(new e)))!==Object.prototype&&(l(E,x,!0),r||u(E,p)||a(E,p,h)),C&&O&&"values"!==O.name&&(S=!0,T=function(){return O.call(this)}),r&&!g||!d&&!S&&P[p]||a(P,p,T),s[t]=T,s[x]=h,m)if(b={values:C?T:w("values"),keys:y?T:w("keys"),entries:k},g)for(_ in b)_ in P||i(P,_,b[_]);else o(o.P+o.F*(d||S),t,b);return b}},function(e,t){var n=Math.expm1;e.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||-2e-17!=n(-2e-17)?function(e){return 0==(e=+e)?e:e>-1e-6&&e<1e-6?e+e*e/2:Math.exp(e)-1}:n},function(e,t){e.exports=Math.sign||function(e){return 0==(e=+e)||e!=e?e:e<0?-1:1}},function(e,t,n){var r=n(3),o=n(133).set,i=r.MutationObserver||r.WebKitMutationObserver,a=r.process,u=r.Promise,s="process"==n(25)(a);e.exports=function(){var e,t,n,c=function(){var r,o;for(s&&(r=a.domain)&&r.exit();e;){o=e.fn,e=e.next;try{o()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(s)n=function(){a.nextTick(c)};else if(i){var l=!0,f=document.createTextNode("");new i(c).observe(f,{characterData:!0}),n=function(){f.data=l=!l}}else if(u&&u.resolve){var p=u.resolve();n=function(){p.then(c)}}else n=function(){o.call(r,c)};return function(r){var o={fn:r,next:void 0};t&&(t.next=o),e||(e=o,n()),t=o}}},function(e,t,n){var r=n(7),o=n(2),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(37)(Function.call,n(23).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){var r=n(92)("keys"),o=n(55);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(2),o=n(18),i=n(8)("species");e.exports=function(e,t){var n,a=r(e).constructor;return void 0===a||void 0==(n=r(a)[i])?t:o(n)}},function(e,t,n){var r=n(45),o=n(26);e.exports=function(e){return function(t,n){var i,a,u=String(o(t)),s=r(n),c=u.length;return s<0||s>=c?e?"":void 0:(i=u.charCodeAt(s),i<55296||i>56319||s+1===c||(a=u.charCodeAt(s+1))<56320||a>57343?e?u.charAt(s):i:e?u.slice(s,s+2):a-56320+(i-55296<<10)+65536)}}},function(e,t,n){var r=n(88),o=n(26);e.exports=function(e,t,n){if(r(t))throw TypeError("String#"+n+" doesn't accept regex!");return String(o(e))}},function(e,t,n){"use strict";var r=n(45),o=n(26);e.exports=function(e){var t=String(o(this)),n="",i=r(e);if(i<0||i==1/0)throw RangeError("Count can't be negative");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(n+=t);return n}},function(e,t){e.exports="\t\n\v\f\r \u2028\u2029\ufeff"},function(e,t,n){var r,o,i,a=n(37),u=n(87),s=n(117),c=n(114),l=n(3),f=l.process,p=l.setImmediate,d=l.clearImmediate,h=l.MessageChannel,v=0,m={},y=function(){var e=+this;if(m.hasOwnProperty(e)){var t=m[e];delete m[e],t()}},g=function(e){y.call(e.data)};p&&d||(p=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return m[++v]=function(){u("function"==typeof e?e:Function(e),t)},r(v),v},d=function(e){delete m[e]},"process"==n(25)(f)?r=function(e){f.nextTick(a(y,e,1))}:h?(o=new h,i=o.port2,o.port1.onmessage=g,r=a(i.postMessage,i,1)):l.addEventListener&&"function"==typeof postMessage&&!l.importScripts?(r=function(e){l.postMessage(e+"","*")},l.addEventListener("message",g,!1)):r="onreadystatechange"in c("script")?function(e){s.appendChild(c("script")).onreadystatechange=function(){s.removeChild(this),y.call(e)}}:function(e){setTimeout(a(y,e,1),0)}),e.exports={set:p,clear:d}},function(e,t,n){"use strict";var r=n(3),o=n(10),i=n(48),a=n(93),u=n(19),s=n(52),c=n(5),l=n(47),f=n(45),p=n(13),d=n(50).f,h=n(11).f,v=n(112),m=n(62),y=r.ArrayBuffer,g=r.DataView,b=r.Math,_=r.RangeError,E=r.Infinity,w=y,x=b.abs,C=b.pow,S=b.floor,P=b.log,O=b.LN2,T=o?"_b":"buffer",k=o?"_l":"byteLength",A=o?"_o":"byteOffset",R=function(e,t,n){var r,o,i,a=Array(n),u=8*n-t-1,s=(1<<u)-1,c=s>>1,l=23===t?C(2,-24)-C(2,-77):0,f=0,p=e<0||0===e&&1/e<0?1:0;for(e=x(e),e!=e||e===E?(o=e!=e?1:0,r=s):(r=S(P(e)/O),e*(i=C(2,-r))<1&&(r--,i*=2),e+=r+c>=1?l/i:l*C(2,1-c),e*i>=2&&(r++,i/=2),r+c>=s?(o=0,r=s):r+c>=1?(o=(e*i-1)*C(2,t),r+=c):(o=e*C(2,c-1)*C(2,t),r=0));t>=8;a[f++]=255&o,o/=256,t-=8);for(r=r<<t|o,u+=t;u>0;a[f++]=255&r,r/=256,u-=8);return a[--f]|=128*p,a},I=function(e,t,n){var r,o=8*n-t-1,i=(1<<o)-1,a=i>>1,u=o-7,s=n-1,c=e[s--],l=127&c;for(c>>=7;u>0;l=256*l+e[s],s--,u-=8);for(r=l&(1<<-u)-1,l>>=-u,u+=t;u>0;r=256*r+e[s],s--,u-=8);if(0===l)l=1-a;else{if(l===i)return r?NaN:c?-E:E;r+=C(2,t),l-=a}return(c?-1:1)*r*C(2,l-t)},N=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},M=function(e){return[255&e]},j=function(e){return[255&e,e>>8&255]},F=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},D=function(e){return R(e,52,8)},U=function(e){return R(e,23,4)},L=function(e,t,n){h(e.prototype,t,{get:function(){return this[n]}})},V=function(e,t,n,r){var o=+n,i=f(o);if(o!=i||i<0||i+t>e[k])throw _("Wrong index!");var a=e[T]._b,u=i+e[A],s=a.slice(u,u+t);return r?s:s.reverse()},B=function(e,t,n,r,o,i){var a=+n,u=f(a);if(a!=u||u<0||u+t>e[k])throw _("Wrong index!");for(var s=e[T]._b,c=u+e[A],l=r(+o),p=0;p<t;p++)s[c+p]=l[i?p:t-p-1]},W=function(e,t){l(e,y,"ArrayBuffer");var n=+t,r=p(n);if(n!=r)throw _("Wrong length!");return r};if(a.ABV){if(!c(function(){new y})||!c(function(){new y(.5)})){y=function(e){return new w(W(this,e))};for(var q,H=y.prototype=w.prototype,z=d(w),Y=0;z.length>Y;)(q=z[Y++])in y||u(y,q,w[q]);i||(H.constructor=y)}var K=new g(new y(2)),G=g.prototype.setInt8;K.setInt8(0,2147483648),K.setInt8(1,2147483649),!K.getInt8(0)&&K.getInt8(1)||s(g.prototype,{setInt8:function(e,t){G.call(this,e,t<<24>>24)},setUint8:function(e,t){G.call(this,e,t<<24>>24)}},!0)}else y=function(e){var t=W(this,e);this._b=v.call(Array(t),0),this[k]=t},g=function(e,t,n){l(this,g,"DataView"),l(e,y,"DataView");var r=e[k],o=f(t);if(o<0||o>r)throw _("Wrong offset!");if(n=void 0===n?r-o:p(n),o+n>r)throw _("Wrong length!");this[T]=e,this[A]=o,this[k]=n},o&&(L(y,"byteLength","_l"),L(g,"buffer","_b"),L(g,"byteLength","_l"),L(g,"byteOffset","_o")),s(g.prototype,{getInt8:function(e){return V(this,1,e)[0]<<24>>24},getUint8:function(e){return V(this,1,e)[0]},getInt16:function(e){var t=V(this,2,e,arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=V(this,2,e,arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return N(V(this,4,e,arguments[1]))},getUint32:function(e){return N(V(this,4,e,arguments[1]))>>>0},getFloat32:function(e){return I(V(this,4,e,arguments[1]),23,4)},getFloat64:function(e){return I(V(this,8,e,arguments[1]),52,8)},setInt8:function(e,t){B(this,1,e,M,t)},setUint8:function(e,t){B(this,1,e,M,t)},setInt16:function(e,t){B(this,2,e,j,t,arguments[2])},setUint16:function(e,t){B(this,2,e,j,t,arguments[2])},setInt32:function(e,t){B(this,4,e,F,t,arguments[2])},setUint32:function(e,t){B(this,4,e,F,t,arguments[2])},setFloat32:function(e,t){B(this,4,e,U,t,arguments[2])},setFloat64:function(e,t){B(this,8,e,D,t,arguments[2])}});m(y,"ArrayBuffer"),m(g,"DataView"),u(g.prototype,a.VIEW,!0),t.ArrayBuffer=y,t.DataView=g},function(e,t,n){var r=n(3),o=n(36),i=n(48),a=n(200),u=n(11).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||u(t,e,{value:a.f(e)})}},function(e,t,n){var r=n(72),o=n(8)("iterator"),i=n(61);e.exports=n(36).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){"use strict";var r=n(59),o=n(188),i=n(61),a=n(22);e.exports=n(122)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var i=Object.prototype.hasOwnProperty;e.exports=o},function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=n},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n.i(r.a)(o.a,"Map");t.a=i},function(e,t,n){"use strict";function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(534),i=n(535),a=n(536),u=n(537),s=n(538);r.prototype.clear=o.a,r.prototype.delete=i.a,r.prototype.get=a.a,r.prototype.has=u.a,r.prototype.set=s.a,t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__=new o.a(e);this.size=t.size}var o=n(94),i=n(551),a=n(552),u=n(553),s=n(554),c=n(555);r.prototype.clear=i.a,r.prototype.delete=a.a,r.prototype.get=u.a,r.prototype.has=s.a,r.prototype.set=c.a,t.a=r},function(e,t,n){"use strict";function r(e,t,a,u,s){return e===t||(null==e||null==t||!n.i(i.a)(e)&&!n.i(i.a)(t)?e!==e&&t!==t:n.i(o.a)(e,t,a,u,r,s))}var o=n(485),i=n(57);t.a=r},function(e,t,n){"use strict";function r(e,t){return!!(t=null==t?o:t)&&("number"==typeof e||i.test(e))&&e>-1&&e%1==0&&e<t}var o=9007199254740991,i=/^(?:0|[1-9]\d*)$/;t.a=r},function(e,t,n){"use strict";function r(e,t){if(n.i(o.a)(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!n.i(i.a)(e))||(u.test(e)||!a.test(e)||null!=t&&e in Object(t))}var o=n(34),i=n(102),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u=/^\w*$/;t.a=r},function(e,t,n){"use strict";function r(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||o)}var o=Object.prototype;t.a=r},function(e,t,n){"use strict";function r(e){return e}t.a=r},function(e,t,n){"use strict";var r=n(484),o=n(57),i=Object.prototype,a=i.hasOwnProperty,u=i.propertyIsEnumerable,s=n.i(r.a)(function(){return arguments}())?r.a:function(e){return n.i(o.a)(e)&&a.call(e,"callee")&&!u.call(e,"callee")};t.a=s},function(e,t,n){"use strict";(function(e){var r=n(33),o=n(564),i="object"==typeof exports&&exports&&!exports.nodeType&&exports,a=i&&"object"==typeof e&&e&&!e.nodeType&&e,u=a&&a.exports===i,s=u?r.a.Buffer:void 0,c=s?s.isBuffer:void 0,l=c||o.a;t.a=l}).call(t,n(176)(e))},function(e,t,n){"use strict";function r(e){if(!n.i(i.a)(e))return!1;var t=n.i(o.a)(e);return t==u||t==s||t==a||t==c}var o=n(64),i=n(46),a="[object AsyncFunction]",u="[object Function]",s="[object GeneratorFunction]",c="[object Proxy]";t.a=r},function(e,t,n){"use strict";function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=o}var o=9007199254740991;t.a=r},function(e,t,n){"use strict";var r=n(488),o=n(502),i=n(543),a=i.a&&i.a.isTypedArray,u=a?n.i(o.a)(a):r.a;t.a=u},function(e,t,n){"use strict";function r(e){return n.i(a.a)(e)?n.i(o.a)(e):n.i(i.a)(e)}var o=n(210),i=n(490),a=n(100);t.a=r},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function i(e){if(f===clearTimeout)return clearTimeout(e);if((f===r||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(e);try{return f(e)}catch(t){try{return f.call(null,e)}catch(t){return f.call(this,e)}}}function a(){v&&d&&(v=!1,d.length?h=d.concat(h):m=-1,h.length&&u())}function u(){if(!v){var e=o(a);v=!0;for(var t=h.length;t;){for(d=h,h=[];++m<t;)d&&d[m].run();m=-1,t=h.length}d=null,v=!1,i(e)}}function s(e,t){this.fun=e,this.array=t}function c(){}var l,f,p=e.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(e){l=n}try{f="function"==typeof clearTimeout?clearTimeout:r}catch(e){f=r}}();var d,h=[],v=!1,m=-1;p.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];h.push(new s(e,t)),1!==h.length||v||o(u)},s.prototype.run=function(){this.fun.apply(null,this.array)},p.title="browser",p.browser=!0,p.env={},p.argv=[],p.version="",p.versions={},p.on=c,p.addListener=c,p.once=c,p.off=c,p.removeListener=c,p.removeAllListeners=c,p.emit=c,p.binding=function(e){throw new Error("process.binding is not supported")},p.cwd=function(){return"/"},p.chdir=function(e){throw new Error("process.chdir is not supported")},p.umask=function(){return 0}},function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){l.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?u(e,t[0],t[1],n):v(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],s(e,t,n),e.removeChild(n)}e.removeChild(t)}function u(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(v(e,o,r),o===n)break;o=i}}function s(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function c(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&v(r,document.createTextNode(n),o):n?(h(o,n),s(r,o,t)):s(r,e,t)}var l=n(65),f=n(573),p=(n(12),n(29),n(164)),d=n(108),h=n(248),v=p(function(e,t,n){e.insertBefore(t,n)}),m=f.dangerouslyReplaceNodeWithMarkup,y={dangerouslyReplaceNodeWithMarkup:m,replaceDelimitedText:c,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var u=t[n];switch(u.type){case"INSERT_MARKUP":o(e,u.content,r(e,u.afterNode));break;case"MOVE_EXISTING":i(e,u.fromNode,r(e,u.afterNode));break;case"SET_MARKUP":d(e,u.content);break;case"TEXT_CONTENT":h(e,u.content);break;case"REMOVE_NODE":a(e,u.fromNode)}}}};e.exports=y},function(e,t,n){"use strict";var r={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};e.exports=r},function(e,t,n){"use strict";function r(){if(u)for(var e in s){var t=s[e],n=u.indexOf(e);if(n>-1||a("96",e),!c.plugins[n]){t.extractEvents||a("97",e),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)||a("98",i,e)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)&&a("99",n),c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var u=r[o];i(u,t,n)}return!0}return!!e.registrationName&&(i(e.registrationName,t,n),!0)}function i(e,t,n){c.registrationNameModules[e]&&a("100",e),c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(6),u=(n(1),null),s={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){u&&a("101"),u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(s[n]&&a("102",n),s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;if(void 0!==t.phasedRegistrationNames){var n=t.phasedRegistrationNames;for(var r in n)if(n.hasOwnProperty(r)){var o=c.registrationNameModules[n[r]];if(o)return o}}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=c},function(e,t,n){"use strict";function r(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function o(e){return"topMouseMove"===e||"topTouchMove"===e}function i(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=y.getNodeFromInstance(r),t?v.invokeGuardedCallbackWithCatch(o,n,e):v.invokeGuardedCallback(o,n,e),e.currentTarget=null}function u(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function s(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=s(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)&&h("103"),e.currentTarget=t?y.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function f(e){return!!e._dispatchListeners}var p,d,h=n(6),v=n(162),m=(n(1),n(4),{injectComponentTree:function(e){p=e},injectTreeTraversal:function(e){d=e}}),y={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:l,executeDispatchesInOrder:u,executeDispatchesInOrderStopAtTrue:c,hasDispatches:f,getInstanceFromNode:function(e){return p.getInstanceFromNode(e)},getNodeFromInstance:function(e){return p.getNodeFromInstance(e)},isAncestor:function(e,t){return d.isAncestor(e,t)},getLowestCommonAncestor:function(e,t){return d.getLowestCommonAncestor(e,t)},getParentInstance:function(e){return d.getParentInstance(e)},traverseTwoPhase:function(e,t,n){return d.traverseTwoPhase(e,t,n)},traverseEnterLeave:function(e,t,n,r,o){return d.traverseEnterLeave(e,t,n,r,o)},injection:m};e.exports=y},function(e,t,n){"use strict";function r(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}function o(e){var t={"=0":"=","=2":":"};return(""+("."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1))).replace(/(=0|=2)/g,function(e){return t[e]})}var i={escape:r,unescape:o};e.exports=i},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink&&u("87")}function o(e){r(e),(null!=e.value||null!=e.onChange)&&u("88")}function i(e){r(e),(null!=e.checked||null!=e.onChange)&&u("89")}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var u=n(6),s=n(69),c=n(602),l=(n(1),n(4),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),f={value:function(e,t,n){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.PropTypes.func},p={},d={checkPropTypes:function(e,t,n){for(var r in f){if(f.hasOwnProperty(r))var o=f[r](t,r,e,"prop",null,c);if(o instanceof Error&&!(o.message in p)){p[o.message]=!0;a(n)}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=d},function(e,t,n){"use strict";var r=n(6),o=(n(1),!1),i={replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o&&r("104"),i.replaceNodeWithMarkup=e.replaceNodeWithMarkup,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){try{t(n)}catch(e){null===o&&(o=e)}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};e.exports=i},function(e,t,n){"use strict";function r(e){s.enqueueUpdate(e)}function o(e){var t=typeof e;if("object"!==t)return t;var n=e.constructor&&e.constructor.name||t,r=Object.keys(e);return r.length>0&&r.length<20?n+" (keys: "+r.join(", ")+")":n}function i(e,t){var n=u.get(e);if(!n){return null}return n}var a=n(6),u=(n(41),n(81)),s=(n(29),n(35)),c=(n(1),n(4),{isMounted:function(e){var t=u.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){c.validateCallback(t,n);var o=i(e);if(!o)return null;o._pendingCallbacks?o._pendingCallbacks.push(t):o._pendingCallbacks=[t],r(o)},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=i(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=i(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=i(e,"setState");if(n){(n._pendingStateQueue||(n._pendingStateQueue=[])).push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e&&a("122",t,o(e))}});e.exports=c},function(e,t,n){"use strict";var r=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e};e.exports=r},function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,t>=32||13===t?t:0}e.exports=r},function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return!!r&&!!n[r]}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}e.exports=r},function(e,t,n){"use strict";/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(17);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&!0!==document.implementation.hasFeature("","")),e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=null===e||!1===e,r=null===t||!1===t;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=r},function(e,t,n){"use strict";var r=(n(9),n(28)),o=(n(4),r);e.exports=o},function(e,t,n){"use strict";function r(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}t.a=r},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||i}var o=n(71),i=n(173),a=(n(257),n(75));n(1),n(4);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&o("85"),this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};e.exports=r},function(e,t,n){"use strict";var r=(n(4),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){},enqueueReplaceState:function(e,t){},enqueueSetState:function(e,t){}});e.exports=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n.d(t,"ARRAY_INSERT",function(){return r}),n.d(t,"ARRAY_MOVE",function(){return o}),n.d(t,"ARRAY_POP",function(){return i}),n.d(t,"ARRAY_PUSH",function(){return a}),n.d(t,"ARRAY_REMOVE",function(){return u}),n.d(t,"ARRAY_REMOVE_ALL",function(){return s}),n.d(t,"ARRAY_SHIFT",function(){return c}),n.d(t,"ARRAY_SPLICE",function(){return l}),n.d(t,"ARRAY_UNSHIFT",function(){return f}),n.d(t,"ARRAY_SWAP",function(){return p}),n.d(t,"AUTOFILL",function(){return d}),n.d(t,"BLUR",function(){return h}),n.d(t,"CHANGE",function(){return v}),n.d(t,"CLEAR_SUBMIT",function(){return m}),n.d(t,"CLEAR_SUBMIT_ERRORS",function(){return y}),n.d(t,"CLEAR_ASYNC_ERROR",function(){return g}),n.d(t,"DESTROY",function(){return b}),n.d(t,"FOCUS",function(){return _}),n.d(t,"INITIALIZE",function(){return E}),n.d(t,"REGISTER_FIELD",function(){return w}),n.d(t,"RESET",function(){return x}),n.d(t,"SET_SUBMIT_FAILED",function(){return C}),n.d(t,"SET_SUBMIT_SUCCEEDED",function(){return S}),n.d(t,"START_ASYNC_VALIDATION",function(){return P}),n.d(t,"START_SUBMIT",function(){return O}),n.d(t,"STOP_ASYNC_VALIDATION",function(){return T}),n.d(t,"STOP_SUBMIT",function(){return k}),n.d(t,"SUBMIT",function(){return A}),n.d(t,"TOUCH",function(){return R}),n.d(t,"UNREGISTER_FIELD",function(){return I}),n.d(t,"UNTOUCH",function(){return N}),n.d(t,"UPDATE_SYNC_ERRORS",function(){return M}),n.d(t,"UPDATE_SYNC_WARNINGS",function(){return j});var r="@@redux-form/ARRAY_INSERT",o="@@redux-form/ARRAY_MOVE",i="@@redux-form/ARRAY_POP",a="@@redux-form/ARRAY_PUSH",u="@@redux-form/ARRAY_REMOVE",s="@@redux-form/ARRAY_REMOVE_ALL",c="@@redux-form/ARRAY_SHIFT",l="@@redux-form/ARRAY_SPLICE",f="@@redux-form/ARRAY_UNSHIFT",p="@@redux-form/ARRAY_SWAP",d="@@redux-form/AUTOFILL",h="@@redux-form/BLUR",v="@@redux-form/CHANGE",m="@@redux-form/CLEAR_SUBMIT",y="@@redux-form/CLEAR_SUBMIT_ERRORS",g="@redux-form/CLEAR_ASYNC_ERROR",b="@@redux-form/DESTROY",_="@@redux-form/FOCUS",E="@@redux-form/INITIALIZE",w="@@redux-form/REGISTER_FIELD",x="@@redux-form/RESET",C="@@redux-form/SET_SUBMIT_FAILED",S="@@redux-form/SET_SUBMIT_SUCCEEDED",P="@@redux-form/START_ASYNC_VALIDATION",O="@@redux-form/START_SUBMIT",T="@@redux-form/STOP_ASYNC_VALIDATION",k="@@redux-form/STOP_SUBMIT",A="@@redux-form/SUBMIT",R="@@redux-form/TOUCH",I="@@redux-form/UNREGISTER_FIELD",N="@@redux-form/UNTOUCH",M="@@redux-form/UPDATE_SYNC_ERRORS",j="@@redux-form/UPDATE_SYNC_WARNINGS"},function(e,t,n){"use strict";var r=n(672),o=function(e){var t=e.getIn,o=e.keys,i=n.i(r.a)(e);return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")},r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function(a){var u=n(a);if(t(u,e+".syncError"))return!1;if(!r){if(t(u,e+".error"))return!1}var s=t(u,e+".syncErrors"),c=t(u,e+".asyncErrors"),l=r?void 0:t(u,e+".submitErrors");if(!s&&!c&&!l)return!0;var f=t(u,e+".registeredFields");return!f||!o(f).filter(function(e){return t(f,"['"+e+"'].count")>0}).some(function(e){return i(t(f,"['"+e+"']"),s,c,l)})}}};t.a=o},function(e,t){e.exports=function(e){if(!e.webpackPolyfill){var t=Object.create(e);t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),Object.defineProperty(t,"exports",{enumerable:!0}),t.webpackPolyfill=1}return t}},function(e,t,n){var r=n(25);e.exports=function(e,t){if("number"!=typeof e&&"Number"!=r(e))throw TypeError(t);return+e}},function(e,t,n){"use strict";var r=n(14),o=n(54),i=n(13);e.exports=[].copyWithin||function(e,t){var n=r(this),a=i(n.length),u=o(e,a),s=o(t,a),c=arguments.length>2?arguments[2]:void 0,l=Math.min((void 0===c?a:o(c,a))-s,a-u),f=1;for(s<u&&u<s+l&&(f=-1,s+=l-1,u+=l-1);l-- >0;)s in n?n[u]=n[s]:delete n[u],u+=f,s+=f;return n}},function(e,t,n){var r=n(60);e.exports=function(e,t){var n=[];return r(e,!1,n.push,n,t),n}},function(e,t,n){var r=n(18),o=n(14),i=n(73),a=n(13);e.exports=function(e,t,n,u,s){r(t);var c=o(e),l=i(c),f=a(c.length),p=s?f-1:0,d=s?-1:1;if(n<2)for(;;){if(p in l){u=l[p],p+=d;break}if(p+=d,s?p<0:f<=p)throw TypeError("Reduce of empty array with no initial value")}for(;s?p>=0:f>p;p+=d)p in l&&(u=t(u,l[p],p,c));return u}},function(e,t,n){"use strict";var r=n(18),o=n(7),i=n(87),a=[].slice,u={},s=function(e,t,n){if(!(t in u)){for(var r=[],o=0;o<t;o++)r[o]="a["+o+"]";u[t]=Function("F,a","return new F("+r.join(",")+")")}return u[t](e,n)};e.exports=Function.bind||function(e){var t=r(this),n=a.call(arguments,1),u=function(){var r=n.concat(a.call(arguments));return this instanceof u?s(t,r.length,r):i(t,r,e)};return o(t.prototype)&&(u.prototype=t.prototype),u}},function(e,t,n){"use strict";var r=n(11).f,o=n(49),i=n(52),a=n(37),u=n(47),s=n(26),c=n(60),l=n(122),f=n(188),p=n(53),d=n(10),h=n(43).fastKey,v=d?"_s":"size",m=function(e,t){var n,r=h(t);if("F"!==r)return e._i[r];for(n=e._f;n;n=n.n)if(n.k==t)return n};e.exports={getConstructor:function(e,t,n,l){var f=e(function(e,r){u(e,f,t,"_i"),e._i=o(null),e._f=void 0,e._l=void 0,e[v]=0,void 0!=r&&c(r,n,e[l],e)});return i(f.prototype,{clear:function(){for(var e=this,t=e._i,n=e._f;n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete t[n.i];e._f=e._l=void 0,e[v]=0},delete:function(e){var t=this,n=m(t,e);if(n){var r=n.n,o=n.p;delete t._i[n.i],n.r=!0,o&&(o.n=r),r&&(r.p=o),t._f==n&&(t._f=r),t._l==n&&(t._l=o),t[v]--}return!!n},forEach:function(e){u(this,f,"forEach");for(var t,n=a(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.n:this._f;)for(n(t.v,t.k,this);t&&t.r;)t=t.p},has:function(e){return!!m(this,e)}}),d&&r(f.prototype,"size",{get:function(){return s(this[v])}}),f},def:function(e,t,n){var r,o,i=m(e,t);return i?i.v=n:(e._l=i={i:o=h(t,!0),k:t,v:n,p:r=e._l,n:void 0,r:!1},e._f||(e._f=i),r&&(r.n=i),e[v]++,"F"!==o&&(e._i[o]=i)),e},getEntry:m,setStrong:function(e,t,n){l(e,t,function(e,t){this._t=e,this._k=t,this._l=void 0},function(){for(var e=this,t=e._k,n=e._l;n&&n.r;)n=n.p;return e._t&&(e._l=n=n?n.n:e._t._f)?"keys"==t?f(0,n.k):"values"==t?f(0,n.v):f(0,[n.k,n.v]):(e._t=void 0,f(1))},n?"entries":"values",!n,!0),p(t)}}},function(e,t,n){var r=n(72),o=n(179);e.exports=function(e){return function(){if(r(this)!=e)throw TypeError(e+"#toJSON isn't generic");return o(this)}}},function(e,t,n){"use strict";var r=n(52),o=n(43).getWeak,i=n(2),a=n(7),u=n(47),s=n(60),c=n(30),l=n(16),f=c(5),p=c(6),d=0,h=function(e){return e._l||(e._l=new v)},v=function(){this.a=[]},m=function(e,t){return f(e.a,function(e){return e[0]===t})};v.prototype={get:function(e){var t=m(this,e);if(t)return t[1]},has:function(e){return!!m(this,e)},set:function(e,t){var n=m(this,e);n?n[1]=t:this.a.push([e,t])},delete:function(e){var t=p(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},e.exports={getConstructor:function(e,t,n,i){var c=e(function(e,r){u(e,c,t,"_i"),e._i=d++,e._l=void 0,void 0!=r&&s(r,n,e[i],e)});return r(c.prototype,{delete:function(e){if(!a(e))return!1;var t=o(e);return!0===t?h(this).delete(e):t&&l(t,this._i)&&delete t[this._i]},has:function(e){if(!a(e))return!1;var t=o(e);return!0===t?h(this).has(e):t&&l(t,this._i)}}),c},def:function(e,t,n){var r=o(i(t),!0);return!0===r?h(e).set(t,n):r[e._i]=n,e},ufstore:h}},function(e,t,n){e.exports=!n(10)&&!n(5)(function(){return 7!=Object.defineProperty(n(114)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(7),o=Math.floor;e.exports=function(e){return!r(e)&&isFinite(e)&&o(e)===e}},function(e,t,n){var r=n(2);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t){e.exports=Math.log1p||function(e){return(e=+e)>-1e-8&&e<1e-8?e-e*e/2:Math.log(1+e)}},function(e,t,n){"use strict";var r=n(51),o=n(91),i=n(74),a=n(14),u=n(73),s=Object.assign;e.exports=!s||n(5)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=s({},e)[n]||Object.keys(s({},t)).join("")!=r})?function(e,t){for(var n=a(e),s=arguments.length,c=1,l=o.f,f=i.f;s>c;)for(var p,d=u(arguments[c++]),h=l?r(d).concat(l(d)):r(d),v=h.length,m=0;v>m;)f.call(d,p=h[m++])&&(n[p]=d[p]);return n}:s},function(e,t,n){var r=n(11),o=n(2),i=n(51);e.exports=n(10)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),u=a.length,s=0;u>s;)r.f(e,n=a[s++],t[n]);return e}},function(e,t,n){var r=n(22),o=n(50).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],u=function(e){try{return o(e)}catch(e){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?u(e):o(r(e))}},function(e,t,n){var r=n(16),o=n(22),i=n(83)(!1),a=n(127)("IE_PROTO");e.exports=function(e,t){var n,u=o(e),s=0,c=[];for(n in u)n!=a&&r(u,n)&&c.push(n);for(;t.length>s;)r(u,n=t[s++])&&(~i(c,n)||c.push(n));return c}},function(e,t,n){var r=n(51),o=n(22),i=n(74).f;e.exports=function(e){return function(t){for(var n,a=o(t),u=r(a),s=u.length,c=0,l=[];s>c;)i.call(a,n=u[c++])&&l.push(e?[n,a[n]]:a[n]);return l}}},function(e,t,n){var r=n(50),o=n(91),i=n(2),a=n(3).Reflect;e.exports=a&&a.ownKeys||function(e){var t=r.f(i(e)),n=o.f;return n?t.concat(n(e)):t}},function(e,t,n){var r=n(3).parseFloat,o=n(63).trim;e.exports=1/r(n(132)+"-0")!=-1/0?function(e){var t=o(String(e),3),n=r(t);return 0===n&&"-"==t.charAt(0)?-0:n}:r},function(e,t,n){var r=n(3).parseInt,o=n(63).trim,i=n(132),a=/^[\-+]?0[xX]/;e.exports=8!==r(i+"08")||22!==r(i+"0x16")?function(e,t){var n=o(String(e),3);return r(n,t>>>0||(a.test(n)?16:10))}:r},function(e,t){e.exports=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}},function(e,t,n){var r=n(13),o=n(131),i=n(26);e.exports=function(e,t,n,a){var u=String(i(e)),s=u.length,c=void 0===n?" ":String(n),l=r(t);if(l<=s||""==c)return u;var f=l-s,p=o.call(c,Math.ceil(f/c.length));return p.length>f&&(p=p.slice(0,f)),a?p+u:u+p}},function(e,t,n){t.f=n(8)},function(e,t,n){"use strict";var r=n(182);e.exports=n(84)("Map",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=r.getEntry(this,e);return t&&t.v},set:function(e,t){return r.def(this,0===e?0:e,t)}},r,!0)},function(e,t,n){n(10)&&"g"!=/./g.flags&&n(11).f(RegExp.prototype,"flags",{configurable:!0,get:n(86)})},function(e,t,n){"use strict";var r=n(182);e.exports=n(84)("Set",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e=0===e?0:e,e)}},r)},function(e,t,n){"use strict";var r,o=n(30)(0),i=n(20),a=n(43),u=n(190),s=n(184),c=n(7),l=a.getWeak,f=Object.isExtensible,p=s.ufstore,d={},h=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},v={get:function(e){if(c(e)){var t=l(e);return!0===t?p(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return s.def(this,e,t)}},m=e.exports=n(84)("WeakMap",h,v,s,!0,!0);7!=(new m).set((Object.freeze||Object)(d),7).get(d)&&(r=s.getConstructor(h),u(r.prototype,v),a.NEED=!0,o(["delete","has","get","set"],function(e){var t=m.prototype,n=t[e];i(t,e,function(t,o){if(c(t)&&!f(t)){this._f||(this._f=new r);var i=this._f[e](t,o);return"set"==e?this:i}return n.call(this,t,o)})}))},function(e,t,n){"use strict";var r=n(28),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e,t,n){"use strict";function r(e){try{e.focus()}catch(e){}}e.exports=r},function(e,t,n){"use strict";function r(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}e.exports=r},function(e,t,n){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},o={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},i="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,n){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);i&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var u=0;u<a.length;++u)if(!(r[a[u]]||o[a[u]]||n&&n[a[u]]))try{e[a[u]]=t[a[u]]}catch(e){}}return e}},function(e,t,n){"use strict";var r=n(33),o=r.a.Uint8Array;t.a=o},function(e,t,n){"use strict";function r(e,t){var r=n.i(a.a)(e),l=!r&&n.i(i.a)(e),p=!r&&!l&&n.i(u.a)(e),d=!r&&!l&&!p&&n.i(c.a)(e),h=r||l||p||d,v=h?n.i(o.a)(e.length,String):[],m=v.length;for(var y in e)!t&&!f.call(e,y)||h&&("length"==y||p&&("offset"==y||"parent"==y)||d&&("buffer"==y||"byteLength"==y||"byteOffset"==y)||n.i(s.a)(y,m))||v.push(y);return v}var o=n(500),i=n(148),a=n(34),u=n(149),s=n(144),c=n(152),l=Object.prototype,f=l.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e,t){for(var n=-1,r=null==e?0:e.length,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}t.a=r},function(e,t,n){"use strict";function r(e,t,r){(void 0===r||n.i(i.a)(e[t],r))&&(void 0!==r||t in e)||n.i(o.a)(e,t,r)}var o=n(97),i=n(78);t.a=r},function(e,t,n){"use strict";var r=n(510),o=n.i(r.a)();t.a=o},function(e,t,n){"use strict";function r(e,t){t=n.i(o.a)(t,e);for(var r=0,a=t.length;null!=e&&r<a;)e=e[n.i(i.a)(t[r++])];return r&&r==a?e:void 0}var o=n(215),i=n(77);t.a=r},function(e,t,n){"use strict";function r(e,t){return n.i(o.a)(e)?e:n.i(i.a)(e,t)?[e]:n.i(a.a)(n.i(u.a)(e))}var o=n(34),i=n(145),a=n(224),u=n(229);t.a=r},function(e,t,n){"use strict";function r(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}t.a=r},function(e,t,n){"use strict";var r=n(56),o=function(){try{var e=n.i(r.a)(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();t.a=o},function(e,t,n){"use strict";function r(e,t,r,c,l,f){var p=r&u,d=e.length,h=t.length;if(d!=h&&!(p&&h>d))return!1;var v=f.get(e);if(v&&f.get(t))return v==t;var m=-1,y=!0,g=r&s?new o.a:void 0;for(f.set(e,t),f.set(t,e);++m<d;){var b=e[m],_=t[m];if(c)var E=p?c(_,b,m,t,e,f):c(b,_,m,e,t,f);if(void 0!==E){if(E)continue;y=!1;break}if(g){if(!n.i(i.a)(t,function(e,t){if(!n.i(a.a)(g,t)&&(b===e||l(b,e,r,c,f)))return g.push(t)})){y=!1;break}}else if(b!==_&&!l(b,_,r,c,f)){y=!1;break}}return f.delete(e),f.delete(t),y}var o=n(473),i=n(478),a=n(503),u=1,s=2;t.a=r},function(e,t,n){"use strict";(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.a=n}).call(t,n(111))},function(e,t,n){"use strict";var r=n(223),o=n.i(r.a)(Object.getPrototypeOf,Object);t.a=o},function(e,t,n){"use strict";function r(e){return e===e&&!n.i(o.a)(e)}var o=n(46);t.a=r},function(e,t,n){"use strict";function r(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}t.a=r},function(e,t,n){"use strict";function r(e,t){return function(n){return e(t(n))}}t.a=r},function(e,t,n){"use strict";var r=n(540),o=/^\./,i=n.i(r.a)(function(e){var t=[];return o.test(e)&&t.push(""),e.replace(/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,function(e,n,r,o){t.push(r?o.replace(/\\(\\)?/g,"$1"):n||e)}),t});t.a=i},function(e,t,n){"use strict";function r(e){if(null!=e){try{return i.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var o=Function.prototype,i=o.toString;t.a=r},function(e,t,n){"use strict";function r(e,t,r){r="function"==typeof r?r:void 0;var i=r?r(e,t):void 0;return void 0===i?n.i(o.a)(e,t,void 0,r):!!i}var o=n(143);t.a=r},function(e,t,n){"use strict";function r(e){return n.i(a.a)(e)?n.i(o.a)(e,!0):n.i(i.a)(e)}var o=n(210),i=n(491),a=n(100);t.a=r},function(e,t,n){"use strict";function r(e,t){var r={};return t=n.i(a.a)(t,3),n.i(i.a)(e,function(e,i,a){n.i(o.a)(r,i,t(e,i,a))}),r}var o=n(97),i=n(481),a=n(489);t.a=r},function(e,t,n){"use strict";function r(e){return null==e?"":n.i(o.a)(e)}var o=n(501);t.a=r},function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},u={isUnitlessNumber:o,shorthandPropertyExpansions:a};e.exports=u},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(6),i=n(58),a=(n(1),function(){function e(t){r(this,e),this._callbacks=null,this._contexts=null,this._arg=t}return e.prototype.enqueue=function(e,t){this._callbacks=this._callbacks||[],this._callbacks.push(e),this._contexts=this._contexts||[],this._contexts.push(t)},e.prototype.notifyAll=function(){var e=this._callbacks,t=this._contexts,n=this._arg;if(e&&t){e.length!==t.length&&o("24"),this._callbacks=null,this._contexts=null;for(var r=0;r<e.length;r++)e[r].call(t[r],n);e.length=0,t.length=0}},e.prototype.checkpoint=function(){return this._callbacks?this._callbacks.length:0},e.prototype.rollback=function(e){this._callbacks&&this._contexts&&(this._callbacks.length=e,this._contexts.length=e)},e.prototype.reset=function(){this._callbacks=null,this._contexts=null},e.prototype.destructor=function(){this.reset()},e}());e.exports=i.addPoolingTo(a)},function(e,t,n){"use strict";function r(e){return!!c.hasOwnProperty(e)||!s.hasOwnProperty(e)&&(u.test(e)?(c[e]=!0,!0):(s[e]=!0,!1))}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&!1===t}var i=n(66),a=(n(12),n(29),n(630)),u=(n(4),new RegExp("^["+i.ATTRIBUTE_NAME_START_CHAR+"]["+i.ATTRIBUTE_NAME_CHAR+"]*$")),s={},c={},l={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return i.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(i.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&!0===t?r+'=""':r+"="+a(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+a(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+a(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else{if(o(r,n))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty)e[r.propertyName]=n;else{var u=r.attributeName,s=r.attributeNamespace;s?e.setAttributeNS(s,u,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&!0===n?e.setAttribute(u,""):e.setAttribute(u,""+n)}}}else if(i.isCustomAttribute(t))return void l.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){if(r(t)){null==n?e.removeAttribute(t):e.setAttribute(t,""+n)}},deleteValueForAttribute:function(e,t){e.removeAttribute(t)},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:e[o]=""}else e.removeAttribute(n.attributeName)}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};e.exports=l},function(e,t,n){"use strict";var r={hasCachedChildNodes:1};e.exports=r},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=u.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=s.getNodeFromInstance(e).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),c.asap(r,this),n}var a=n(9),u=n(160),s=n(12),c=n(35),l=(n(4),!1),f={getHostProps:function(e,t){return a({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=u.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,listeners:null,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)},void 0===t.value||void 0===t.defaultValue||l||(l=!0)},getSelectValueContext:function(e){return e._wrapperState.initialValue},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=u.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=f},function(e,t,n){"use strict";var r,o={injectEmptyComponentFactory:function(e){r=e}},i={create:function(e){return r(e)}};i.injection=o,e.exports=i},function(e,t,n){"use strict";var r={logTopLevelRenders:!1};e.exports=r},function(e,t,n){"use strict";function r(e){return u||a("111",e.type),new u(e)}function o(e){return new s(e)}function i(e){return e instanceof s}var a=n(6),u=(n(1),null),s=null,c={injectGenericComponentClass:function(e){u=e},injectTextComponentClass:function(e){s=e}},l={createInternalComponent:r,createInstanceForText:o,isTextComponent:i,injection:c};e.exports=l},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(589),i=n(458),a=n(206),u=n(207),s={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if(void 0===r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=s},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===M?e.documentElement:e.firstChild:null}function i(e){return e.getAttribute&&e.getAttribute(R)||""}function a(e,t,n,r,o){var i;if(E.logTopLevelRenders){var a=e._currentElement.props.child,u=a.type;i="React mount: "+("string"==typeof u?u:u.displayName||u.name),console.time(i)}var s=C.mountComponent(e,n,null,b(e,t),o,0);i&&console.timeEnd(i),e._renderedComponent._topLevelWrapper=e,L._mountImageIntoNode(s,t,e,r,n)}function u(e,t,n,r){var o=P.ReactReconcileTransaction.getPooled(!n&&_.useCreateElement);o.perform(a,null,e,t,o,n,r),P.ReactReconcileTransaction.release(o)}function s(e,t,n){for(C.unmountComponent(e,n),t.nodeType===M&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function c(e){var t=o(e);if(t){var n=g.getInstanceFromNode(t);return!(!n||!n._hostParent)}}function l(e){return!(!e||e.nodeType!==N&&e.nodeType!==M&&e.nodeType!==j)}function f(e){var t=o(e),n=t&&g.getInstanceFromNode(t);return n&&!n._hostParent?n:null}function p(e){var t=f(e);return t?t._hostContainerInfo._topLevelWrapper:null}var d=n(6),h=n(65),v=n(66),m=n(69),y=n(104),g=(n(41),n(12)),b=n(583),_=n(585),E=n(236),w=n(81),x=(n(29),n(599)),C=n(67),S=n(163),P=n(35),O=n(75),T=n(246),k=(n(1),n(108)),A=n(169),R=(n(4),v.ID_ATTRIBUTE_NAME),I=v.ROOT_ATTRIBUTE_NAME,N=1,M=9,j=11,F={},D=1,U=function(){this.rootID=D++};U.prototype.isReactComponent={},U.prototype.render=function(){return this.props.child},U.isReactTopLevelWrapper=!0;var L={TopLevelWrapper:U,_instancesByReactRootID:F,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r,o){return L.scrollMonitor(r,function(){S.enqueueElementInternal(e,t,n),o&&S.enqueueCallbackInternal(e,o)}),e},_renderNewRootComponent:function(e,t,n,r){l(t)||d("37"),y.ensureScrollValueMonitoring();var o=T(e,!1);P.batchedUpdates(u,o,t,n,r);var i=o._instance.rootID;return F[i]=o,o},renderSubtreeIntoContainer:function(e,t,n,r){return null!=e&&w.has(e)||d("38"),L._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){S.validateCallback(r,"ReactDOM.render"),m.isValidElement(t)||d("39","string"==typeof t?" Instead of passing a string like 'div', pass React.createElement('div') or <div />.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or <Foo />.":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":"");var a,u=m.createElement(U,{child:t});if(e){var s=w.get(e);a=s._processChildContext(s._context)}else a=O;var l=p(n);if(l){var f=l._currentElement,h=f.props.child;if(A(h,t)){var v=l._renderedComponent.getPublicInstance(),y=r&&function(){r.call(v)};return L._updateRootComponent(l,u,a,n,y),v}L.unmountComponentAtNode(n)}var g=o(n),b=g&&!!i(g),_=c(n),E=b&&!l&&!_,x=L._renderNewRootComponent(u,n,E,a)._renderedComponent.getPublicInstance();return r&&r.call(x),x},render:function(e,t,n){return L._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){l(e)||d("40");var t=p(e);if(!t){c(e),1===e.nodeType&&e.hasAttribute(I);return!1}return delete F[t._instance.rootID],P.batchedUpdates(s,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,i,a){if(l(t)||d("41"),i){var u=o(t);if(x.canReuseMarkup(e,u))return void g.precacheNode(n,u);var s=u.getAttribute(x.CHECKSUM_ATTR_NAME);u.removeAttribute(x.CHECKSUM_ATTR_NAME);var c=u.outerHTML;u.setAttribute(x.CHECKSUM_ATTR_NAME,s);var f=e,p=r(f,c),v=" (client) "+f.substring(p-20,p+20)+"\n (server) "+c.substring(p-20,p+20);t.nodeType===M&&d("42",v)}if(t.nodeType===M&&d("43"),a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);h.insertTreeBefore(t,e,null)}else k(t,e),g.precacheNode(n,t.firstChild)}};e.exports=L},function(e,t,n){"use strict";var r=n(6),o=n(69),i=(n(1),{HOST:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||!1===e?i.EMPTY:o.isValidElement(e)?"function"==typeof e.type?i.COMPOSITE:i.HOST:void r("26",e)}});e.exports=i},function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};e.exports=r},function(e,t,n){"use strict";function r(e,t){return null==t&&o("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}var o=n(6);n(1);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}e.exports=r},function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.HOST?e._renderedComponent:t===o.EMPTY?null:void 0}var o=n(240);e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(17),i=null;e.exports=r},function(e,t,n){"use strict";function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function o(e){return"function"==typeof e&&void 0!==e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e,t){var n;if(null===e||!1===e)n=c.create(i);else if("object"==typeof e){var u=e,s=u.type;if("function"!=typeof s&&"string"!=typeof s){var p="";p+=r(u._owner),a("130",null==s?s:typeof s,p)}"string"==typeof u.type?n=l.createInternalComponent(u):o(u.type)?(n=new u.type(u),n.getHostNode||(n.getHostNode=n.getNativeNode)):n=new f(u)}else"string"==typeof e||"number"==typeof e?n=l.createInstanceForText(e):a("131",typeof e);return n._mountIndex=0,n._mountImage=null,n}var a=n(6),u=n(9),s=n(580),c=n(235),l=n(237),f=(n(627),n(1),n(4),function(e){this.construct(e)});u(f.prototype,s,{_instantiateReactComponent:i}),e.exports=i},function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!o[e.type]:"textarea"===t}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=r},function(e,t,n){"use strict";var r=n(17),o=n(107),i=n(108),a=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){if(3===e.nodeType)return void(e.nodeValue=t);i(e,o(t))})),e.exports=a},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===u)return n(i,e,""===t?l+r(e,0):t),1;var d,h,v=0,m=""===t?l:t+f;if(Array.isArray(e))for(var y=0;y<e.length;y++)d=e[y],h=m+r(d,y),v+=o(d,h,n,i);else{var g=s(e);if(g){var b,_=g.call(e);if(g!==e.entries)for(var E=0;!(b=_.next()).done;)d=b.value,h=m+r(d,E++),v+=o(d,h,n,i);else for(;!(b=_.next()).done;){var w=b.value;w&&(d=w[1],h=m+c.escape(w[0])+f+r(d,0),v+=o(d,h,n,i))}}else if("object"===p){var x="",C=String(e);a("31","[object Object]"===C?"object with keys {"+Object.keys(e).join(", ")+"}":C,x)}}return v}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(6),u=(n(41),n(595)),s=n(626),c=(n(1),n(159)),l=(n(4),"."),f=":";e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function u(){}function s(e,t){var n={run:function(r){try{var o=e(t.getState(),r);(o!==n.props||n.error)&&(n.shouldComponentUpdate=!0,n.props=o,n.error=null)}catch(e){n.shouldComponentUpdate=!0,n.error=e}}};return n}function c(e){var t,c,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},p=l.getDisplayName,_=void 0===p?function(e){return"ConnectAdvanced("+e+")"}:p,E=l.methodName,w=void 0===E?"connectAdvanced":E,x=l.renderCountProp,C=void 0===x?void 0:x,S=l.shouldHandleStateChanges,P=void 0===S||S,O=l.storeKey,T=void 0===O?"store":O,k=l.withRef,A=void 0!==k&&k,R=a(l,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef"]),I=T+"Subscription",N=g++,M=(t={},t[T]=m.a,t[I]=m.b,t),j=(c={},c[I]=m.b,c);return function(t){d()("function"==typeof t,"You must pass a component to the function returned by connect. Instead received "+JSON.stringify(t));var a=t.displayName||t.name||"Component",c=_(a),l=y({},R,{getDisplayName:_,methodName:w,renderCountProp:C,shouldHandleStateChanges:P,storeKey:T,withRef:A,displayName:c,wrappedComponentName:a,WrappedComponent:t}),p=function(a){function f(e,t){r(this,f);var n=o(this,a.call(this,e,t));return n.version=N,n.state={},n.renderCount=0,n.store=e[T]||t[T],n.propsMode=Boolean(e[T]),n.setWrappedInstance=n.setWrappedInstance.bind(n),d()(n.store,'Could not find "'+T+'" in either the context or props of "'+c+'". Either wrap the root component in a <Provider>, or explicitly pass "'+T+'" as a prop to "'+c+'".'),n.initSelector(),n.initSubscription(),n}return i(f,a),f.prototype.getChildContext=function(){var e,t=this.propsMode?null:this.subscription;return e={},e[I]=t||this.context[I],e},f.prototype.componentDidMount=function(){P&&(this.subscription.trySubscribe(),this.selector.run(this.props),this.selector.shouldComponentUpdate&&this.forceUpdate())},f.prototype.componentWillReceiveProps=function(e){this.selector.run(e)},f.prototype.shouldComponentUpdate=function(){return this.selector.shouldComponentUpdate},f.prototype.componentWillUnmount=function(){this.subscription&&this.subscription.tryUnsubscribe(),this.subscription=null,this.notifyNestedSubs=u,this.store=null,this.selector.run=u,this.selector.shouldComponentUpdate=!1},f.prototype.getWrappedInstance=function(){return d()(A,"To access the wrapped instance, you need to specify { withRef: true } in the options argument of the "+w+"() call."),this.wrappedInstance},f.prototype.setWrappedInstance=function(e){this.wrappedInstance=e},f.prototype.initSelector=function(){var t=e(this.store.dispatch,l);this.selector=s(t,this.store),this.selector.run(this.props)},f.prototype.initSubscription=function(){if(P){var e=(this.propsMode?this.props:this.context)[I];this.subscription=new v.a(this.store,e,this.onStateChange.bind(this)),this.notifyNestedSubs=this.subscription.notifyNestedSubs.bind(this.subscription)}},f.prototype.onStateChange=function(){this.selector.run(this.props),this.selector.shouldComponentUpdate?(this.componentDidUpdate=this.notifyNestedSubsOnComponentDidUpdate,this.setState(b)):this.notifyNestedSubs()},f.prototype.notifyNestedSubsOnComponentDidUpdate=function(){this.componentDidUpdate=void 0,this.notifyNestedSubs()},f.prototype.isSubscribed=function(){return Boolean(this.subscription)&&this.subscription.isSubscribed()},f.prototype.addExtraProps=function(e){if(!(A||C||this.propsMode&&this.subscription))return e;var t=y({},e);return A&&(t.ref=this.setWrappedInstance),C&&(t[C]=this.renderCount++),this.propsMode&&this.subscription&&(t[I]=this.subscription),t},f.prototype.render=function(){var e=this.selector;if(e.shouldComponentUpdate=!1,e.error)throw e.error;return n.i(h.createElement)(t,this.addExtraProps(e.props))},f}(h.Component);return p.WrappedComponent=t,p.displayName=c,p.childContextTypes=j,p.contextTypes=M,p.propTypes=M,f()(p,t)}}var l=n(208),f=n.n(l),p=n(76),d=n.n(p),h=n(15),v=(n.n(h),n(639)),m=n(252);t.a=c;var y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},g=0,b={}},function(e,t,n){"use strict";function r(e){return function(t,n){function r(){return o}var o=e(t,n);return r.dependsOnOwnProps=!1,r}}function o(e){return null!==e.dependsOnOwnProps&&void 0!==e.dependsOnOwnProps?Boolean(e.dependsOnOwnProps):1!==e.length}function i(e,t){return function(t,n){var r=(n.displayName,function(e,t){return r.dependsOnOwnProps?r.mapToProps(e,t):r.mapToProps(e)});return r.dependsOnOwnProps=!0,r.mapToProps=function(t,n){r.mapToProps=e,r.dependsOnOwnProps=o(e);var i=r(t,n);return"function"==typeof i&&(r.mapToProps=i,r.dependsOnOwnProps=o(i),i=r(t,n)),i},r}}n(253);t.b=r,t.a=i},function(e,t,n){"use strict";var r=n(15);n.n(r);n.d(t,"b",function(){return o}),n.d(t,"a",function(){return i});var o=r.PropTypes.shape({trySubscribe:r.PropTypes.func.isRequired,tryUnsubscribe:r.PropTypes.func.isRequired,notifyNestedSubs:r.PropTypes.func.isRequired,isSubscribed:r.PropTypes.func.isRequired}),i=r.PropTypes.shape({subscribe:r.PropTypes.func.isRequired,dispatch:r.PropTypes.func.isRequired,getState:r.PropTypes.func.isRequired})},function(e,t,n){"use strict";n(101),n(171)},function(e,t,n){"use strict";function r(e){var t=Function.prototype.toString,n=Object.prototype.hasOwnProperty,r=RegExp("^"+t.call(n).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");try{var o=t.call(e);return r.test(o)}catch(e){return!1}}function o(e){var t=c(e);if(t){var n=t.childIDs;l(e),n.forEach(o)}}function i(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}function a(e){return null==e?"#empty":"string"==typeof e||"number"==typeof e?"#text":"string"==typeof e.type?e.type:e.type.displayName||e.type.name||"Unknown"}function u(e){var t,n=S.getDisplayName(e),r=S.getElement(e),o=S.getOwnerID(e);return o&&(t=S.getDisplayName(o)),i(n,r&&r._source,t)}var s,c,l,f,p,d,h,v=n(71),m=n(41),y=(n(1),n(4),"function"==typeof Array.from&&"function"==typeof Map&&r(Map)&&null!=Map.prototype&&"function"==typeof Map.prototype.keys&&r(Map.prototype.keys)&&"function"==typeof Set&&r(Set)&&null!=Set.prototype&&"function"==typeof Set.prototype.keys&&r(Set.prototype.keys));if(y){var g=new Map,b=new Set;s=function(e,t){g.set(e,t)},c=function(e){return g.get(e)},l=function(e){g.delete(e)},f=function(){return Array.from(g.keys())},p=function(e){b.add(e)},d=function(e){b.delete(e)},h=function(){return Array.from(b.keys())}}else{var _={},E={},w=function(e){return"."+e},x=function(e){return parseInt(e.substr(1),10)};s=function(e,t){var n=w(e);_[n]=t},c=function(e){var t=w(e);return _[t]},l=function(e){var t=w(e);delete _[t]},f=function(){return Object.keys(_).map(x)},p=function(e){var t=w(e);E[t]=!0},d=function(e){var t=w(e);delete E[t]},h=function(){return Object.keys(E).map(x)}}var C=[],S={onSetChildren:function(e,t){var n=c(e);n||v("144"),n.childIDs=t;for(var r=0;r<t.length;r++){var o=t[r],i=c(o);i||v("140"),null==i.childIDs&&"object"==typeof i.element&&null!=i.element&&v("141"),i.isMounted||v("71"),null==i.parentID&&(i.parentID=e),i.parentID!==e&&v("142",o,i.parentID,e)}},onBeforeMountComponent:function(e,t,n){s(e,{element:t,parentID:n,text:null,childIDs:[],isMounted:!1,updateCount:0})},onBeforeUpdateComponent:function(e,t){var n=c(e);n&&n.isMounted&&(n.element=t)},onMountComponent:function(e){var t=c(e);t||v("144"),t.isMounted=!0,0===t.parentID&&p(e)},onUpdateComponent:function(e){var t=c(e);t&&t.isMounted&&t.updateCount++},onUnmountComponent:function(e){var t=c(e);if(t){t.isMounted=!1;0===t.parentID&&d(e)}C.push(e)},purgeUnmountedComponents:function(){if(!S._preventPurging){for(var e=0;e<C.length;e++){o(C[e])}C.length=0}},isMounted:function(e){var t=c(e);return!!t&&t.isMounted},getCurrentStackAddendum:function(e){var t="";if(e){var n=a(e),r=e._owner;t+=i(n,e._source,r&&r.getName())}var o=m.current,u=o&&o._debugID;return t+=S.getStackAddendumByID(u)},getStackAddendumByID:function(e){for(var t="";e;)t+=u(e),e=S.getParentID(e);return t},getChildIDs:function(e){var t=c(e);return t?t.childIDs:[]},getDisplayName:function(e){var t=S.getElement(e);return t?a(t):null},getElement:function(e){var t=c(e);return t?t.element:null},getOwnerID:function(e){var t=S.getElement(e);return t&&t._owner?t._owner._debugID:null},getParentID:function(e){var t=c(e);return t?t.parentID:null},getSource:function(e){var t=c(e),n=t?t.element:null;return null!=n?n._source:null},getText:function(e){var t=S.getElement(e);return"string"==typeof t?t:"number"==typeof t?""+t:null},getUpdateCount:function(e){var t=c(e);return t?t.updateCount:0},getRootIDs:h,getRegisteredIDs:f};e.exports=S},function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=r},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";var r=!1;e.exports=r},function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(455),u=n.n(a),s=function(e){function t(e){r(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,"Submit Validation Failed"));return n.errors=e,n}return i(t,e),t}(u.a);t.a=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(174);n.d(t,"arrayInsert",function(){return i}),n.d(t,"arrayMove",function(){return a}),n.d(t,"arrayPop",function(){return u}),n.d(t,"arrayPush",function(){return s}),n.d(t,"arrayRemove",function(){return c}),n.d(t,"arrayRemoveAll",function(){return l}),n.d(t,"arrayShift",function(){return f}),n.d(t,"arraySplice",function(){return p}),n.d(t,"arraySwap",function(){return d}),n.d(t,"arrayUnshift",function(){return h}),n.d(t,"autofill",function(){return v}),n.d(t,"blur",function(){return m}),n.d(t,"change",function(){return y}),n.d(t,"clearSubmit",function(){return g}),n.d(t,"clearSubmitErrors",function(){return b}),n.d(t,"clearAsyncError",function(){return _}),n.d(t,"destroy",function(){return E}),n.d(t,"focus",function(){return w}),n.d(t,"initialize",function(){return x}),n.d(t,"registerField",function(){return C}),n.d(t,"reset",function(){return S}),n.d(t,"startAsyncValidation",function(){return P}),n.d(t,"startSubmit",function(){return O}),n.d(t,"stopAsyncValidation",function(){return T}),n.d(t,"stopSubmit",function(){return k}),n.d(t,"submit",function(){return A}),n.d(t,"setSubmitFailed",function(){return R}),n.d(t,"setSubmitSucceeded",function(){return I}),n.d(t,"touch",function(){return N}),n.d(t,"unregisterField",function(){return M}),n.d(t,"untouch",function(){return j}),n.d(t,"updateSyncErrors",function(){return F}),n.d(t,"updateSyncWarnings",function(){return D});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=function(e,t,n,o){return{type:r.ARRAY_INSERT,meta:{form:e,field:t,index:n},payload:o}},a=function(e,t,n,o){return{type:r.ARRAY_MOVE,meta:{form:e,field:t,from:n,to:o}}},u=function(e,t){return{type:r.ARRAY_POP,meta:{form:e,field:t}}},s=function(e,t,n){return{type:r.ARRAY_PUSH,meta:{form:e,field:t},payload:n}},c=function(e,t,n){return{type:r.ARRAY_REMOVE,meta:{form:e,field:t,index:n}}},l=function(e,t){return{type:r.ARRAY_REMOVE_ALL,meta:{form:e,field:t}}},f=function(e,t){return{type:r.ARRAY_SHIFT,meta:{form:e,field:t}}},p=function(e,t,n,o,i){var a={type:r.ARRAY_SPLICE,meta:{form:e,field:t,index:n,removeNum:o}};return void 0!==i&&(a.payload=i),a},d=function(e,t,n,o){if(n===o)throw new Error("Swap indices cannot be equal");if(n<0||o<0)throw new Error("Swap indices cannot be negative");return{type:r.ARRAY_SWAP,meta:{form:e,field:t,indexA:n,indexB:o}}},h=function(e,t,n){return{type:r.ARRAY_UNSHIFT,meta:{form:e,field:t},payload:n}},v=function(e,t,n){return{type:r.AUTOFILL,meta:{form:e,field:t},payload:n}},m=function(e,t,n,o){return{type:r.BLUR,meta:{form:e,field:t,touch:o},payload:n}},y=function(e,t,n,o,i){return{type:r.CHANGE,meta:{form:e,field:t,touch:o,persistentSubmitErrors:i},payload:n}},g=function(e){return{type:r.CLEAR_SUBMIT,meta:{form:e}}},b=function(e){return{type:r.CLEAR_SUBMIT_ERRORS,meta:{form:e}}},_=function(e,t){return{type:r.CLEAR_ASYNC_ERROR,meta:{form:e,field:t}}},E=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return{type:r.DESTROY,meta:{form:t}}},w=function(e,t){return{type:r.FOCUS,meta:{form:e,field:t}}},x=function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return n instanceof Object&&(i=n,n=!1),{type:r.INITIALIZE,meta:o({form:e,keepDirty:n},i),payload:t}},C=function(e,t,n){return{type:r.REGISTER_FIELD,meta:{form:e},payload:{name:t,type:n}}},S=function(e){return{type:r.RESET,meta:{form:e}}},P=function(e,t){return{type:r.START_ASYNC_VALIDATION,meta:{form:e,field:t}}},O=function(e){return{type:r.START_SUBMIT,meta:{form:e}}},T=function(e,t){var n={type:r.STOP_ASYNC_VALIDATION,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(n.error=!0),n},k=function(e,t){var n={type:r.STOP_SUBMIT,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(n.error=!0),n},A=function(e){return{type:r.SUBMIT,meta:{form:e}}},R=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.SET_SUBMIT_FAILED,meta:{form:e,fields:n},error:!0}},I=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.SET_SUBMIT_SUCCEEDED,meta:{form:e,fields:n},error:!1}},N=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.TOUCH,meta:{form:e,fields:n}}},M=function(e,t){var n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];return{type:r.UNREGISTER_FIELD,meta:{form:e},payload:{name:t,destroyOnUnmount:n}}},j=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.UNTOUCH,meta:{form:e,fields:n}}},F=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return{type:r.UPDATE_SYNC_ERRORS,meta:{form:e},payload:{syncErrors:t,error:n}}},D=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return{type:r.UPDATE_SYNC_WARNINGS,meta:{form:e},payload:{syncWarnings:t,warning:n}}}},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=function(e,t,n){var r=t.value;return"checkbox"===e?o({},t,{checked:!!r}):"radio"===e?o({},t,{checked:r===n,value:n}):"select-multiple"===e?o({},t,{value:r||[]}):"file"===e?o({},t,{value:r||void 0}):t},a=function(e,t,n){var a=e.getIn,u=e.toJS,s=n.asyncError,c=n.asyncValidating,l=n.onBlur,f=n.onChange,p=n.onDrop,d=n.onDragStart,h=n.dirty,v=n.dispatch,m=n.onFocus,y=n.form,g=n.format,b=(n.parse,n.pristine),_=n.props,E=n.state,w=n.submitError,x=n.submitFailed,C=n.submitting,S=n.syncError,P=n.syncWarning,O=(n.validate,n.value),T=n._value,k=(n.warn,r(n,["asyncError","asyncValidating","onBlur","onChange","onDrop","onDragStart","dirty","dispatch","onFocus","form","format","parse","pristine","props","state","submitError","submitFailed","submitting","syncError","syncWarning","validate","value","_value","warn"])),A=S||s||w,R=P,I=function(e,n){if(null===n)return e;var r=null==e?"":e;return n?n(e,t):r}(O,g);return{input:i(k.type,{name:t,onBlur:l,onChange:f,onDragStart:d,onDrop:p,onFocus:m,value:I},T),meta:o({},u(E),{active:!(!E||!a(E,"active")),asyncValidating:c,autofilled:!(!E||!a(E,"autofilled")),dirty:h,dispatch:v,error:A,form:y,warning:R,invalid:!!A,pristine:b,submitting:!!C,submitFailed:!!x,touched:!(!E||!a(E,"touched")),valid:!A,visited:!(!E||!a(E,"visited"))}),custom:o({},k,_)}};t.a=a},function(e,t,n){"use strict";var r=function(e){return!!(e&&e.stopPropagation&&e.preventDefault)};t.a=r},function(e,t,n){"use strict";var r=n(667),o=n(673),i=function(e,t){var i=t.name,a=t.parse,u=t.normalize,s=n.i(r.a)(e,o.a);return a&&(s=a(s,i)),u&&(s=u(i,s)),s};t.a=i},function(e,t,n){"use strict";var r=n(262),o=function(e){var t=n.i(r.a)(e);return t&&e.preventDefault(),t};t.a=o},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(662),o=n(42);n.d(t,"actionTypes",function(){return a}),n.d(t,"arrayInsert",function(){return u}),n.d(t,"arrayMove",function(){return s}),n.d(t,"arrayPop",function(){return c}),n.d(t,"arrayPush",function(){return l}),n.d(t,"arrayRemove",function(){return f}),n.d(t,"arrayRemoveAll",function(){return p}),n.d(t,"arrayShift",function(){return d}),n.d(t,"arraySplice",function(){return h}),n.d(t,"arraySwap",function(){return v}),n.d(t,"arrayUnshift",function(){return m}),n.d(t,"autofill",function(){return y}),n.d(t,"blur",function(){return g}),n.d(t,"change",function(){return b}),n.d(t,"clearSubmitErrors",function(){return _}),n.d(t,"destroy",function(){return E}),n.d(t,"Field",function(){return w}),n.d(t,"Fields",function(){return x}),n.d(t,"FieldArray",function(){return C}),n.d(t,"Form",function(){return S}),n.d(t,"FormSection",function(){return P}),n.d(t,"focus",function(){return O}),n.d(t,"formValueSelector",function(){return T}),n.d(t,"getFormNames",function(){return k}),n.d(t,"getFormValues",function(){return A}),n.d(t,"getFormInitialValues",function(){return R}),n.d(t,"getFormSyncErrors",function(){return I}),n.d(t,"getFormAsyncErrors",function(){return N}),n.d(t,"getFormSyncWarnings",function(){return M}),n.d(t,"getFormSubmitErrors",function(){return j}),n.d(t,"initialize",function(){return F}),n.d(t,"isDirty",function(){return D}),n.d(t,"isInvalid",function(){return U}),n.d(t,"isPristine",function(){return L}),n.d(t,"isValid",function(){return V}),n.d(t,"isSubmitting",function(){return B}),n.d(t,"hasSubmitSucceeded",function(){return W}),n.d(t,"hasSubmitFailed",function(){return q}),n.d(t,"propTypes",function(){return H}),n.d(t,"reducer",function(){return z}),n.d(t,"reduxForm",function(){return Y}),n.d(t,"registerField",function(){return K}),n.d(t,"reset",function(){return G}),n.d(t,"setSubmitFailed",function(){return $}),n.d(t,"setSubmitSucceeded",function(){return X}),n.d(t,"startAsyncValidation",function(){return Q}),n.d(t,"startSubmit",function(){return J}),n.d(t,"stopAsyncValidation",function(){return Z}),n.d(t,"stopSubmit",function(){return ee}),n.d(t,"submit",function(){return te}),n.d(t,"SubmissionError",function(){return ne}),n.d(t,"touch",function(){return re}),n.d(t,"unregisterField",function(){return oe}),n.d(t,"untouch",function(){return ie}),n.d(t,"values",function(){return ae});var i=n.i(r.a)(o.a),a=i.actionTypes,u=i.arrayInsert,s=i.arrayMove,c=i.arrayPop,l=i.arrayPush,f=i.arrayRemove,p=i.arrayRemoveAll,d=i.arrayShift,h=i.arraySplice,v=i.arraySwap,m=i.arrayUnshift,y=i.autofill,g=i.blur,b=i.change,_=i.clearSubmitErrors,E=i.destroy,w=i.Field,x=i.Fields,C=i.FieldArray,S=i.Form,P=i.FormSection,O=i.focus,T=i.formValueSelector,k=i.getFormNames,A=i.getFormValues,R=i.getFormInitialValues,I=i.getFormSyncErrors,N=i.getFormAsyncErrors,M=i.getFormSyncWarnings,j=i.getFormSubmitErrors,F=i.initialize,D=i.isDirty,U=i.isInvalid,L=i.isPristine,V=i.isValid,B=i.isSubmitting,W=i.hasSubmitSucceeded,q=i.hasSubmitFailed,H=i.propTypes,z=i.reducer,Y=i.reduxForm,K=i.registerField,G=i.reset,$=i.setSubmitFailed,X=i.setSubmitSucceeded,Q=i.startAsyncValidation,J=i.startSubmit,Z=i.stopAsyncValidation,ee=i.stopSubmit,te=i.submit,ne=i.SubmissionError,re=i.touch,oe=i.unregisterField,ie=i.untouch,ae=i.values},function(e,t,n){"use strict";var r=function(e){var t=e.deepEqual,n=e.empty,r=e.getIn;return function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return r(e,"form")};return function(i){var a=o(i),u=r(a,e+".initial")||n,s=r(a,e+".values")||u;return t(u,s)}}};t.a=r},function(e,t,n){"use strict";var r=n(226),o=function(e,t,n,r,o,i){if(i)return e===t},i=function(e,t,i){return!n.i(r.a)(e.props,t,o)||!n.i(r.a)(e.state,i,o)};t.a=i},function(e,t,n){"use strict";function r(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0===t.length)return function(e){return e};if(1===t.length)return t[0];var r=t[t.length-1],o=t.slice(0,-1);return function(){return o.reduceRight(function(e,t){return t(e)},r.apply(void 0,arguments))}}t.a=r},function(e,t,n){"use strict";function r(e,t,i){function s(){g===y&&(g=y.slice())}function c(){return m}function l(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return s(),g.push(e),function(){if(t){t=!1,s();var n=g.indexOf(e);g.splice(n,1)}}}function f(e){if(!n.i(o.a)(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(b)throw new Error("Reducers may not dispatch actions.");try{b=!0,m=v(m,e)}finally{b=!1}for(var t=y=g,r=0;r<t.length;r++)t[r]();return e}function p(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");v=e,f({type:u.INIT})}function d(){var e,t=l;return e={subscribe:function(e){function n(){e.next&&e.next(c())}if("object"!=typeof e)throw new TypeError("Expected the observer to be an object.");return n(),{unsubscribe:t(n)}}},e[a.a]=function(){return this},e}var h;if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error("Expected the enhancer to be a function.");return i(r)(e,t)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");var v=e,m=t,y=[],g=y,b=!1;return f({type:u.INIT}),h={dispatch:f,subscribe:l,getState:c,replaceReducer:p},h[a.a]=d,h}var o=n(101),i=n(702),a=n.n(i);n.d(t,"b",function(){return u}),t.a=r;var u={INIT:"@@redux/INIT"}},function(e,t,n){"use strict"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o=n(15),i=r(o),a=n(567),u=r(a),s=n(68),c=n(110),l=n(265),f=n(652),p=document.getElementById("content"),d=(0,c.combineReducers)({form:l.reducer}),h=(window.devToolsExtension?window.devToolsExtension()(c.createStore):c.createStore)(d),v=function(e){return new Promise(function(t){setTimeout(function(){window.alert("You submitted:\n\n"+JSON.stringify(e,null,2)),t()},500)})},m=function(){var e=n(273).default,t=n(468),r=n(566);u.default.render(i.default.createElement(s.Provider,{store:h},i.default.createElement(f.App,{version:"6.6.2",path:"/examples/syncValidation",breadcrumbs:(0,f.generateExampleBreadcrumbs)("syncValidation","Synchronous Validation Example","6.6.2")},i.default.createElement(f.Markdown,{content:t}),i.default.createElement("h2",null,"Form"),i.default.createElement(e,{onSubmit:v}),i.default.createElement(f.Values,{form:"syncValidation"}),i.default.createElement("h2",null,"Code"),i.default.createElement("h3",null,"SyncValidationForm.js"),i.default.createElement(f.Code,{source:r}))),p)};m()},function(e,t,n){"use strict";(function(e){function t(e,t,n){e[t]||Object[r](e,t,{writable:!0,configurable:!0,value:n})}if(n(454),n(701),n(274),e._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");e._babelPolyfill=!0;var r="defineProperty";t(String.prototype,"padLeft","".padStart),t(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(e){[][e]&&t(Array,e,Function.call.bind([][e]))})}).call(t,n(111))},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(15),i=function(e){return e&&e.__esModule?e:{default:e}}(o),a=n(265),u=function(e){var t={};return e.username?e.username.length>15&&(t.username="Must be 15 characters or less"):t.username="Required",e.email?/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(e.email)||(t.email="Invalid email address"):t.email="Required",e.age?isNaN(Number(e.age))?t.age="Must be a number":Number(e.age)<18&&(t.age="Sorry, you must be at least 18 years old"):t.age="Required",t},s=function(e){var t={};return e.age<19&&(t.age="Hmm, you seem a bit young..."),t},c=function(e){var t=e.input,n=e.label,o=e.type,a=e.meta,u=a.touched,s=a.error,c=a.warning;return i.default.createElement("div",null,i.default.createElement("label",null,n),i.default.createElement("div",null,i.default.createElement("input",r({},t,{placeholder:n,type:o})),u&&(s&&i.default.createElement("span",null,s)||c&&i.default.createElement("span",null,c))))},l=function(e){var t=e.handleSubmit,n=e.pristine,r=e.reset,o=e.submitting;return i.default.createElement("form",{onSubmit:t},i.default.createElement(a.Field,{name:"username",type:"text",component:c,label:"Username"}),i.default.createElement(a.Field,{name:"email",type:"email",component:c,label:"Email"}),i.default.createElement(a.Field,{name:"age",type:"number",component:c,label:"Age"}),i.default.createElement("div",null,i.default.createElement("button",{type:"submit",disabled:o},"Submit"),i.default.createElement("button",{type:"button",disabled:n||o,onClick:r},"Clear Values")))};t.default=(0,a.reduxForm)({form:"syncValidation",validate:u,warn:s})(l)},function(e,t,n){n(283),e.exports=n(36).RegExp.escape},function(e,t,n){var r=n(7),o=n(120),i=n(8)("species");e.exports=function(e){var t;return o(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!o(t.prototype)||(t=void 0),r(t)&&null===(t=t[i])&&(t=void 0)),void 0===t?Array:t}},function(e,t,n){var r=n(275);e.exports=function(e,t){return new(r(e))(t)}},function(e,t,n){"use strict";var r=n(2),o=n(32);e.exports=function(e){if("string"!==e&&"number"!==e&&"default"!==e)throw TypeError("Incorrect hint");return o(r(this),"number"!=e)}},function(e,t,n){var r=n(51),o=n(91),i=n(74);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,u=n(e),s=i.f,c=0;u.length>c;)s.call(e,a=u[c++])&&t.push(a);return t}},function(e,t,n){var r=n(51),o=n(22);e.exports=function(e,t){for(var n,i=o(e),a=r(i),u=a.length,s=0;u>s;)if(i[n=a[s++]]===t)return n}},function(e,t,n){"use strict";var r=n(281),o=n(87),i=n(18);e.exports=function(){for(var e=i(this),t=arguments.length,n=Array(t),a=0,u=r._,s=!1;t>a;)(n[a]=arguments[a++])===u&&(s=!0);return function(){var r,i=this,a=arguments.length,c=0,l=0;if(!s&&!a)return o(e,n,i);if(r=n.slice(),s)for(;t>c;c++)r[c]===u&&(r[c]=arguments[l++]);for(;a>l;)r.push(arguments[l++]);return o(e,r,i)}}},function(e,t,n){e.exports=n(3)},function(e,t){e.exports=function(e,t){var n=t===Object(t)?function(e){return t[e]}:t;return function(t){return String(t).replace(e,n)}}},function(e,t,n){var r=n(0),o=n(282)(/[\\^$*+?.()|[\]{}]/g,"\\$&");r(r.S,"RegExp",{escape:function(e){return o(e)}})},function(e,t,n){var r=n(0);r(r.P,"Array",{copyWithin:n(178)}),n(59)("copyWithin")},function(e,t,n){"use strict";var r=n(0),o=n(30)(4);r(r.P+r.F*!n(27)([].every,!0),"Array",{every:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(0);r(r.P,"Array",{fill:n(112)}),n(59)("fill")},function(e,t,n){"use strict";var r=n(0),o=n(30)(2);r(r.P+r.F*!n(27)([].filter,!0),"Array",{filter:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(30)(6),i="findIndex",a=!0;i in[]&&Array(1)[i](function(){a=!1}),r(r.P+r.F*a,"Array",{findIndex:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(59)(i)},function(e,t,n){"use strict";var r=n(0),o=n(30)(5),i=!0;"find"in[]&&Array(1).find(function(){i=!1}),r(r.P+r.F*i,"Array",{find:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(59)("find")},function(e,t,n){"use strict";var r=n(0),o=n(30)(0),i=n(27)([].forEach,!0);r(r.P+r.F*!i,"Array",{forEach:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(37),o=n(0),i=n(14),a=n(187),u=n(119),s=n(13),c=n(113),l=n(136);o(o.S+o.F*!n(89)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,f,p=i(e),d="function"==typeof this?this:Array,h=arguments.length,v=h>1?arguments[1]:void 0,m=void 0!==v,y=0,g=l(p);if(m&&(v=r(v,h>2?arguments[2]:void 0,2)),void 0==g||d==Array&&u(g))for(t=s(p.length),n=new d(t);t>y;y++)c(n,y,m?v(p[y],y):p[y]);else for(f=g.call(p),n=new d;!(o=f.next()).done;y++)c(n,y,m?a(f,v,[o.value,y],!0):o.value);return n.length=y,n}})},function(e,t,n){"use strict";var r=n(0),o=n(83)(!1),i=[].indexOf,a=!!i&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(a||!n(27)(i)),"Array",{indexOf:function(e){return a?i.apply(this,arguments)||0:o(this,e,arguments[1])}})},function(e,t,n){var r=n(0);r(r.S,"Array",{isArray:n(120)})},function(e,t,n){"use strict";var r=n(0),o=n(22),i=[].join;r(r.P+r.F*(n(73)!=Object||!n(27)(i)),"Array",{join:function(e){return i.call(o(this),void 0===e?",":e)}})},function(e,t,n){"use strict";var r=n(0),o=n(22),i=n(45),a=n(13),u=[].lastIndexOf,s=!!u&&1/[1].lastIndexOf(1,-0)<0;r(r.P+r.F*(s||!n(27)(u)),"Array",{lastIndexOf:function(e){if(s)return u.apply(this,arguments)||0;var t=o(this),n=a(t.length),r=n-1;for(arguments.length>1&&(r=Math.min(r,i(arguments[1]))),r<0&&(r=n+r);r>=0;r--)if(r in t&&t[r]===e)return r||0;return-1}})},function(e,t,n){"use strict";var r=n(0),o=n(30)(1);r(r.P+r.F*!n(27)([].map,!0),"Array",{map:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(113);r(r.S+r.F*n(5)(function(){function e(){}return!(Array.of.call(e)instanceof e)}),"Array",{of:function(){for(var e=0,t=arguments.length,n=new("function"==typeof this?this:Array)(t);t>e;)o(n,e,arguments[e++]);return n.length=t,n}})},function(e,t,n){"use strict";var r=n(0),o=n(180);r(r.P+r.F*!n(27)([].reduceRight,!0),"Array",{reduceRight:function(e){return o(this,e,arguments.length,arguments[1],!0)}})},function(e,t,n){"use strict";var r=n(0),o=n(180);r(r.P+r.F*!n(27)([].reduce,!0),"Array",{reduce:function(e){return o(this,e,arguments.length,arguments[1],!1)}})},function(e,t,n){"use strict";var r=n(0),o=n(117),i=n(25),a=n(54),u=n(13),s=[].slice;r(r.P+r.F*n(5)(function(){o&&s.call(o)}),"Array",{slice:function(e,t){var n=u(this.length),r=i(this);if(t=void 0===t?n:t,"Array"==r)return s.call(this,e,t);for(var o=a(e,n),c=a(t,n),l=u(c-o),f=Array(l),p=0;p<l;p++)f[p]="String"==r?this.charAt(o+p):this[o+p];return f}})},function(e,t,n){"use strict";var r=n(0),o=n(30)(3);r(r.P+r.F*!n(27)([].some,!0),"Array",{some:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(18),i=n(14),a=n(5),u=[].sort,s=[1,2,3];r(r.P+r.F*(a(function(){s.sort(void 0)})||!a(function(){s.sort(null)})||!n(27)(u)),"Array",{sort:function(e){return void 0===e?u.call(i(this)):u.call(i(this),o(e))}})},function(e,t,n){n(53)("Array")},function(e,t,n){var r=n(0);r(r.S,"Date",{now:function(){return(new Date).getTime()}})},function(e,t,n){"use strict";var r=n(0),o=n(5),i=Date.prototype.getTime,a=function(e){return e>9?e:"0"+e};r(r.P+r.F*(o(function(){return"0385-07-25T07:06:39.999Z"!=new Date(-5e13-1).toISOString()})||!o(function(){new Date(NaN).toISOString()})),"Date",{toISOString:function(){if(!isFinite(i.call(this)))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),n=e.getUTCMilliseconds(),r=t<0?"-":t>9999?"+":"";return r+("00000"+Math.abs(t)).slice(r?-6:-4)+"-"+a(e.getUTCMonth()+1)+"-"+a(e.getUTCDate())+"T"+a(e.getUTCHours())+":"+a(e.getUTCMinutes())+":"+a(e.getUTCSeconds())+"."+(n>99?n:"0"+a(n))+"Z"}})},function(e,t,n){"use strict";var r=n(0),o=n(14),i=n(32);r(r.P+r.F*n(5)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}),"Date",{toJSON:function(e){var t=o(this),n=i(t);return"number"!=typeof n||isFinite(n)?t.toISOString():null}})},function(e,t,n){var r=n(8)("toPrimitive"),o=Date.prototype;r in o||n(19)(o,r,n(277))},function(e,t,n){var r=Date.prototype,o=r.toString,i=r.getTime;new Date(NaN)+""!="Invalid Date"&&n(20)(r,"toString",function(){var e=i.call(this);return e===e?o.call(this):"Invalid Date"})},function(e,t,n){var r=n(0);r(r.P,"Function",{bind:n(181)})},function(e,t,n){"use strict";var r=n(7),o=n(24),i=n(8)("hasInstance"),a=Function.prototype;i in a||n(11).f(a,i,{value:function(e){if("function"!=typeof this||!r(e))return!1;if(!r(this.prototype))return e instanceof this;for(;e=o(e);)if(this.prototype===e)return!0;return!1}})},function(e,t,n){var r=n(11).f,o=n(44),i=n(16),a=Function.prototype,u=Object.isExtensible||function(){return!0};"name"in a||n(10)&&r(a,"name",{configurable:!0,get:function(){try{var e=this,t=(""+e).match(/^\s*function ([^ (]*)/)[1];return i(e,"name")||!u(e)||r(e,"name",o(5,t)),t}catch(e){return""}}})},function(e,t,n){var r=n(0),o=n(189),i=Math.sqrt,a=Math.acosh;r(r.S+r.F*!(a&&710==Math.floor(a(Number.MAX_VALUE))&&a(1/0)==1/0),"Math",{acosh:function(e){return(e=+e)<1?NaN:e>94906265.62425156?Math.log(e)+Math.LN2:o(e-1+i(e-1)*i(e+1))}})},function(e,t,n){function r(e){return isFinite(e=+e)&&0!=e?e<0?-r(-e):Math.log(e+Math.sqrt(e*e+1)):e}var o=n(0),i=Math.asinh;o(o.S+o.F*!(i&&1/i(0)>0),"Math",{asinh:r})},function(e,t,n){var r=n(0),o=Math.atanh;r(r.S+r.F*!(o&&1/o(-0)<0),"Math",{atanh:function(e){return 0==(e=+e)?e:Math.log((1+e)/(1-e))/2}})},function(e,t,n){var r=n(0),o=n(124);r(r.S,"Math",{cbrt:function(e){return o(e=+e)*Math.pow(Math.abs(e),1/3)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{clz32:function(e){return(e>>>=0)?31-Math.floor(Math.log(e+.5)*Math.LOG2E):32}})},function(e,t,n){var r=n(0),o=Math.exp;r(r.S,"Math",{cosh:function(e){return(o(e=+e)+o(-e))/2}})},function(e,t,n){var r=n(0),o=n(123);r(r.S+r.F*(o!=Math.expm1),"Math",{expm1:o})},function(e,t,n){var r=n(0),o=n(124),i=Math.pow,a=i(2,-52),u=i(2,-23),s=i(2,127)*(2-u),c=i(2,-126),l=function(e){return e+1/a-1/a};r(r.S,"Math",{fround:function(e){var t,n,r=Math.abs(e),i=o(e);return r<c?i*l(r/c/u)*c*u:(t=(1+u/a)*r,n=t-(t-r),n>s||n!=n?i*(1/0):i*n)}})},function(e,t,n){var r=n(0),o=Math.abs;r(r.S,"Math",{hypot:function(e,t){for(var n,r,i=0,a=0,u=arguments.length,s=0;a<u;)n=o(arguments[a++]),s<n?(r=s/n,i=i*r*r+1,s=n):n>0?(r=n/s,i+=r*r):i+=n;return s===1/0?1/0:s*Math.sqrt(i)}})},function(e,t,n){var r=n(0),o=Math.imul;r(r.S+r.F*n(5)(function(){return-5!=o(4294967295,5)||2!=o.length}),"Math",{imul:function(e,t){var n=+e,r=+t,o=65535&n,i=65535&r;return 0|o*i+((65535&n>>>16)*i+o*(65535&r>>>16)<<16>>>0)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{log10:function(e){return Math.log(e)/Math.LN10}})},function(e,t,n){var r=n(0);r(r.S,"Math",{log1p:n(189)})},function(e,t,n){var r=n(0);r(r.S,"Math",{log2:function(e){return Math.log(e)/Math.LN2}})},function(e,t,n){var r=n(0);r(r.S,"Math",{sign:n(124)})},function(e,t,n){var r=n(0),o=n(123),i=Math.exp;r(r.S+r.F*n(5)(function(){return-2e-17!=!Math.sinh(-2e-17)}),"Math",{sinh:function(e){return Math.abs(e=+e)<1?(o(e)-o(-e))/2:(i(e-1)-i(-e-1))*(Math.E/2)}})},function(e,t,n){var r=n(0),o=n(123),i=Math.exp;r(r.S,"Math",{tanh:function(e){var t=o(e=+e),n=o(-e);return t==1/0?1:n==1/0?-1:(t-n)/(i(e)+i(-e))}})},function(e,t,n){var r=n(0);r(r.S,"Math",{trunc:function(e){return(e>0?Math.floor:Math.ceil)(e)}})},function(e,t,n){"use strict";var r=n(3),o=n(16),i=n(25),a=n(118),u=n(32),s=n(5),c=n(50).f,l=n(23).f,f=n(11).f,p=n(63).trim,d=r.Number,h=d,v=d.prototype,m="Number"==i(n(49)(v)),y="trim"in String.prototype,g=function(e){var t=u(e,!1);if("string"==typeof t&&t.length>2){t=y?t.trim():p(t,3);var n,r,o,i=t.charCodeAt(0);if(43===i||45===i){if(88===(n=t.charCodeAt(2))||120===n)return NaN}else if(48===i){switch(t.charCodeAt(1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+t}for(var a,s=t.slice(2),c=0,l=s.length;c<l;c++)if((a=s.charCodeAt(c))<48||a>o)return NaN;return parseInt(s,r)}}return+t};if(!d(" 0o1")||!d("0b1")||d("+0x1")){d=function(e){var t=arguments.length<1?0:e,n=this;return n instanceof d&&(m?s(function(){v.valueOf.call(n)}):"Number"!=i(n))?a(new h(g(t)),n,d):g(t)};for(var b,_=n(10)?c(h):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),E=0;_.length>E;E++)o(h,b=_[E])&&!o(d,b)&&f(d,b,l(h,b));d.prototype=v,v.constructor=d,n(20)(r,"Number",d)}},function(e,t,n){var r=n(0);r(r.S,"Number",{EPSILON:Math.pow(2,-52)})},function(e,t,n){var r=n(0),o=n(3).isFinite;r(r.S,"Number",{isFinite:function(e){return"number"==typeof e&&o(e)}})},function(e,t,n){var r=n(0);r(r.S,"Number",{isInteger:n(186)})},function(e,t,n){var r=n(0);r(r.S,"Number",{isNaN:function(e){return e!=e}})},function(e,t,n){var r=n(0),o=n(186),i=Math.abs;r(r.S,"Number",{isSafeInteger:function(e){return o(e)&&i(e)<=9007199254740991}})},function(e,t,n){var r=n(0);r(r.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(e,t,n){var r=n(0);r(r.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991})},function(e,t,n){var r=n(0),o=n(196);r(r.S+r.F*(Number.parseFloat!=o),"Number",{parseFloat:o})},function(e,t,n){var r=n(0),o=n(197);r(r.S+r.F*(Number.parseInt!=o),"Number",{parseInt:o})},function(e,t,n){"use strict";var r=n(0),o=n(45),i=n(177),a=n(131),u=1..toFixed,s=Math.floor,c=[0,0,0,0,0,0],l="Number.toFixed: incorrect invocation!",f=function(e,t){for(var n=-1,r=t;++n<6;)r+=e*c[n],c[n]=r%1e7,r=s(r/1e7)},p=function(e){for(var t=6,n=0;--t>=0;)n+=c[t],c[t]=s(n/e),n=n%e*1e7},d=function(){for(var e=6,t="";--e>=0;)if(""!==t||0===e||0!==c[e]){var n=String(c[e]);t=""===t?n:t+a.call("0",7-n.length)+n}return t},h=function(e,t,n){return 0===t?n:t%2==1?h(e,t-1,n*e):h(e*e,t/2,n)},v=function(e){for(var t=0,n=e;n>=4096;)t+=12,n/=4096;for(;n>=2;)t+=1,n/=2;return t};r(r.P+r.F*(!!u&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!n(5)(function(){u.call({})})),"Number",{toFixed:function(e){var t,n,r,u,s=i(this,l),c=o(e),m="",y="0";if(c<0||c>20)throw RangeError(l);if(s!=s)return"NaN";if(s<=-1e21||s>=1e21)return String(s);if(s<0&&(m="-",s=-s),s>1e-21)if(t=v(s*h(2,69,1))-69,n=t<0?s*h(2,-t,1):s/h(2,t,1),n*=4503599627370496,(t=52-t)>0){for(f(0,n),r=c;r>=7;)f(1e7,0),r-=7;for(f(h(10,r,1),0),r=t-1;r>=23;)p(1<<23),r-=23;p(1<<r),f(1,1),p(2),y=d()}else f(0,n),f(1<<-t,0),y=d()+a.call("0",c);return c>0?(u=y.length,y=m+(u<=c?"0."+a.call("0",c-u)+y:y.slice(0,u-c)+"."+y.slice(u-c))):y=m+y,y}})},function(e,t,n){"use strict";var r=n(0),o=n(5),i=n(177),a=1..toPrecision;r(r.P+r.F*(o(function(){return"1"!==a.call(1,void 0)})||!o(function(){a.call({})})),"Number",{toPrecision:function(e){var t=i(this,"Number#toPrecision: incorrect invocation!");return void 0===e?a.call(t):a.call(t,e)}})},function(e,t,n){var r=n(0);r(r.S+r.F,"Object",{assign:n(190)})},function(e,t,n){var r=n(0);r(r.S,"Object",{create:n(49)})},function(e,t,n){var r=n(0);r(r.S+r.F*!n(10),"Object",{defineProperties:n(191)})},function(e,t,n){var r=n(0);r(r.S+r.F*!n(10),"Object",{defineProperty:n(11).f})},function(e,t,n){var r=n(7),o=n(43).onFreeze;n(31)("freeze",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(22),o=n(23).f;n(31)("getOwnPropertyDescriptor",function(){return function(e,t){return o(r(e),t)}})},function(e,t,n){n(31)("getOwnPropertyNames",function(){return n(192).f})},function(e,t,n){var r=n(14),o=n(24);n(31)("getPrototypeOf",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(7);n(31)("isExtensible",function(e){return function(t){return!!r(t)&&(!e||e(t))}})},function(e,t,n){var r=n(7);n(31)("isFrozen",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(7);n(31)("isSealed",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(0);r(r.S,"Object",{is:n(198)})},function(e,t,n){var r=n(14),o=n(51);n(31)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(7),o=n(43).onFreeze;n(31)("preventExtensions",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(7),o=n(43).onFreeze;n(31)("seal",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(0);r(r.S,"Object",{setPrototypeOf:n(126).set})},function(e,t,n){"use strict";var r=n(72),o={};o[n(8)("toStringTag")]="z",o+""!="[object z]"&&n(20)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(e,t,n){var r=n(0),o=n(196);r(r.G+r.F*(parseFloat!=o),{parseFloat:o})},function(e,t,n){var r=n(0),o=n(197);r(r.G+r.F*(parseInt!=o),{parseInt:o})},function(e,t,n){"use strict";var r,o,i,a=n(48),u=n(3),s=n(37),c=n(72),l=n(0),f=n(7),p=n(18),d=n(47),h=n(60),v=n(128),m=n(133).set,y=n(125)(),g=u.TypeError,b=u.process,_=u.Promise,b=u.process,E="process"==c(b),w=function(){},x=!!function(){try{var e=_.resolve(1),t=(e.constructor={})[n(8)("species")]=function(e){e(w,w)};return(E||"function"==typeof PromiseRejectionEvent)&&e.then(w)instanceof t}catch(e){}}(),C=function(e,t){return e===t||e===_&&t===i},S=function(e){var t;return!(!f(e)||"function"!=typeof(t=e.then))&&t},P=function(e){return C(_,e)?new O(e):new o(e)},O=o=function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw g("Bad Promise constructor");t=e,n=r}),this.resolve=p(t),this.reject=p(n)},T=function(e){try{e()}catch(e){return{error:e}}},k=function(e,t){if(!e._n){e._n=!0;var n=e._c;y(function(){for(var r=e._v,o=1==e._s,i=0;n.length>i;)!function(t){var n,i,a=o?t.ok:t.fail,u=t.resolve,s=t.reject,c=t.domain;try{a?(o||(2==e._h&&I(e),e._h=1),!0===a?n=r:(c&&c.enter(),n=a(r),c&&c.exit()),n===t.promise?s(g("Promise-chain cycle")):(i=S(n))?i.call(n,u,s):u(n)):s(r)}catch(e){s(e)}}(n[i++]);e._c=[],e._n=!1,t&&!e._h&&A(e)})}},A=function(e){m.call(u,function(){var t,n,r,o=e._v;if(R(e)&&(t=T(function(){E?b.emit("unhandledRejection",o,e):(n=u.onunhandledrejection)?n({promise:e,reason:o}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",o)}),e._h=E||R(e)?2:1),e._a=void 0,t)throw t.error})},R=function(e){if(1==e._h)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!R(t.promise))return!1;return!0},I=function(e){m.call(u,function(){var t;E?b.emit("rejectionHandled",e):(t=u.onrejectionhandled)&&t({promise:e,reason:e._v})})},N=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||(t._a=t._c.slice()),k(t,!0))},M=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw g("Promise can't be resolved itself");(t=S(e))?y(function(){var r={_w:n,_d:!1};try{t.call(e,s(M,r,1),s(N,r,1))}catch(e){N.call(r,e)}}):(n._v=e,n._s=1,k(n,!1))}catch(e){N.call({_w:n,_d:!1},e)}}};x||(_=function(e){d(this,_,"Promise","_h"),p(e),r.call(this);try{e(s(M,this,1),s(N,this,1))}catch(e){N.call(this,e)}},r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(52)(_.prototype,{then:function(e,t){var n=P(v(this,_));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=E?b.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&k(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),O=function(){var e=new r;this.promise=e,this.resolve=s(M,e,1),this.reject=s(N,e,1)}),l(l.G+l.W+l.F*!x,{Promise:_}),n(62)(_,"Promise"),n(53)("Promise"),i=n(36).Promise,l(l.S+l.F*!x,"Promise",{reject:function(e){var t=P(this);return(0,t.reject)(e),t.promise}}),l(l.S+l.F*(a||!x),"Promise",{resolve:function(e){if(e instanceof _&&C(e.constructor,this))return e;var t=P(this);return(0,t.resolve)(e),t.promise}}),l(l.S+l.F*!(x&&n(89)(function(e){_.all(e).catch(w)})),"Promise",{all:function(e){var t=this,n=P(t),r=n.resolve,o=n.reject,i=T(function(){var n=[],i=0,a=1;h(e,!1,function(e){var u=i++,s=!1;n.push(void 0),a++,t.resolve(e).then(function(e){s||(s=!0,n[u]=e,--a||r(n))},o)}),--a||r(n)});return i&&o(i.error),n.promise},race:function(e){var t=this,n=P(t),r=n.reject,o=T(function(){h(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return o&&r(o.error),n.promise}})},function(e,t,n){var r=n(0),o=n(18),i=n(2),a=(n(3).Reflect||{}).apply,u=Function.apply;r(r.S+r.F*!n(5)(function(){a(function(){})}),"Reflect",{apply:function(e,t,n){var r=o(e),s=i(n);return a?a(r,t,s):u.call(r,t,s)}})},function(e,t,n){var r=n(0),o=n(49),i=n(18),a=n(2),u=n(7),s=n(5),c=n(181),l=(n(3).Reflect||{}).construct,f=s(function(){function e(){}return!(l(function(){},[],e)instanceof e)}),p=!s(function(){l(function(){})});r(r.S+r.F*(f||p),"Reflect",{construct:function(e,t){i(e),a(t);var n=arguments.length<3?e:i(arguments[2]);if(p&&!f)return l(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return r.push.apply(r,t),new(c.apply(e,r))}var s=n.prototype,d=o(u(s)?s:Object.prototype),h=Function.apply.call(e,d,t);return u(h)?h:d}})},function(e,t,n){var r=n(11),o=n(0),i=n(2),a=n(32);o(o.S+o.F*n(5)(function(){Reflect.defineProperty(r.f({},1,{value:1}),1,{value:2})}),"Reflect",{defineProperty:function(e,t,n){i(e),t=a(t,!0),i(n);try{return r.f(e,t,n),!0}catch(e){return!1}}})},function(e,t,n){var r=n(0),o=n(23).f,i=n(2);r(r.S,"Reflect",{deleteProperty:function(e,t){var n=o(i(e),t);return!(n&&!n.configurable)&&delete e[t]}})},function(e,t,n){"use strict";var r=n(0),o=n(2),i=function(e){this._t=o(e),this._i=0;var t,n=this._k=[];for(t in e)n.push(t)};n(121)(i,"Object",function(){var e,t=this,n=t._k;do{if(t._i>=n.length)return{value:void 0,done:!0}}while(!((e=n[t._i++])in t._t));return{value:e,done:!1}}),r(r.S,"Reflect",{enumerate:function(e){return new i(e)}})},function(e,t,n){var r=n(23),o=n(0),i=n(2);o(o.S,"Reflect",{getOwnPropertyDescriptor:function(e,t){return r.f(i(e),t)}})},function(e,t,n){var r=n(0),o=n(24),i=n(2);r(r.S,"Reflect",{getPrototypeOf:function(e){return o(i(e))}})},function(e,t,n){function r(e,t){var n,u,l=arguments.length<3?e:arguments[2];return c(e)===l?e[t]:(n=o.f(e,t))?a(n,"value")?n.value:void 0!==n.get?n.get.call(l):void 0:s(u=i(e))?r(u,t,l):void 0}var o=n(23),i=n(24),a=n(16),u=n(0),s=n(7),c=n(2);u(u.S,"Reflect",{get:r})},function(e,t,n){var r=n(0);r(r.S,"Reflect",{has:function(e,t){return t in e}})},function(e,t,n){var r=n(0),o=n(2),i=Object.isExtensible;r(r.S,"Reflect",{isExtensible:function(e){return o(e),!i||i(e)}})},function(e,t,n){var r=n(0);r(r.S,"Reflect",{ownKeys:n(195)})},function(e,t,n){var r=n(0),o=n(2),i=Object.preventExtensions;r(r.S,"Reflect",{preventExtensions:function(e){o(e);try{return i&&i(e),!0}catch(e){return!1}}})},function(e,t,n){var r=n(0),o=n(126);o&&r(r.S,"Reflect",{setPrototypeOf:function(e,t){o.check(e,t);try{return o.set(e,t),!0}catch(e){return!1}}})},function(e,t,n){function r(e,t,n){var s,p,d=arguments.length<4?e:arguments[3],h=i.f(l(e),t);if(!h){if(f(p=a(e)))return r(p,t,n,d);h=c(0)}return u(h,"value")?!(!1===h.writable||!f(d))&&(s=i.f(d,t)||c(0),s.value=n,o.f(d,t,s),!0):void 0!==h.set&&(h.set.call(d,n),!0)}var o=n(11),i=n(23),a=n(24),u=n(16),s=n(0),c=n(44),l=n(2),f=n(7);s(s.S,"Reflect",{set:r})},function(e,t,n){var r=n(3),o=n(118),i=n(11).f,a=n(50).f,u=n(88),s=n(86),c=r.RegExp,l=c,f=c.prototype,p=/a/g,d=new c(/a/g)!==/a/g;if(n(10)&&(!d||n(5)(function(){return p[n(8)("match")]=!1,c(/a/g)!=/a/g||c(p)==p||"/a/i"!=c(/a/g,"i")}))){c=function(e,t){var n=this instanceof c,r=u(e),i=void 0===t;return!n&&r&&e.constructor===c&&i?e:o(d?new l(r&&!i?e.source:e,t):l((r=e instanceof c)?e.source:e,r&&i?s.call(e):t),n?this:f,c)};for(var h=a(l),v=0;h.length>v;)!function(e){e in c||i(c,e,{configurable:!0,get:function(){return l[e]},set:function(t){l[e]=t}})}(h[v++]);f.constructor=c,c.prototype=f,n(20)(r,"RegExp",c)}n(53)("RegExp")},function(e,t,n){n(85)("match",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=void 0==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){n(85)("replace",2,function(e,t,n){return[function(r,o){"use strict";var i=e(this),a=void 0==r?void 0:r[t];return void 0!==a?a.call(r,i,o):n.call(String(i),r,o)},n]})},function(e,t,n){n(85)("search",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=void 0==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){n(85)("split",2,function(e,t,r){"use strict";var o=n(88),i=r,a=[].push,u="length";if("c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1)[u]||2!="ab".split(/(?:ab)*/)[u]||4!=".".split(/(.?)(.?)/)[u]||".".split(/()()/)[u]>1||"".split(/.?/)[u]){var s=void 0===/()??/.exec("")[1];r=function(e,t){var n=String(this);if(void 0===e&&0===t)return[];if(!o(e))return i.call(n,e,t);var r,c,l,f,p,d=[],h=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),v=0,m=void 0===t?4294967295:t>>>0,y=new RegExp(e.source,h+"g");for(s||(r=new RegExp("^"+y.source+"$(?!\\s)",h));(c=y.exec(n))&&!((l=c.index+c[0][u])>v&&(d.push(n.slice(v,c.index)),!s&&c[u]>1&&c[0].replace(r,function(){for(p=1;p<arguments[u]-2;p++)void 0===arguments[p]&&(c[p]=void 0)}),c[u]>1&&c.index<n[u]&&a.apply(d,c.slice(1)),f=c[0][u],v=l,d[u]>=m));)y.lastIndex===c.index&&y.lastIndex++;return v===n[u]?!f&&y.test("")||d.push(""):d.push(n.slice(v)),d[u]>m?d.slice(0,m):d}}else"0".split(void 0,0)[u]&&(r=function(e,t){return void 0===e&&0===t?[]:i.call(this,e,t)});return[function(n,o){var i=e(this),a=void 0==n?void 0:n[t];return void 0!==a?a.call(n,i,o):r.call(String(i),n,o)},r]})},function(e,t,n){"use strict";n(202);var r=n(2),o=n(86),i=n(10),a=/./.toString,u=function(e){n(20)(RegExp.prototype,"toString",e,!0)};n(5)(function(){return"/a/b"!=a.call({source:"a",flags:"b"})})?u(function(){var e=r(this);return"/".concat(e.source,"/","flags"in e?e.flags:!i&&e instanceof RegExp?o.call(e):void 0)}):"toString"!=a.name&&u(function(){return a.call(this)})},function(e,t,n){"use strict";n(21)("anchor",function(e){return function(t){return e(this,"a","name",t)}})},function(e,t,n){"use strict";n(21)("big",function(e){return function(){return e(this,"big","","")}})},function(e,t,n){"use strict";n(21)("blink",function(e){return function(){return e(this,"blink","","")}})},function(e,t,n){"use strict";n(21)("bold",function(e){return function(){return e(this,"b","","")}})},function(e,t,n){"use strict";var r=n(0),o=n(129)(!1);r(r.P,"String",{codePointAt:function(e){return o(this,e)}})},function(e,t,n){"use strict";var r=n(0),o=n(13),i=n(130),a="".endsWith;r(r.P+r.F*n(116)("endsWith"),"String",{endsWith:function(e){var t=i(this,e,"endsWith"),n=arguments.length>1?arguments[1]:void 0,r=o(t.length),u=void 0===n?r:Math.min(o(n),r),s=String(e);return a?a.call(t,s,u):t.slice(u-s.length,u)===s}})},function(e,t,n){"use strict";n(21)("fixed",function(e){return function(){return e(this,"tt","","")}})},function(e,t,n){"use strict";n(21)("fontcolor",function(e){return function(t){return e(this,"font","color",t)}})},function(e,t,n){"use strict";n(21)("fontsize",function(e){return function(t){return e(this,"font","size",t)}})},function(e,t,n){var r=n(0),o=n(54),i=String.fromCharCode,a=String.fromCodePoint;r(r.S+r.F*(!!a&&1!=a.length),"String",{fromCodePoint:function(e){for(var t,n=[],r=arguments.length,a=0;r>a;){if(t=+arguments[a++],o(t,1114111)!==t)throw RangeError(t+" is not a valid code point");n.push(t<65536?i(t):i(55296+((t-=65536)>>10),t%1024+56320))}return n.join("")}})},function(e,t,n){"use strict";var r=n(0),o=n(130);r(r.P+r.F*n(116)("includes"),"String",{includes:function(e){return!!~o(this,e,"includes").indexOf(e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){"use strict";n(21)("italics",function(e){return function(){return e(this,"i","","")}})},function(e,t,n){"use strict";var r=n(129)(!0);n(122)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";n(21)("link",function(e){return function(t){return e(this,"a","href",t)}})},function(e,t,n){var r=n(0),o=n(22),i=n(13);r(r.S,"String",{raw:function(e){for(var t=o(e.raw),n=i(t.length),r=arguments.length,a=[],u=0;n>u;)a.push(String(t[u++])),u<r&&a.push(String(arguments[u]));return a.join("")}})},function(e,t,n){var r=n(0);r(r.P,"String",{repeat:n(131)})},function(e,t,n){"use strict";n(21)("small",function(e){return function(){return e(this,"small","","")}})},function(e,t,n){"use strict";var r=n(0),o=n(13),i=n(130),a="".startsWith;r(r.P+r.F*n(116)("startsWith"),"String",{startsWith:function(e){var t=i(this,e,"startsWith"),n=o(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return a?a.call(t,r,n):t.slice(n,n+r.length)===r}})},function(e,t,n){"use strict";n(21)("strike",function(e){return function(){return e(this,"strike","","")}})},function(e,t,n){"use strict";n(21)("sub",function(e){return function(){return e(this,"sub","","")}})},function(e,t,n){"use strict";n(21)("sup",function(e){return function(){return e(this,"sup","","")}})},function(e,t,n){"use strict";n(63)("trim",function(e){return function(){return e(this,3)}})},function(e,t,n){"use strict";var r=n(3),o=n(16),i=n(10),a=n(0),u=n(20),s=n(43).KEY,c=n(5),l=n(92),f=n(62),p=n(55),d=n(8),h=n(200),v=n(135),m=n(279),y=n(278),g=n(120),b=n(2),_=n(22),E=n(32),w=n(44),x=n(49),C=n(192),S=n(23),P=n(11),O=n(51),T=S.f,k=P.f,A=C.f,R=r.Symbol,I=r.JSON,N=I&&I.stringify,M=d("_hidden"),j=d("toPrimitive"),F={}.propertyIsEnumerable,D=l("symbol-registry"),U=l("symbols"),L=l("op-symbols"),V=Object.prototype,B="function"==typeof R,W=r.QObject,q=!W||!W.prototype||!W.prototype.findChild,H=i&&c(function(){return 7!=x(k({},"a",{get:function(){return k(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=T(V,t);r&&delete V[t],k(e,t,n),r&&e!==V&&k(V,t,r)}:k,z=function(e){var t=U[e]=x(R.prototype);return t._k=e,t},Y=B&&"symbol"==typeof R.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof R},K=function(e,t,n){return e===V&&K(L,t,n),b(e),t=E(t,!0),b(n),o(U,t)?(n.enumerable?(o(e,M)&&e[M][t]&&(e[M][t]=!1),n=x(n,{enumerable:w(0,!1)})):(o(e,M)||k(e,M,w(1,{})),e[M][t]=!0),H(e,t,n)):k(e,t,n)},G=function(e,t){b(e);for(var n,r=y(t=_(t)),o=0,i=r.length;i>o;)K(e,n=r[o++],t[n]);return e},$=function(e,t){return void 0===t?x(e):G(x(e),t)},X=function(e){var t=F.call(this,e=E(e,!0));return!(this===V&&o(U,e)&&!o(L,e))&&(!(t||!o(this,e)||!o(U,e)||o(this,M)&&this[M][e])||t)},Q=function(e,t){if(e=_(e),t=E(t,!0),e!==V||!o(U,t)||o(L,t)){var n=T(e,t);return!n||!o(U,t)||o(e,M)&&e[M][t]||(n.enumerable=!0),n}},J=function(e){for(var t,n=A(_(e)),r=[],i=0;n.length>i;)o(U,t=n[i++])||t==M||t==s||r.push(t);return r},Z=function(e){for(var t,n=e===V,r=A(n?L:_(e)),i=[],a=0;r.length>a;)!o(U,t=r[a++])||n&&!o(V,t)||i.push(U[t]);return i};B||(R=function(){if(this instanceof R)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function(n){this===V&&t.call(L,n),o(this,M)&&o(this[M],e)&&(this[M][e]=!1),H(this,e,w(1,n))};return i&&q&&H(V,e,{configurable:!0,set:t}),z(e)},u(R.prototype,"toString",function(){return this._k}),S.f=Q,P.f=K,n(50).f=C.f=J,n(74).f=X,n(91).f=Z,i&&!n(48)&&u(V,"propertyIsEnumerable",X,!0),h.f=function(e){return z(d(e))}),a(a.G+a.W+a.F*!B,{Symbol:R});for(var ee="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),te=0;ee.length>te;)d(ee[te++]);for(var ee=O(d.store),te=0;ee.length>te;)v(ee[te++]);a(a.S+a.F*!B,"Symbol",{for:function(e){return o(D,e+="")?D[e]:D[e]=R(e)},keyFor:function(e){if(Y(e))return m(D,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){q=!0},useSimple:function(){q=!1}}),a(a.S+a.F*!B,"Object",{create:$,defineProperty:K,defineProperties:G,getOwnPropertyDescriptor:Q,getOwnPropertyNames:J,getOwnPropertySymbols:Z}),I&&a(a.S+a.F*(!B||c(function(){var e=R();return"[null]"!=N([e])||"{}"!=N({a:e})||"{}"!=N(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!Y(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!Y(t))return t}),r[1]=t,N.apply(I,r)}}}),R.prototype[j]||n(19)(R.prototype,j,R.prototype.valueOf),f(R,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0)},function(e,t,n){"use strict";var r=n(0),o=n(93),i=n(134),a=n(2),u=n(54),s=n(13),c=n(7),l=n(3).ArrayBuffer,f=n(128),p=i.ArrayBuffer,d=i.DataView,h=o.ABV&&l.isView,v=p.prototype.slice,m=o.VIEW;r(r.G+r.W+r.F*(l!==p),{ArrayBuffer:p}),r(r.S+r.F*!o.CONSTR,"ArrayBuffer",{isView:function(e){return h&&h(e)||c(e)&&m in e}}),r(r.P+r.U+r.F*n(5)(function(){return!new p(2).slice(1,void 0).byteLength}),"ArrayBuffer",{slice:function(e,t){if(void 0!==v&&void 0===t)return v.call(a(this),e);for(var n=a(this).byteLength,r=u(e,n),o=u(void 0===t?n:t,n),i=new(f(this,p))(s(o-r)),c=new d(this),l=new d(i),h=0;r<o;)l.setUint8(h++,c.getUint8(r++));return i}}),n(53)("ArrayBuffer")},function(e,t,n){var r=n(0);r(r.G+r.W+r.F*!n(93).ABV,{DataView:n(134).DataView})},function(e,t,n){n(39)("Float32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Float64",8,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Int16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Int32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Int8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Uint16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Uint32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(39)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}},!0)},function(e,t,n){"use strict";var r=n(184);n(84)("WeakSet",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e,!0)}},r,!1,!0)},function(e,t,n){"use strict";var r=n(0),o=n(83)(!0);r(r.P,"Array",{includes:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(59)("includes")},function(e,t,n){var r=n(0),o=n(125)(),i=n(3).process,a="process"==n(25)(i);r(r.G,{asap:function(e){var t=a&&i.domain;o(t?t.bind(e):e)}})},function(e,t,n){var r=n(0),o=n(25);r(r.S,"Error",{isError:function(e){return"Error"===o(e)}})},function(e,t,n){var r=n(0);r(r.P+r.R,"Map",{toJSON:n(183)("Map")})},function(e,t,n){var r=n(0);r(r.S,"Math",{iaddh:function(e,t,n,r){var o=e>>>0,i=t>>>0,a=n>>>0;return i+(r>>>0)+((o&a|(o|a)&~(o+a>>>0))>>>31)|0}})},function(e,t,n){var r=n(0);r(r.S,"Math",{imulh:function(e,t){var n=+e,r=+t,o=65535&n,i=65535&r,a=n>>16,u=r>>16,s=(a*i>>>0)+(o*i>>>16);return a*u+(s>>16)+((o*u>>>0)+(65535&s)>>16)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{isubh:function(e,t,n,r){var o=e>>>0,i=t>>>0,a=n>>>0;return i-(r>>>0)-((~o&a|~(o^a)&o-a>>>0)>>>31)|0}})},function(e,t,n){var r=n(0);r(r.S,"Math",{umulh:function(e,t){var n=+e,r=+t,o=65535&n,i=65535&r,a=n>>>16,u=r>>>16,s=(a*i>>>0)+(o*i>>>16);return a*u+(s>>>16)+((o*u>>>0)+(65535&s)>>>16)}})},function(e,t,n){"use strict";var r=n(0),o=n(14),i=n(18),a=n(11);n(10)&&r(r.P+n(90),"Object",{__defineGetter__:function(e,t){a.f(o(this),e,{get:i(t),enumerable:!0,configurable:!0})}})},function(e,t,n){"use strict";var r=n(0),o=n(14),i=n(18),a=n(11);n(10)&&r(r.P+n(90),"Object",{__defineSetter__:function(e,t){a.f(o(this),e,{set:i(t),enumerable:!0,configurable:!0})}})},function(e,t,n){var r=n(0),o=n(194)(!0);r(r.S,"Object",{entries:function(e){return o(e)}})},function(e,t,n){var r=n(0),o=n(195),i=n(22),a=n(23),u=n(113);r(r.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,n=i(e),r=a.f,s=o(n),c={},l=0;s.length>l;)u(c,t=s[l++],r(n,t));return c}})},function(e,t,n){"use strict";var r=n(0),o=n(14),i=n(32),a=n(24),u=n(23).f;n(10)&&r(r.P+n(90),"Object",{__lookupGetter__:function(e){var t,n=o(this),r=i(e,!0);do{if(t=u(n,r))return t.get}while(n=a(n))}})},function(e,t,n){"use strict";var r=n(0),o=n(14),i=n(32),a=n(24),u=n(23).f;n(10)&&r(r.P+n(90),"Object",{__lookupSetter__:function(e){var t,n=o(this),r=i(e,!0);do{if(t=u(n,r))return t.set}while(n=a(n))}})},function(e,t,n){var r=n(0),o=n(194)(!1);r(r.S,"Object",{values:function(e){return o(e)}})},function(e,t,n){"use strict";var r=n(0),o=n(3),i=n(36),a=n(125)(),u=n(8)("observable"),s=n(18),c=n(2),l=n(47),f=n(52),p=n(19),d=n(60),h=d.RETURN,v=function(e){return null==e?void 0:s(e)},m=function(e){var t=e._c;t&&(e._c=void 0,t())},y=function(e){return void 0===e._o},g=function(e){y(e)||(e._o=void 0,m(e))},b=function(e,t){c(e),this._c=void 0,this._o=e,e=new _(this);try{var n=t(e),r=n;null!=n&&("function"==typeof n.unsubscribe?n=function(){r.unsubscribe()}:s(n),this._c=n)}catch(t){return void e.error(t)}y(this)&&m(this)};b.prototype=f({},{unsubscribe:function(){g(this)}});var _=function(e){this._s=e};_.prototype=f({},{next:function(e){var t=this._s;if(!y(t)){var n=t._o;try{var r=v(n.next);if(r)return r.call(n,e)}catch(e){try{g(t)}finally{throw e}}}},error:function(e){var t=this._s;if(y(t))throw e;var n=t._o;t._o=void 0;try{var r=v(n.error);if(!r)throw e;e=r.call(n,e)}catch(e){try{m(t)}finally{throw e}}return m(t),e},complete:function(e){var t=this._s;if(!y(t)){var n=t._o;t._o=void 0;try{var r=v(n.complete);e=r?r.call(n,e):void 0}catch(e){try{m(t)}finally{throw e}}return m(t),e}}});var E=function(e){l(this,E,"Observable","_f")._f=s(e)};f(E.prototype,{subscribe:function(e){return new b(e,this._f)},forEach:function(e){var t=this;return new(i.Promise||o.Promise)(function(n,r){s(e);var o=t.subscribe({next:function(t){try{return e(t)}catch(e){r(e),o.unsubscribe()}},error:r,complete:n})})}}),f(E,{from:function(e){var t="function"==typeof this?this:E,n=v(c(e)[u]);if(n){var r=c(n.call(e));return r.constructor===t?r:new t(function(e){return r.subscribe(e)})}return new t(function(t){var n=!1;return a(function(){if(!n){try{if(d(e,!1,function(e){if(t.next(e),n)return h})===h)return}catch(e){if(n)throw e;return void t.error(e)}t.complete()}}),function(){n=!0}})},of:function(){for(var e=0,t=arguments.length,n=Array(t);e<t;)n[e]=arguments[e++];return new("function"==typeof this?this:E)(function(e){var t=!1;return a(function(){if(!t){for(var r=0;r<n.length;++r)if(e.next(n[r]),t)return;e.complete()}}),function(){t=!0}})}}),p(E.prototype,u,function(){return this}),r(r.G,{Observable:E}),n(53)("Observable")},function(e,t,n){var r=n(38),o=n(2),i=r.key,a=r.set;r.exp({defineMetadata:function(e,t,n,r){a(e,t,o(n),i(r))}})},function(e,t,n){var r=n(38),o=n(2),i=r.key,a=r.map,u=r.store;r.exp({deleteMetadata:function(e,t){var n=arguments.length<3?void 0:i(arguments[2]),r=a(o(t),n,!1);if(void 0===r||!r.delete(e))return!1;if(r.size)return!0;var s=u.get(t);return s.delete(n),!!s.size||u.delete(t)}})},function(e,t,n){var r=n(203),o=n(179),i=n(38),a=n(2),u=n(24),s=i.keys,c=i.key,l=function(e,t){var n=s(e,t),i=u(e);if(null===i)return n;var a=l(i,t);return a.length?n.length?o(new r(n.concat(a))):a:n};i.exp({getMetadataKeys:function(e){return l(a(e),arguments.length<2?void 0:c(arguments[1]))}})},function(e,t,n){var r=n(38),o=n(2),i=n(24),a=r.has,u=r.get,s=r.key,c=function(e,t,n){if(a(e,t,n))return u(e,t,n);var r=i(t);return null!==r?c(e,r,n):void 0};r.exp({getMetadata:function(e,t){return c(e,o(t),arguments.length<3?void 0:s(arguments[2]))}})},function(e,t,n){var r=n(38),o=n(2),i=r.keys,a=r.key;r.exp({getOwnMetadataKeys:function(e){return i(o(e),arguments.length<2?void 0:a(arguments[1]))}})},function(e,t,n){var r=n(38),o=n(2),i=r.get,a=r.key;r.exp({getOwnMetadata:function(e,t){return i(e,o(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(38),o=n(2),i=n(24),a=r.has,u=r.key,s=function(e,t,n){if(a(e,t,n))return!0;var r=i(t);return null!==r&&s(e,r,n)};r.exp({hasMetadata:function(e,t){return s(e,o(t),arguments.length<3?void 0:u(arguments[2]))}})},function(e,t,n){var r=n(38),o=n(2),i=r.has,a=r.key;r.exp({hasOwnMetadata:function(e,t){return i(e,o(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(38),o=n(2),i=n(18),a=r.key,u=r.set;r.exp({metadata:function(e,t){return function(n,r){u(e,t,(void 0!==r?o:i)(n),a(r))}}})},function(e,t,n){var r=n(0);r(r.P+r.R,"Set",{toJSON:n(183)("Set")})},function(e,t,n){"use strict";var r=n(0),o=n(129)(!0);r(r.P,"String",{at:function(e){return o(this,e)}})},function(e,t,n){"use strict";var r=n(0),o=n(26),i=n(13),a=n(88),u=n(86),s=RegExp.prototype,c=function(e,t){this._r=e,this._s=t};n(121)(c,"RegExp String",function(){var e=this._r.exec(this._s);return{value:e,done:null===e}}),r(r.P,"String",{matchAll:function(e){if(o(this),!a(e))throw TypeError(e+" is not a regexp!");var t=String(this),n="flags"in s?String(e.flags):u.call(e),r=new RegExp(e.source,~n.indexOf("g")?n:"g"+n);return r.lastIndex=i(e.lastIndex),new c(r,t)}})},function(e,t,n){"use strict";var r=n(0),o=n(199);r(r.P,"String",{padEnd:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0,!1)}})},function(e,t,n){"use strict";var r=n(0),o=n(199);r(r.P,"String",{padStart:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0,!0)}})},function(e,t,n){"use strict";n(63)("trimLeft",function(e){return function(){return e(this,1)}},"trimStart")},function(e,t,n){"use strict";n(63)("trimRight",function(e){return function(){return e(this,2)}},"trimEnd")},function(e,t,n){n(135)("asyncIterator")},function(e,t,n){n(135)("observable")},function(e,t,n){var r=n(0);r(r.S,"System",{global:n(3)})},function(e,t,n){for(var r=n(137),o=n(20),i=n(3),a=n(19),u=n(61),s=n(8),c=s("iterator"),l=s("toStringTag"),f=u.Array,p=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],d=0;d<5;d++){var h,v=p[d],m=i[v],y=m&&m.prototype;if(y){y[c]||a(y,c,f),y[l]||a(y,l,v),u[v]=f;for(h in r)y[h]||o(y,h,r[h],!0)}}},function(e,t,n){var r=n(0),o=n(133);r(r.G+r.B,{setImmediate:o.set,clearImmediate:o.clear})},function(e,t,n){var r=n(3),o=n(0),i=n(87),a=n(280),u=r.navigator,s=!!u&&/MSIE .\./.test(u.userAgent),c=function(e){return s?function(t,n){return e(i(a,[].slice.call(arguments,2),"function"==typeof t?t:Function(t)),n)}:e};o(o.G+o.B+o.F*s,{setTimeout:c(r.setTimeout),setInterval:c(r.setInterval)})},function(e,t,n){n(403),n(342),n(344),n(343),n(346),n(348),n(353),n(347),n(345),n(355),n(354),n(350),n(351),n(349),n(341),n(352),n(356),n(357),n(309),n(311),n(310),n(359),n(358),n(329),n(339),n(340),n(330),n(331),n(332),n(333),n(334),n(335),n(336),n(337),n(338),n(312),n(313),n(314),n(315),n(316),n(317),n(318),n(319),n(320),n(321),n(322),n(323),n(324),n(325),n(326),n(327),n(328),n(390),n(395),n(402),n(393),n(385),n(386),n(391),n(396),n(398),n(381),n(382),n(383),n(384),n(387),n(388),n(389),n(392),n(394),n(397),n(399),n(400),n(401),n(304),n(306),n(305),n(308),n(307),n(293),n(291),n(297),n(294),n(300),n(302),n(290),n(296),n(287),n(301),n(285),n(299),n(298),n(292),n(295),n(284),n(286),n(289),n(288),n(303),n(137),n(375),n(380),n(202),n(376),n(377),n(378),n(379),n(360),n(201),n(203),n(204),n(415),n(404),n(405),n(410),n(413),n(414),n(408),n(411),n(409),n(412),n(406),n(407),n(361),n(362),n(363),n(364),n(365),n(368),n(366),n(367),n(369),n(370),n(371),n(372),n(374),n(373),n(416),n(442),n(445),n(444),n(446),n(447),n(443),n(448),n(449),n(427),n(430),n(426),n(424),n(425),n(428),n(429),n(419),n(441),n(450),n(418),n(420),n(422),n(421),n(423),n(432),n(433),n(435),n(434),n(437),n(436),n(438),n(439),n(440),n(417),n(431),n(453),n(452),n(451),e.exports=n(36)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";r(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object.defineProperty(n,"message",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(n,"name",{configurable:!0,enumerable:!1,value:n.constructor.name,writable:!0}),Error.hasOwnProperty("captureStackTrace")?(Error.captureStackTrace(n,n.constructor),o(n)):(Object.defineProperty(n,"stack",{configurable:!0,enumerable:!1,value:new Error(e).stack,writable:!0}),n)}return i(t,e),t}(function(e){function t(){e.apply(this,arguments)}return t.prototype=Object.create(e.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e,t}(Error));t.default=a,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(456),i=/^-ms-/;e.exports=r},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!o(e)&&(o(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var o=n(466);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.length;if((Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e)&&a(!1),"number"!=typeof t&&a(!1),0===t||t-1 in e||a(!1),"function"==typeof e.callee&&a(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=n(1);e.exports=i},function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function o(e,t){var n=c;c||s(!1);var o=r(e),i=o&&u(o);if(i){n.innerHTML=i[1]+e+i[2];for(var l=i[0];l--;)n=n.lastChild}else n.innerHTML=e;var f=n.getElementsByTagName("script");f.length&&(t||s(!1),a(f).forEach(t));for(var p=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return p}var i=n(17),a=n(459),u=n(461),s=n(1),c=i.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return a||i(!1),p.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||(a.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",u[e]=!a.firstChild),u[e]?p[e]:null}var o=n(17),i=n(1),a=o.canUseDOM?document.createElement("div"):null,u={},s=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],f=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l};["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"].forEach(function(e){p[e]=f,u[e]=!0}),e.exports=r},function(e,t,n){"use strict";function r(e){return e.Window&&e instanceof e.Window?{x:e.pageXOffset||e.document.documentElement.scrollLeft,y:e.pageYOffset||e.document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=r},function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(463),i=/^ms-/;e.exports=r},function(e,t,n){"use strict";function r(e){var t=e?e.ownerDocument||e:document,n=t.defaultView||window;return!(!e||!("function"==typeof n.Node?e instanceof n.Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(465);e.exports=r},function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=r},function(e,t){e.exports='<h1 id="synchronous-validation-example">Synchronous Validation Example</h1>\n<p>There are two ways to provide synchronous client-side validation to your form.</p>\n<p>The first is to provide redux-form with a\nvalidation function that takes an object of form values and returns an object of errors.\nThis is done by providing the validation function to the decorator as a config parameter, or\nto the decorated form component as a prop.</p>\n<p>The second is to use individual validators for each field. See\n<a href="http://redux-form.com/6.6.2/examples/fieldLevelValidation/">Field-Level Validation Example</a>.</p>\n<p>Additionally, you can provide redux-form with a warn function with the same type signature as\nyour validation function. Warnings are errors that do not mark a form as invalid, allowing for\ntwo tiers of severity for errors.</p>\n<p>The example validation function is purely for simplistic demonstration value. In your \napplication, you will want to build some type of reusable system of validators.</p>\n<p>Notice the reused stateless function component used to render each field. It is important that \nthis not be defined inline (in the <code>render()</code> function), because it will be created anew on every\nrender and trigger a rerender for the field, because the <code>component</code> prop will have changed.</p>\n<p><strong>IMPORTANT</strong>: Synchronous validation happens on every change to your form data, so, if your field \nvalue is invalid, your field.error value will always be present. You will probably only want to\nshow validation errors once your field has been touched, a flag that is set for you by <code>redux-form</code>\nwhen the onBlur event occurs on your field. When you submit the form, all the fields are marked as\ntouched, allowing any of their validation errors to show.</p>\n<h2 id="running-this-example-locally">Running this example locally</h2>\n<p>To run this example locally on your machine clone the <code>redux-form</code> repository,\nthen <code>cd redux-form</code> to change to the repo directory, and run <code>npm install</code>.</p>\n<p>Then run <code>npm run example:syncValidation</code> or manually run the\nfollowing commands:</p>\n<pre><code>cd ./examples/syncValidation\nnpm install\nnpm start\n</code></pre>'},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n.i(r.a)(o.a,"DataView");t.a=i},function(e,t,n){"use strict";function r(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(520),i=n(521),a=n(522),u=n(523),s=n(524);r.prototype.clear=o.a,r.prototype.delete=i.a,r.prototype.get=a.a,r.prototype.has=u.a,r.prototype.set=s.a,t.a=r},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n.i(r.a)(o.a,"Promise");t.a=i},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n.i(r.a)(o.a,"Set");t.a=i},function(e,t,n){"use strict";function r(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new o.a;++t<n;)this.add(e[t])}var o=n(141),i=n(546),a=n(547);r.prototype.add=r.prototype.push=i.a,r.prototype.has=a.a,t.a=r},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n.i(r.a)(o.a,"WeakMap");t.a=i},function(e,t,n){"use strict";function r(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}t.a=r},function(e,t,n){"use strict";function r(e,t){for(var n=-1,r=null==e?0:e.length,o=0,i=[];++n<r;){var a=e[n];t(a,n,e)&&(i[o++]=a)}return i}t.a=r},function(e,t,n){"use strict";function r(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}t.a=r},function(e,t,n){"use strict";function r(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}t.a=r},function(e,t,n){"use strict";function r(e,t,r){var a=e[t];u.call(e,t)&&n.i(i.a)(a,r)&&(void 0!==r||t in e)||n.i(o.a)(e,t,r)}var o=n(97),i=n(78),a=Object.prototype,u=a.hasOwnProperty;t.a=r},function(e,t,n){"use strict";var r=n(46),o=Object.create,i=function(){function e(){}return function(t){if(!n.i(r.a)(t))return{};if(o)return o(t);e.prototype=t;var i=new e;return e.prototype=void 0,i}}();t.a=i},function(e,t,n){"use strict";function r(e,t){return e&&n.i(o.a)(e,t,i.a)}var o=n(213),i=n(153);t.a=r},function(e,t,n){"use strict";function r(e,t,r){var a=t(e);return n.i(i.a)(e)?a:n.i(o.a)(a,r(e))}var o=n(477),i=n(34);t.a=r},function(e,t,n){"use strict";function r(e,t){return null!=e&&t in Object(e)}t.a=r},function(e,t,n){"use strict";function r(e){return n.i(i.a)(e)&&n.i(o.a)(e)==a}var o=n(64),i=n(57),a="[object Arguments]";t.a=r},function(e,t,n){"use strict";function r(e,t,r,m,g,b){var _=n.i(c.a)(e),E=n.i(c.a)(t),w=_?h:n.i(s.a)(e),x=E?h:n.i(s.a)(t);w=w==d?v:w,x=x==d?v:x;var C=w==v,S=x==v,P=w==x;if(P&&n.i(l.a)(e)){if(!n.i(l.a)(t))return!1;_=!0,C=!1}if(P&&!C)return b||(b=new o.a),_||n.i(f.a)(e)?n.i(i.a)(e,t,r,m,g,b):n.i(a.a)(e,t,w,r,m,g,b);if(!(r&p)){var O=C&&y.call(e,"__wrapped__"),T=S&&y.call(t,"__wrapped__");if(O||T){var k=O?e.value():e,A=T?t.value():t;return b||(b=new o.a),g(k,A,r,m,b)}}return!!P&&(b||(b=new o.a),n.i(u.a)(e,t,r,m,g,b))}var o=n(142),i=n(218),a=n(511),u=n(512),s=n(517),c=n(34),l=n(149),f=n(152),p=1,d="[object Arguments]",h="[object Array]",v="[object Object]",m=Object.prototype,y=m.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e,t,r,s){var c=r.length,l=c,f=!s;if(null==e)return!l;for(e=Object(e);c--;){var p=r[c];if(f&&p[2]?p[1]!==e[p[0]]:!(p[0]in e))return!1}for(;++c<l;){p=r[c];var d=p[0],h=e[d],v=p[1];if(f&&p[2]){if(void 0===h&&!(d in e))return!1}else{var m=new o.a;if(s)var y=s(h,v,d,e,t,m);if(!(void 0===y?n.i(i.a)(v,h,a|u,s,m):y))return!1}}return!0}var o=n(142),i=n(143),a=1,u=2;t.a=r},function(e,t,n){"use strict";function r(e){return!(!n.i(a.a)(e)||n.i(i.a)(e))&&(n.i(o.a)(e)?d:s).test(n.i(u.a)(e))}var o=n(150),i=n(528),a=n(46),u=n(225),s=/^\[object .+?Constructor\]$/,c=Function.prototype,l=Object.prototype,f=c.toString,p=l.hasOwnProperty,d=RegExp("^"+f.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.a=r},function(e,t,n){"use strict";function r(e){return n.i(a.a)(e)&&n.i(i.a)(e.length)&&!!u[n.i(o.a)(e)]}var o=n(64),i=n(151),a=n(57),u={};u["[object Float32Array]"]=u["[object Float64Array]"]=u["[object Int8Array]"]=u["[object Int16Array]"]=u["[object Int32Array]"]=u["[object Uint8Array]"]=u["[object Uint8ClampedArray]"]=u["[object Uint16Array]"]=u["[object Uint32Array]"]=!0,u["[object Arguments]"]=u["[object Array]"]=u["[object ArrayBuffer]"]=u["[object Boolean]"]=u["[object DataView]"]=u["[object Date]"]=u["[object Error]"]=u["[object Function]"]=u["[object Map]"]=u["[object Number]"]=u["[object Object]"]=u["[object RegExp]"]=u["[object Set]"]=u["[object String]"]=u["[object WeakMap]"]=!1,t.a=r},function(e,t,n){"use strict";function r(e){return"function"==typeof e?e:null==e?a.a:"object"==typeof e?n.i(u.a)(e)?n.i(i.a)(e[0],e[1]):n.i(o.a)(e):n.i(s.a)(e)}var o=n(492),i=n(493),a=n(147),u=n(34),s=n(562);t.a=r},function(e,t,n){"use strict";function r(e){if(!n.i(o.a)(e))return n.i(i.a)(e);var t=[];for(var r in Object(e))u.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=n(146),i=n(541),a=Object.prototype,u=a.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e){if(!n.i(o.a)(e))return n.i(a.a)(e);var t=n.i(i.a)(e),r=[];for(var u in e)("constructor"!=u||!t&&s.call(e,u))&&r.push(u);return r}var o=n(46),i=n(146),a=n(542),u=Object.prototype,s=u.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e){var t=n.i(i.a)(e);return 1==t.length&&t[0][2]?n.i(a.a)(t[0][0],t[0][1]):function(r){return r===e||n.i(o.a)(r,e,t)}}var o=n(486),i=n(514),a=n(222);t.a=r},function(e,t,n){"use strict";function r(e,t){return n.i(u.a)(e)&&n.i(s.a)(t)?n.i(c.a)(n.i(l.a)(e),t):function(r){var u=n.i(i.a)(r,e);return void 0===u&&u===t?n.i(a.a)(r,e):n.i(o.a)(t,u,f|p)}}var o=n(143),i=n(557),a=n(558),u=n(145),s=n(221),c=n(222),l=n(77),f=1,p=2;t.a=r},function(e,t,n){"use strict";function r(e,t,l,f,p){e!==t&&n.i(a.a)(t,function(a,c){if(n.i(s.a)(a))p||(p=new o.a),n.i(u.a)(e,t,c,l,r,f,p);else{var d=f?f(e[c],a,c+"",e,t,p):void 0;void 0===d&&(d=a),n.i(i.a)(e,c,d)}},c.a)}var o=n(142),i=n(212),a=n(213),u=n(495),s=n(46),c=n(227);t.a=r},function(e,t,n){"use strict";function r(e,t,r,g,b,_,E){var w=e[r],x=t[r],C=E.get(x);if(C)return void n.i(o.a)(e,r,C);var S=_?_(w,x,r+"",e,t,E):void 0,P=void 0===S;if(P){var O=n.i(l.a)(x),T=!O&&n.i(p.a)(x),k=!O&&!T&&n.i(m.a)(x);S=x,O||T||k?n.i(l.a)(w)?S=w:n.i(f.a)(w)?S=n.i(u.a)(w):T?(P=!1,S=n.i(i.a)(x,!0)):k?(P=!1,S=n.i(a.a)(x,!0)):S=[]:n.i(v.a)(x)||n.i(c.a)(x)?(S=w,n.i(c.a)(w)?S=n.i(y.a)(w):(!n.i(h.a)(w)||g&&n.i(d.a)(w))&&(S=n.i(s.a)(x))):P=!1}P&&(E.set(x,S),b(S,x,g,_,E),E.delete(x)),n.i(o.a)(e,r,S)}var o=n(212),i=n(505),a=n(506),u=n(216),s=n(525),c=n(148),l=n(34),f=n(559),p=n(149),d=n(150),h=n(46),v=n(101),m=n(152),y=n(565);t.a=r},function(e,t,n){"use strict";function r(e){return function(t){return null==t?void 0:t[e]}}t.a=r},function(e,t,n){"use strict";function r(e){return function(t){return n.i(o.a)(t,e)}}var o=n(214);t.a=r},function(e,t,n){"use strict";function r(e,t){return n.i(a.a)(n.i(i.a)(e,t,o.a),e+"")}var o=n(147),i=n(545),a=n(549);t.a=r},function(e,t,n){"use strict";var r=n(556),o=n(217),i=n(147),a=o.a?function(e,t){return n.i(o.a)(e,"toString",{configurable:!0,enumerable:!1,value:n.i(r.a)(t),writable:!0})}:i.a;t.a=a},function(e,t,n){"use strict";function r(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}t.a=r},function(e,t,n){"use strict";function r(e){if("string"==typeof e)return e;if(n.i(a.a)(e))return n.i(i.a)(e,r)+"";if(n.i(u.a)(e))return l?l.call(e):"";var t=e+"";return"0"==t&&1/e==-s?"-0":t}var o=n(95),i=n(211),a=n(34),u=n(102),s=1/0,c=o.a?o.a.prototype:void 0,l=c?c.toString:void 0;t.a=r},function(e,t,n){"use strict";function r(e){return function(t){return e(t)}}t.a=r},function(e,t,n){"use strict";function r(e,t){return e.has(t)}t.a=r},function(e,t,n){"use strict";function r(e){var t=new e.constructor(e.byteLength);return new o.a(t).set(new o.a(e)),t}var o=n(209);t.a=r},function(e,t,n){"use strict";(function(e){function r(e,t){if(t)return e.slice();var n=e.length,r=c?c(n):new e.constructor(n);return e.copy(r),r}var o=n(33),i="object"==typeof exports&&exports&&!exports.nodeType&&exports,a=i&&"object"==typeof e&&e&&!e.nodeType&&e,u=a&&a.exports===i,s=u?o.a.Buffer:void 0,c=s?s.allocUnsafe:void 0;t.a=r}).call(t,n(176)(e))},function(e,t,n){"use strict";function r(e,t){var r=t?n.i(o.a)(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var o=n(504);t.a=r},function(e,t,n){"use strict";function r(e,t,r,a){var u=!r;r||(r={});for(var s=-1,c=t.length;++s<c;){var l=t[s],f=a?a(r[l],e[l],l,r,e):void 0;void 0===f&&(f=e[l]),u?n.i(i.a)(r,l,f):n.i(o.a)(r,l,f)}return r}var o=n(479),i=n(97);t.a=r},function(e,t,n){"use strict";var r=n(33),o=r.a["__core-js_shared__"];t.a=o},function(e,t,n){"use strict";function r(e){return n.i(o.a)(function(t,r){var o=-1,a=r.length,u=a>1?r[a-1]:void 0,s=a>2?r[2]:void 0;for(u=e.length>3&&"function"==typeof u?(a--,u):void 0,s&&n.i(i.a)(r[0],r[1],s)&&(u=a<3?void 0:u,a=1),t=Object(t);++o<a;){var c=r[o];c&&e(t,c,o,u)}return t})}var o=n(498),i=n(526);t.a=r},function(e,t,n){"use strict";function r(e){return function(t,n,r){for(var o=-1,i=Object(t),a=r(t),u=a.length;u--;){var s=a[e?u:++o];if(!1===n(i[s],s,i))break}return t}}t.a=r},function(e,t,n){"use strict";function r(e,t,r,o,x,S,P){switch(r){case w:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case E:return!(e.byteLength!=t.byteLength||!S(new i.a(e),new i.a(t)));case p:case d:case m:return n.i(a.a)(+e,+t);case h:return e.name==t.name&&e.message==t.message;case y:case b:return e==t+"";case v:var O=s.a;case g:var T=o&l;if(O||(O=c.a),e.size!=t.size&&!T)return!1;var k=P.get(e);if(k)return k==t;o|=f,P.set(e,t);var A=n.i(u.a)(O(e),O(t),o,x,S,P);return P.delete(e),A;case _:if(C)return C.call(e)==C.call(t)}return!1}var o=n(95),i=n(209),a=n(78),u=n(218),s=n(539),c=n(548),l=1,f=2,p="[object Boolean]",d="[object Date]",h="[object Error]",v="[object Map]",m="[object Number]",y="[object RegExp]",g="[object Set]",b="[object String]",_="[object Symbol]",E="[object ArrayBuffer]",w="[object DataView]",x=o.a?o.a.prototype:void 0,C=x?x.valueOf:void 0;t.a=r},function(e,t,n){"use strict";function r(e,t,r,a,s,c){var l=r&i,f=n.i(o.a)(e),p=f.length;if(p!=n.i(o.a)(t).length&&!l)return!1;for(var d=p;d--;){var h=f[d];if(!(l?h in t:u.call(t,h)))return!1}var v=c.get(e);if(v&&c.get(t))return v==t;var m=!0;c.set(e,t),c.set(t,e);for(var y=l;++d<p;){h=f[d];var g=e[h],b=t[h];if(a)var _=l?a(b,g,h,t,e,c):a(g,b,h,e,t,c);if(!(void 0===_?g===b||s(g,b,r,a,c):_)){m=!1;break}y||(y="constructor"==h)}if(m&&!y){var E=e.constructor,w=t.constructor;E!=w&&"constructor"in e&&"constructor"in t&&!("function"==typeof E&&E instanceof E&&"function"==typeof w&&w instanceof w)&&(m=!1)}return c.delete(e),c.delete(t),m}var o=n(513),i=1,a=Object.prototype,u=a.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e){return n.i(o.a)(e,a.a,i.a)}var o=n(482),i=n(516),a=n(153);t.a=r},function(e,t,n){"use strict";function r(e){for(var t=n.i(i.a)(e),r=t.length;r--;){var a=t[r],u=e[a];t[r]=[a,u,n.i(o.a)(u)]}return t}var o=n(221),i=n(153);t.a=r},function(e,t,n){"use strict";function r(e){var t=a.call(e,s),n=e[s];try{e[s]=void 0}catch(e){}var r=u.call(e);return t?e[s]=n:delete e[s],r}var o=n(95),i=Object.prototype,a=i.hasOwnProperty,u=i.toString,s=o.a?o.a.toStringTag:void 0;t.a=r},function(e,t,n){"use strict";var r=n(476),o=n(563),i=Object.prototype,a=i.propertyIsEnumerable,u=Object.getOwnPropertySymbols,s=u?function(e){return null==e?[]:(e=Object(e),n.i(r.a)(u(e),function(t){return a.call(e,t)}))}:o.a;t.a=s},function(e,t,n){"use strict";var r=n(469),o=n(140),i=n(471),a=n(472),u=n(474),s=n(64),c=n(225),l=n.i(c.a)(r.a),f=n.i(c.a)(o.a),p=n.i(c.a)(i.a),d=n.i(c.a)(a.a),h=n.i(c.a)(u.a),v=s.a;(r.a&&"[object DataView]"!=v(new r.a(new ArrayBuffer(1)))||o.a&&"[object Map]"!=v(new o.a)||i.a&&"[object Promise]"!=v(i.a.resolve())||a.a&&"[object Set]"!=v(new a.a)||u.a&&"[object WeakMap]"!=v(new u.a))&&(v=function(e){var t=n.i(s.a)(e),r="[object Object]"==t?e.constructor:void 0,o=r?n.i(c.a)(r):"";if(o)switch(o){case l:return"[object DataView]";case f:return"[object Map]";case p:return"[object Promise]";case d:return"[object Set]";case h:return"[object WeakMap]"}return t}),t.a=v},function(e,t,n){"use strict";function r(e,t){return null==e?void 0:e[t]}t.a=r},function(e,t,n){"use strict";function r(e,t,r){t=n.i(o.a)(t,e);for(var l=-1,f=t.length,p=!1;++l<f;){var d=n.i(c.a)(t[l]);if(!(p=null!=e&&r(e,d)))break;e=e[d]}return p||++l!=f?p:!!(f=null==e?0:e.length)&&n.i(s.a)(f)&&n.i(u.a)(d,f)&&(n.i(a.a)(e)||n.i(i.a)(e))}var o=n(215),i=n(148),a=n(34),u=n(144),s=n(151),c=n(77);t.a=r},function(e,t,n){"use strict";function r(){this.__data__=o.a?n.i(o.a)(null):{},this.size=0}var o=n(99);t.a=r},function(e,t,n){"use strict";function r(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__;if(o.a){var n=t[e];return n===i?void 0:n}return u.call(t,e)?t[e]:void 0}var o=n(99),i="__lodash_hash_undefined__",a=Object.prototype,u=a.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__;return o.a?void 0!==t[e]:a.call(t,e)}var o=n(99),i=Object.prototype,a=i.hasOwnProperty;t.a=r},function(e,t,n){"use strict";function r(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=o.a&&void 0===t?i:t,this}var o=n(99),i="__lodash_hash_undefined__";t.a=r},function(e,t,n){"use strict";function r(e){return"function"!=typeof e.constructor||n.i(a.a)(e)?{}:n.i(o.a)(n.i(i.a)(e))}var o=n(480),i=n(220),a=n(146);t.a=r},function(e,t,n){"use strict";function r(e,t,r){if(!n.i(u.a)(r))return!1;var s=typeof t;return!!("number"==s?n.i(i.a)(r)&&n.i(a.a)(t,r.length):"string"==s&&t in r)&&n.i(o.a)(r[t],e)}var o=n(78),i=n(100),a=n(144),u=n(46);t.a=r},function(e,t,n){"use strict";function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}t.a=r},function(e,t,n){"use strict";function r(e){return!!i&&i in e}var o=n(508),i=function(){var e=/[^.]+$/.exec(o.a&&o.a.keys&&o.a.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();t.a=r},function(e,t,n){"use strict";function r(){this.__data__=[],this.size=0}t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__,r=n.i(o.a)(t,e);return!(r<0)&&(r==t.length-1?t.pop():a.call(t,r,1),--this.size,!0)}var o=n(96),i=Array.prototype,a=i.splice;t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__,r=n.i(o.a)(t,e);return r<0?void 0:t[r][1]}var o=n(96);t.a=r},function(e,t,n){"use strict";function r(e){return n.i(o.a)(this.__data__,e)>-1}var o=n(96);t.a=r},function(e,t,n){"use strict";function r(e,t){var r=this.__data__,i=n.i(o.a)(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var o=n(96);t.a=r},function(e,t,n){"use strict";function r(){this.size=0,this.__data__={hash:new o.a,map:new(a.a||i.a),string:new o.a}}var o=n(470),i=n(94),a=n(140);t.a=r},function(e,t,n){"use strict";function r(e){var t=n.i(o.a)(this,e).delete(e);return this.size-=t?1:0,t}var o=n(98);t.a=r},function(e,t,n){"use strict";function r(e){return n.i(o.a)(this,e).get(e)}var o=n(98);t.a=r},function(e,t,n){"use strict";function r(e){return n.i(o.a)(this,e).has(e)}var o=n(98);t.a=r},function(e,t,n){"use strict";function r(e,t){var r=n.i(o.a)(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var o=n(98);t.a=r},function(e,t,n){"use strict";function r(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}t.a=r},function(e,t,n){"use strict";function r(e){var t=n.i(o.a)(e,function(e){return r.size===i&&r.clear(),e}),r=t.cache;return t}var o=n(560),i=500;t.a=r},function(e,t,n){"use strict";var r=n(223),o=n.i(r.a)(Object.keys,Object);t.a=o},function(e,t,n){"use strict";function r(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}t.a=r},function(e,t,n){"use strict";(function(e){var r=n(219),o="object"==typeof exports&&exports&&!exports.nodeType&&exports,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,a=i&&i.exports===o,u=a&&r.a.process,s=function(){try{return u&&u.binding&&u.binding("util")}catch(e){}}();t.a=s}).call(t,n(176)(e))},function(e,t,n){"use strict";function r(e){return i.call(e)}var o=Object.prototype,i=o.toString;t.a=r},function(e,t,n){"use strict";function r(e,t,r){return t=i(void 0===t?e.length-1:t,0),function(){for(var a=arguments,u=-1,s=i(a.length-t,0),c=Array(s);++u<s;)c[u]=a[t+u];u=-1;for(var l=Array(t+1);++u<t;)l[u]=a[u];return l[t]=r(c),n.i(o.a)(e,this,l)}}var o=n(475),i=Math.max;t.a=r},function(e,t,n){"use strict";function r(e){return this.__data__.set(e,o),this}var o="__lodash_hash_undefined__";t.a=r},function(e,t,n){"use strict";function r(e){return this.__data__.has(e)}t.a=r},function(e,t,n){"use strict";function r(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}t.a=r},function(e,t,n){"use strict";var r=n(499),o=n(550),i=n.i(o.a)(r.a);t.a=i},function(e,t,n){"use strict";function r(e){var t=0,n=0;return function(){var r=a(),u=i-(r-n);if(n=r,u>0){if(++t>=o)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var o=800,i=16,a=Date.now;t.a=r},function(e,t,n){"use strict";function r(){this.__data__=new o.a,this.size=0}var o=n(94);t.a=r},function(e,t,n){"use strict";function r(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}t.a=r},function(e,t,n){"use strict";function r(e){return this.__data__.get(e)}t.a=r},function(e,t,n){"use strict";function r(e){return this.__data__.has(e)}t.a=r},function(e,t,n){"use strict";function r(e,t){var n=this.__data__;if(n instanceof o.a){var r=n.__data__;if(!i.a||r.length<u-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new a.a(r)}return n.set(e,t),this.size=n.size,this}var o=n(94),i=n(140),a=n(141),u=200;t.a=r},function(e,t,n){"use strict";function r(e){return function(){return e}}t.a=r},function(e,t,n){"use strict";function r(e,t,r){var i=null==e?void 0:n.i(o.a)(e,t);return void 0===i?r:i}var o=n(214);t.a=r},function(e,t,n){"use strict";function r(e,t){return null!=e&&n.i(i.a)(e,t,o.a)}var o=n(483),i=n(519);t.a=r},function(e,t,n){"use strict";function r(e){return n.i(i.a)(e)&&n.i(o.a)(e)}var o=n(100),i=n(57);t.a=r},function(e,t,n){"use strict";function r(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a)||i,a};return n.cache=new(r.Cache||o.a),n}var o=n(141),i="Expected a function";r.Cache=o.a,t.a=r},function(e,t,n){"use strict";var r=n(494),o=n(509),i=n.i(o.a)(function(e,t,o){n.i(r.a)(e,t,o)});t.a=i},function(e,t,n){"use strict";function r(e){return n.i(a.a)(e)?n.i(o.a)(n.i(u.a)(e)):n.i(i.a)(e)}var o=n(496),i=n(497),a=n(145),u=n(77);t.a=r},function(e,t,n){"use strict";function r(){return[]}t.a=r},function(e,t,n){"use strict";function r(){return!1}t.a=r},function(e,t,n){"use strict";function r(e){return n.i(o.a)(e,n.i(i.a)(e))}var o=n(507),i=n(227);t.a=r},function(e,t){e.exports="import React from 'react'\nimport { Field, reduxForm } from 'redux-form'\n\nconst validate = values => {\n const errors = {}\n if (!values.username) {\n errors.username = 'Required'\n } else if (values.username.length > 15) {\n errors.username = 'Must be 15 characters or less'\n }\n if (!values.email) {\n errors.email = 'Required'\n } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i.test(values.email)) {\n errors.email = 'Invalid email address'\n }\n if (!values.age) {\n errors.age = 'Required'\n } else if (isNaN(Number(values.age))) {\n errors.age = 'Must be a number'\n } else if (Number(values.age) < 18) {\n errors.age = 'Sorry, you must be at least 18 years old'\n }\n return errors\n}\n\nconst warn = values => {\n const warnings = {}\n if (values.age < 19) {\n warnings.age = 'Hmm, you seem a bit young...'\n }\n return warnings\n}\n\nconst renderField = ({ input, label, type, meta: { touched, error, warning } }) => (\n <div>\n <label>{label}</label>\n <div>\n <input {...input} placeholder={label} type={type}/>\n {touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}\n </div>\n </div>\n)\n\nconst SyncValidationForm = (props) => {\n const { handleSubmit, pristine, reset, submitting } = props\n return (\n <form onSubmit={handleSubmit}>\n <Field name=\"username\" type=\"text\" component={renderField} label=\"Username\"/>\n <Field name=\"email\" type=\"email\" component={renderField} label=\"Email\"/>\n <Field name=\"age\" type=\"number\" component={renderField} label=\"Age\"/>\n <div>\n <button type=\"submit\" disabled={submitting}>Submit</button>\n <button type=\"button\" disabled={pristine || submitting} onClick={reset}>Clear Values</button>\n </div>\n </form>\n )\n}\n\nexport default reduxForm({\n form: 'syncValidation', // a unique identifier for this form\n validate, // <--- validation function given to redux-form\n warn // <--- warning function given to redux-form\n})(SyncValidationForm)\n"},function(e,t,n){"use strict";e.exports=n(581)},function(e,t,n){"use strict";var r={Properties:{"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},DOMAttributeNames:{},DOMPropertyNames:{}};e.exports=r},function(e,t,n){"use strict";var r=n(12),o=n(206),i={focusDOMComponent:function(){o(r.getNodeFromInstance(this))}};e.exports=i},function(e,t,n){"use strict";function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function o(e){switch(e){case"topCompositionStart":return S.compositionStart;case"topCompositionEnd":return S.compositionEnd;case"topCompositionUpdate":return S.compositionUpdate}}function i(e,t){return"topKeyDown"===e&&t.keyCode===g}function a(e,t){switch(e){case"topKeyUp":return-1!==y.indexOf(t.keyCode);case"topKeyDown":return t.keyCode!==g;case"topKeyPress":case"topMouseDown":case"topBlur":return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function s(e,t,n,r){var s,c;if(b?s=o(e):O?a(e,n)&&(s=S.compositionEnd):i(e,n)&&(s=S.compositionStart),!s)return null;w&&(O||s!==S.compositionStart?s===S.compositionEnd&&O&&(c=O.getData()):O=h.getPooled(r));var l=v.getPooled(s,t,n,r);if(c)l.data=c;else{var f=u(n);null!==f&&(l.data=f)}return p.accumulateTwoPhaseDispatches(l),l}function c(e,t){switch(e){case"topCompositionEnd":return u(t);case"topKeyPress":return t.which!==x?null:(P=!0,C);case"topTextInput":var n=t.data;return n===C&&P?null:n;default:return null}}function l(e,t){if(O){if("topCompositionEnd"===e||!b&&a(e,t)){var n=O.getData();return h.release(O),O=null,n}return null}switch(e){case"topPaste":return null;case"topKeyPress":return t.which&&!r(t)?String.fromCharCode(t.which):null;case"topCompositionEnd":return w?null:t.data;default:return null}}function f(e,t,n,r){var o;if(!(o=E?c(e,n):l(e,n)))return null;var i=m.getPooled(S.beforeInput,t,n,r);return i.data=o,p.accumulateTwoPhaseDispatches(i),i}var p=n(80),d=n(17),h=n(576),v=n(613),m=n(616),y=[9,13,27,32],g=229,b=d.canUseDOM&&"CompositionEvent"in window,_=null;d.canUseDOM&&"documentMode"in document&&(_=document.documentMode);var E=d.canUseDOM&&"TextEvent"in window&&!_&&!function(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}(),w=d.canUseDOM&&(!b||_&&_>8&&_<=11),x=32,C=String.fromCharCode(x),S={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},P=!1,O=null,T={eventTypes:S,extractEvents:function(e,t,n,r){return[s(e,t,n,r),f(e,t,n,r)]}};e.exports=T},function(e,t,n){"use strict";var r=n(230),o=n(17),i=(n(29),n(457),n(622)),a=n(464),u=n(467),s=(n(4),u(function(e){return a(e)})),c=!1,l="cssFloat";if(o.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(e){c=!0}void 0===document.documentElement.style.cssFloat&&(l="styleFloat")}var p={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=s(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var u=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=l),u)o[a]=u;else{var s=c&&r.shorthandPropertyExpansions[a];if(s)for(var f in s)o[f]="";else o[a]=""}}}};e.exports=p},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=x.getPooled(O.change,k,e,C(e));b.accumulateTwoPhaseDispatches(t),w.batchedUpdates(i,t)}function i(e){g.enqueueEvents(e),g.processEventQueue(!1)}function a(e,t){T=e,k=t,T.attachEvent("onchange",o)}function u(){T&&(T.detachEvent("onchange",o),T=null,k=null)}function s(e,t){if("topChange"===e)return t}function c(e,t,n){"topFocus"===e?(u(),a(t,n)):"topBlur"===e&&u()}function l(e,t){T=e,k=t,A=e.value,R=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(T,"value",M),T.attachEvent?T.attachEvent("onpropertychange",p):T.addEventListener("propertychange",p,!1)}function f(){T&&(delete T.value,T.detachEvent?T.detachEvent("onpropertychange",p):T.removeEventListener("propertychange",p,!1),T=null,k=null,A=null,R=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==A&&(A=t,o(e))}}function d(e,t){if("topInput"===e)return t}function h(e,t,n){"topFocus"===e?(f(),l(t,n)):"topBlur"===e&&f()}function v(e,t){if(("topSelectionChange"===e||"topKeyUp"===e||"topKeyDown"===e)&&T&&T.value!==A)return A=T.value,k}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function y(e,t){if("topClick"===e)return t}var g=n(79),b=n(80),_=n(17),E=n(12),w=n(35),x=n(40),C=n(167),S=n(168),P=n(247),O={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:["topBlur","topChange","topClick","topFocus","topInput","topKeyDown","topKeyUp","topSelectionChange"]}},T=null,k=null,A=null,R=null,I=!1;_.canUseDOM&&(I=S("change")&&(!document.documentMode||document.documentMode>8));var N=!1;_.canUseDOM&&(N=S("input")&&(!document.documentMode||document.documentMode>11));var M={get:function(){return R.get.call(this)},set:function(e){A=""+e,R.set.call(this,e)}},j={eventTypes:O,extractEvents:function(e,t,n,o){var i,a,u=t?E.getNodeFromInstance(t):window;if(r(u)?I?i=s:a=c:P(u)?N?i=d:(i=v,a=h):m(u)&&(i=y),i){var l=i(e,t);if(l){var f=x.getPooled(O.change,l,n,o);return f.type="change",b.accumulateTwoPhaseDispatches(f),f}}a&&a(e,u,t)}};e.exports=j},function(e,t,n){"use strict";var r=n(6),o=n(65),i=n(17),a=n(460),u=n(28),s=(n(1),{dangerouslyReplaceNodeWithMarkup:function(e,t){if(i.canUseDOM||r("56"),t||r("57"),"HTML"===e.nodeName&&r("58"),"string"==typeof t){var n=a(t,u)[0];e.parentNode.replaceChild(n,e)}else o.replaceChildWithTree(e,t)}});e.exports=s},function(e,t,n){"use strict";var r=["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"];e.exports=r},function(e,t,n){"use strict";var r=n(80),o=n(12),i=n(105),a={mouseEnter:{registrationName:"onMouseEnter",dependencies:["topMouseOut","topMouseOver"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["topMouseOut","topMouseOver"]}},u={eventTypes:a,extractEvents:function(e,t,n,u){if("topMouseOver"===e&&(n.relatedTarget||n.fromElement))return null;if("topMouseOut"!==e&&"topMouseOver"!==e)return null;var s;if(u.window===u)s=u;else{var c=u.ownerDocument;s=c?c.defaultView||c.parentWindow:window}var l,f;if("topMouseOut"===e){l=t;var p=n.relatedTarget||n.toElement;f=p?o.getClosestInstanceFromNode(p):null}else l=null,f=t;if(l===f)return null;var d=null==l?s:o.getNodeFromInstance(l),h=null==f?s:o.getNodeFromInstance(f),v=i.getPooled(a.mouseLeave,l,n,u);v.type="mouseleave",v.target=d,v.relatedTarget=h;var m=i.getPooled(a.mouseEnter,f,n,u);return m.type="mouseenter",m.target=h,m.relatedTarget=d,r.accumulateEnterLeaveDispatches(v,m,l,f),[v,m]}};e.exports=u},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(9),i=n(58),a=n(245);o(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(66),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_NUMERIC_VALUE,u=r.injection.HAS_POSITIVE_NUMERIC_VALUE,s=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,c={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,as:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:u,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,default:i,defer:i,dir:0,disabled:i,download:s,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,playsInline:i,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,referrerPolicy:0,rel:0,required:i,reversed:i,role:0,rows:u,rowSpan:a,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:u,sizes:0,span:u,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:a,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};e.exports=c},function(e,t,n){"use strict";(function(t){function r(e,t,n,r){var o=void 0===e[n];null!=t&&o&&(e[n]=i(t,!0))}var o=n(67),i=n(246),a=(n(159),n(169)),u=n(249);n(4);void 0!==t&&n.i({NODE_ENV:"production"});var s={instantiateChildren:function(e,t,n,o){if(null==e)return null;var i={};return u(e,r,i),i},updateChildren:function(e,t,n,r,u,s,c,l,f){if(t||e){var p,d;for(p in t)if(t.hasOwnProperty(p)){d=e&&e[p];var h=d&&d._currentElement,v=t[p];if(null!=d&&a(h,v))o.receiveComponent(d,v,u,l),t[p]=d;else{d&&(r[p]=o.getHostNode(d),o.unmountComponent(d,!1));var m=i(v,!0);t[p]=m;var y=o.mountComponent(m,u,s,c,l,f);n.push(y)}}for(p in e)!e.hasOwnProperty(p)||t&&t.hasOwnProperty(p)||(d=e[p],r[p]=o.getHostNode(d),o.unmountComponent(d,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];o.unmountComponent(r,t)}}};e.exports=s}).call(t,n(154))},function(e,t,n){"use strict";var r=n(155),o=n(586),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup};e.exports=i},function(e,t,n){"use strict";function r(e){}function o(e){return!(!e.prototype||!e.prototype.isReactComponent)}function i(e){return!(!e.prototype||!e.prototype.isPureReactComponent)}var a=n(6),u=n(9),s=n(69),c=n(161),l=n(41),f=n(162),p=n(81),d=(n(29),n(240)),h=n(67),v=n(75),m=(n(1),n(138)),y=n(169),g=(n(4),{ImpureClass:0,PureClass:1,StatelessFunctional:2});r.prototype.render=function(){var e=p.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return t};var b=1,_={construct:function(e){this._currentElement=e,this._rootNodeID=0,this._compositeType=null,this._instance=null,this._hostParent=null,this._hostContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1},mountComponent:function(e,t,n,u){this._context=u,this._mountOrder=b++,this._hostParent=t,this._hostContainerInfo=n;var c,l=this._currentElement.props,f=this._processContext(u),d=this._currentElement.type,h=e.getUpdateQueue(),m=o(d),y=this._constructComponent(m,l,f,h);m||null!=y&&null!=y.render?i(d)?this._compositeType=g.PureClass:this._compositeType=g.ImpureClass:(c=y,null===y||!1===y||s.isValidElement(y)||a("105",d.displayName||d.name||"Component"),y=new r(d),this._compositeType=g.StatelessFunctional);y.props=l,y.context=f,y.refs=v,y.updater=h,this._instance=y,p.set(y,this);var _=y.state;void 0===_&&(y.state=_=null),("object"!=typeof _||Array.isArray(_))&&a("106",this.getName()||"ReactCompositeComponent"),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var E;return E=y.unstable_handleError?this.performInitialMountWithErrorHandling(c,t,n,e,u):this.performInitialMount(c,t,n,e,u),y.componentDidMount&&e.getReactMountReady().enqueue(y.componentDidMount,y),E},_constructComponent:function(e,t,n,r){return this._constructComponentWithoutOwner(e,t,n,r)},_constructComponentWithoutOwner:function(e,t,n,r){var o=this._currentElement.type;return e?new o(t,n,r):o(t,n,r)},performInitialMountWithErrorHandling:function(e,t,n,r,o){var i,a=r.checkpoint();try{i=this.performInitialMount(e,t,n,r,o)}catch(u){r.rollback(a),this._instance.unstable_handleError(u),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),i=this.performInitialMount(e,t,n,r,o)}return i},performInitialMount:function(e,t,n,r,o){var i=this._instance,a=0;i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===e&&(e=this._renderValidatedComponent());var u=d.getType(e);this._renderedNodeType=u;var s=this._instantiateReactComponent(e,u!==d.EMPTY);this._renderedComponent=s;var c=h.mountComponent(s,r,t,n,this._processChildContext(o),a);return c},getHostNode:function(){return h.getHostNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";f.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(h.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,this._renderedComponent=null,this._instance=null),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=0,this._topLevelWrapper=null,p.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return v;var r={};for(var o in n)r[o]=e[o];return r},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t,n=this._currentElement.type,r=this._instance;if(r.getChildContext&&(t=r.getChildContext()),t){"object"!=typeof n.childContextTypes&&a("107",this.getName()||"ReactCompositeComponent");for(var o in t)o in n.childContextTypes||a("108",this.getName()||"ReactCompositeComponent",o);return u({},e,t)}return e},_checkContextTypes:function(e,t,n){},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement?h.receiveComponent(this,this._pendingElement,e,this._context):null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null},updateComponent:function(e,t,n,r,o){var i=this._instance;null==i&&a("136",this.getName()||"ReactCompositeComponent");var u,s=!1;this._context===o?u=i.context:(u=this._processContext(o),s=!0);var c=t.props,l=n.props;t!==n&&(s=!0),s&&i.componentWillReceiveProps&&i.componentWillReceiveProps(l,u);var f=this._processPendingState(l,u),p=!0;this._pendingForceUpdate||(i.shouldComponentUpdate?p=i.shouldComponentUpdate(l,f,u):this._compositeType===g.PureClass&&(p=!m(c,l)||!m(i.state,f))),this._updateBatchNumber=null,p?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,l,f,u,e,o)):(this._currentElement=n,this._context=o,i.props=l,i.state=f,i.context=u)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=u({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var s=r[a];u(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,u,s,c=this._instance,l=Boolean(c.componentDidUpdate);l&&(a=c.props,u=c.state,s=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(o,i),l&&o.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,u,s),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent(),i=0;if(y(r,o))h.receiveComponent(n,o,e,this._processChildContext(t));else{var a=h.getHostNode(n);h.unmountComponent(n,!1);var u=d.getType(o);this._renderedNodeType=u;var s=this._instantiateReactComponent(o,u!==d.EMPTY);this._renderedComponent=s;var c=h.mountComponent(s,e,this._hostParent,this._hostContainerInfo,this._processChildContext(t),i);this._replaceNodeWithMarkup(a,c,n)}},_replaceNodeWithMarkup:function(e,t,n){c.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance;return e.render()},_renderValidatedComponent:function(){var e;if(this._compositeType!==g.StatelessFunctional){l.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{l.current=null}}else e=this._renderValidatedComponentWithoutOwnerOrContext();return null===e||!1===e||s.isValidElement(e)||a("109",this.getName()||"ReactCompositeComponent"),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n&&a("110");var r=t.getPublicInstance();(n.refs===v?n.refs={}:n.refs)[e]=r},detachRef:function(e){delete this.getPublicInstance().refs[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return this._compositeType===g.StatelessFunctional?null:e},_instantiateReactComponent:null};e.exports=_},function(e,t,n){"use strict";var r=n(12),o=n(594),i=n(239),a=n(67),u=n(35),s=n(607),c=n(623),l=n(244),f=n(631);n(4);o.inject();var p={findDOMNode:c,render:i.render,unmountComponentAtNode:i.unmountComponentAtNode,version:s,unstable_batchedUpdates:u.batchedUpdates,unstable_renderSubtreeIntoContainer:f};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:r.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=l(e)),e?r.getNodeFromInstance(e):null}},Mount:i,Reconciler:a});e.exports=p},function(e,t,n){"use strict";function r(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function o(e,t){t&&(K[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&v("137",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&v("60"),"object"==typeof t.dangerouslySetInnerHTML&&B in t.dangerouslySetInnerHTML||v("61")),null!=t.style&&"object"!=typeof t.style&&v("62",r(e)))}function i(e,t,n,r){if(!(r instanceof N)){var o=e._hostContainerInfo,i=o._node&&o._node.nodeType===q,u=i?o._node:o._ownerDocument;U(t,u),r.getReactMountReady().enqueue(a,{inst:e,registrationName:t,listener:n})}}function a(){var e=this;x.putListener(e.inst,e.registrationName,e.listener)}function u(){var e=this;T.postMountWrapper(e)}function s(){var e=this;R.postMountWrapper(e)}function c(){var e=this;k.postMountWrapper(e)}function l(){var e=this;e._rootNodeID||v("63");var t=D(e);switch(t||v("64"),e._tag){case"iframe":case"object":e._wrapperState.listeners=[S.trapBubbledEvent("topLoad","load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in H)H.hasOwnProperty(n)&&e._wrapperState.listeners.push(S.trapBubbledEvent(n,H[n],t));break;case"source":e._wrapperState.listeners=[S.trapBubbledEvent("topError","error",t)];break;case"img":e._wrapperState.listeners=[S.trapBubbledEvent("topError","error",t),S.trapBubbledEvent("topLoad","load",t)];break;case"form":e._wrapperState.listeners=[S.trapBubbledEvent("topReset","reset",t),S.trapBubbledEvent("topSubmit","submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[S.trapBubbledEvent("topInvalid","invalid",t)]}}function f(){A.postUpdateWrapper(this)}function p(e){X.call($,e)||(G.test(e)||v("65",e),$[e]=!0)}function d(e,t){return e.indexOf("-")>=0||null!=t.is}function h(e){var t=e.type;p(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._hostNode=null,this._hostParent=null,this._rootNodeID=0,this._domID=0,this._hostContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var v=n(6),m=n(9),y=n(569),g=n(571),b=n(65),_=n(156),E=n(66),w=n(232),x=n(79),C=n(157),S=n(104),P=n(233),O=n(12),T=n(587),k=n(588),A=n(234),R=n(591),I=(n(29),n(600)),N=n(605),M=(n(28),n(107)),j=(n(1),n(168),n(138),n(170),n(4),P),F=x.deleteListener,D=O.getNodeFromInstance,U=S.listenTo,L=C.registrationNameModules,V={string:!0,number:!0},B="__html",W={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},q=11,H={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},z={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},Y={listing:!0,pre:!0,textarea:!0},K=m({menuitem:!0},z),G=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,$={},X={}.hasOwnProperty,Q=1;h.displayName="ReactDOMComponent",h.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=Q++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(l,this);break;case"input":T.mountWrapper(this,i,t),i=T.getHostProps(this,i),e.getReactMountReady().enqueue(l,this);break;case"option":k.mountWrapper(this,i,t),i=k.getHostProps(this,i);break;case"select":A.mountWrapper(this,i,t),i=A.getHostProps(this,i),e.getReactMountReady().enqueue(l,this);break;case"textarea":R.mountWrapper(this,i,t),i=R.getHostProps(this,i),e.getReactMountReady().enqueue(l,this)}o(this,i);var a,f;null!=t?(a=t._namespaceURI,f=t._tag):n._tag&&(a=n._namespaceURI,f=n._tag),(null==a||a===_.svg&&"foreignobject"===f)&&(a=_.html),a===_.html&&("svg"===this._tag?a=_.svg:"math"===this._tag&&(a=_.mathml)),this._namespaceURI=a;var p;if(e.useCreateElement){var d,h=n._ownerDocument;if(a===_.html)if("script"===this._tag){var v=h.createElement("div"),m=this._currentElement.type;v.innerHTML="<"+m+"></"+m+">",d=v.removeChild(v.firstChild)}else d=i.is?h.createElement(this._currentElement.type,i.is):h.createElement(this._currentElement.type);else d=h.createElementNS(a,this._currentElement.type);O.precacheNode(this,d),this._flags|=j.hasCachedChildNodes,this._hostParent||w.setAttributeForRoot(d),this._updateDOMProperties(null,i,e);var g=b(d);this._createInitialChildren(e,i,r,g),p=g}else{var E=this._createOpenTagMarkupAndPutListeners(e,i),x=this._createContentMarkup(e,i,r);p=!x&&z[this._tag]?E+"/>":E+">"+x+"</"+this._currentElement.type+">"}switch(this._tag){case"input":e.getReactMountReady().enqueue(u,this),i.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(s,this),i.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"select":case"button":i.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(c,this)}return p},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(L.hasOwnProperty(r))o&&i(this,r,o,e);else{"style"===r&&(o&&(o=this._previousStyleCopy=m({},t.style)),o=g.createMarkupForStyles(o,this));var a=null;null!=this._tag&&d(this._tag,t)?W.hasOwnProperty(r)||(a=w.createMarkupForCustomAttribute(r,o)):a=w.createMarkupForProperty(r,o),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+w.createMarkupForRoot()),n+=" "+w.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=M(i);else if(null!=a){var u=this.mountChildren(a,e,n);r=u.join("")}}return Y[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&b.queueHTML(r,o.__html);else{var i=V[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)""!==i&&b.queueText(r,i);else if(null!=a)for(var u=this.mountChildren(a,e,n),s=0;s<u.length;s++)b.queueChild(r,u[s])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var i=t.props,a=this._currentElement.props;switch(this._tag){case"input":i=T.getHostProps(this,i),a=T.getHostProps(this,a);break;case"option":i=k.getHostProps(this,i),a=k.getHostProps(this,a);break;case"select":i=A.getHostProps(this,i),a=A.getHostProps(this,a);break;case"textarea":i=R.getHostProps(this,i),a=R.getHostProps(this,a)}switch(o(this,a),this._updateDOMProperties(i,a,e),this._updateDOMChildren(i,a,e,r),this._tag){case"input":T.updateWrapper(this);break;case"textarea":R.updateWrapper(this);break;case"select":e.getReactMountReady().enqueue(f,this)}},_updateDOMProperties:function(e,t,n){var r,o,a;for(r in e)if(!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&null!=e[r])if("style"===r){var u=this._previousStyleCopy;for(o in u)u.hasOwnProperty(o)&&(a=a||{},a[o]="");this._previousStyleCopy=null}else L.hasOwnProperty(r)?e[r]&&F(this,r):d(this._tag,e)?W.hasOwnProperty(r)||w.deleteValueForAttribute(D(this),r):(E.properties[r]||E.isCustomAttribute(r))&&w.deleteValueForProperty(D(this),r);for(r in t){var s=t[r],c="style"===r?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&s!==c&&(null!=s||null!=c))if("style"===r)if(s?s=this._previousStyleCopy=m({},s):this._previousStyleCopy=null,c){for(o in c)!c.hasOwnProperty(o)||s&&s.hasOwnProperty(o)||(a=a||{},a[o]="");for(o in s)s.hasOwnProperty(o)&&c[o]!==s[o]&&(a=a||{},a[o]=s[o])}else a=s;else if(L.hasOwnProperty(r))s?i(this,r,s,n):c&&F(this,r);else if(d(this._tag,t))W.hasOwnProperty(r)||w.setValueForAttribute(D(this),r,s);else if(E.properties[r]||E.isCustomAttribute(r)){var l=D(this);null!=s?w.setValueForProperty(l,r,s):w.deleteValueForProperty(l,r)}}a&&g.setValueForStyles(D(this),a,this)},_updateDOMChildren:function(e,t,n,r){var o=V[typeof e.children]?e.children:null,i=V[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,c=null!=i?null:t.children,l=null!=o||null!=a,f=null!=i||null!=u;null!=s&&null==c?this.updateChildren(null,n,r):l&&!f&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=u?a!==u&&this.updateMarkup(""+u):null!=c&&this.updateChildren(c,n,r)},getHostNode:function(){return D(this)},unmountComponent:function(e){switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":var t=this._wrapperState.listeners;if(t)for(var n=0;n<t.length;n++)t[n].remove();break;case"html":case"head":case"body":v("66",this._tag)}this.unmountChildren(e),O.uncacheNode(this),x.deleteAllListeners(this),this._rootNodeID=0,this._domID=0,this._wrapperState=null},getPublicInstance:function(){return D(this)}},m(h.prototype,h.Mixin,I.Mixin),e.exports=h},function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===o?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var o=(n(170),9);e.exports=r},function(e,t,n){"use strict";var r=n(9),o=n(65),i=n(12),a=function(e){this._currentElement=null,this._hostNode=null,this._hostParent=null,this._hostContainerInfo=null,this._domID=0};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._hostParent=t,this._hostContainerInfo=n;var u=" react-empty: "+this._domID+" ";if(e.useCreateElement){var s=n._ownerDocument,c=s.createComment(u);return i.precacheNode(this,c),o(c)}return e.renderToStaticMarkup?"":"<!--"+u+"-->"},receiveComponent:function(){},getHostNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),e.exports=a},function(e,t,n){"use strict";var r={useCreateElement:!0,useFiber:!1};e.exports=r},function(e,t,n){"use strict";var r=n(155),o=n(12),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};e.exports=i},function(e,t,n){"use strict";function r(){this._rootNodeID&&f.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);l.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var a=c.getNodeFromInstance(this),u=a;u.parentNode;)u=u.parentNode;for(var f=u.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),p=0;p<f.length;p++){var d=f[p];if(d!==a&&d.form===a.form){var h=c.getInstanceFromNode(d);h||i("90"),l.asap(r,h)}}}return n}var i=n(6),a=n(9),u=n(232),s=n(160),c=n(12),l=n(35),f=(n(1),n(4),{getHostProps:function(e,t){var n=s.getValue(t),r=s.getChecked(t);return a({type:void 0,step:void 0,min:void 0,max:void 0},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:null!=t.checked?t.checked:t.defaultChecked,initialValue:null!=t.value?t.value:n,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&u.setValueForProperty(c.getNodeFromInstance(e),"checked",n||!1);var r=c.getNodeFromInstance(e),o=s.getValue(t);if(null!=o){var i=""+o;i!==r.value&&(r.value=i)}else null==t.value&&null!=t.defaultValue&&r.defaultValue!==""+t.defaultValue&&(r.defaultValue=""+t.defaultValue),null==t.checked&&null!=t.defaultChecked&&(r.defaultChecked=!!t.defaultChecked)},postMountWrapper:function(e){var t=e._currentElement.props,n=c.getNodeFromInstance(e);switch(t.type){case"submit":case"reset":break;case"color":case"date":case"datetime":case"datetime-local":case"month":case"time":case"week":n.value="",n.value=n.defaultValue;break;default:n.value=n.value}var r=n.name;""!==r&&(n.name=""),n.defaultChecked=!n.defaultChecked,n.defaultChecked=!n.defaultChecked,""!==r&&(n.name=r)}});e.exports=f},function(e,t,n){"use strict";function r(e){var t="";return i.Children.forEach(e,function(e){null!=e&&("string"==typeof e||"number"==typeof e?t+=e:s||(s=!0))}),t}var o=n(9),i=n(69),a=n(12),u=n(234),s=(n(4),!1),c={mountWrapper:function(e,t,n){var o=null;if(null!=n){var i=n;"optgroup"===i._tag&&(i=i._hostParent),null!=i&&"select"===i._tag&&(o=u.getSelectValueContext(i))}var a=null;if(null!=o){var s;if(s=null!=t.value?t.value+"":r(t.children),a=!1,Array.isArray(o)){for(var c=0;c<o.length;c++)if(""+o[c]===s){a=!0;break}}else a=""+o===s}e._wrapperState={selected:a}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){a.getNodeFromInstance(e).setAttribute("value",t.value)}},getHostProps:function(e,t){var n=o({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var i=r(t.children);return i&&(n.children=i),n}};e.exports=c},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length;return{start:i,end:i+r}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,u=t.getRangeAt(0);try{u.startContainer.nodeType,u.endContainer.nodeType}catch(e){return null}var s=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=s?0:u.toString().length,l=u.cloneRange();l.selectNodeContents(e),l.setEnd(u.startContainer,u.startOffset);var f=r(l.startContainer,l.startOffset,l.endContainer,l.endOffset),p=f?0:l.toString().length,d=p+c,h=document.createRange();h.setStart(n,o),h.setEnd(i,a);var v=h.collapsed;return{start:v?d:p,end:v?p:d}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();void 0===t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,o=Math.min(t.start,r),i=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var u=c(e,o),s=c(e,i);if(u&&s){var f=document.createRange();f.setStart(u.node,u.offset),n.removeAllRanges(),o>i?(n.addRange(f),n.extend(s.node,s.offset)):(f.setEnd(s.node,s.offset),n.addRange(f))}}}var s=n(17),c=n(628),l=n(245),f=s.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:f?o:i,setOffsets:f?a:u};e.exports=p},function(e,t,n){"use strict";var r=n(6),o=n(9),i=n(155),a=n(65),u=n(12),s=n(107),c=(n(1),n(170),function(e){this._currentElement=e,this._stringText=""+e,this._hostNode=null,this._hostParent=null,this._domID=0,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});o(c.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,i=" react-text: "+o+" ";if(this._domID=o,this._hostParent=t,e.useCreateElement){var c=n._ownerDocument,l=c.createComment(i),f=c.createComment(" /react-text "),p=a(c.createDocumentFragment());return a.queueChild(p,a(l)),this._stringText&&a.queueChild(p,a(c.createTextNode(this._stringText))),a.queueChild(p,a(f)),u.precacheNode(this,l),this._closingComment=f,p}var d=s(this._stringText);return e.renderToStaticMarkup?d:"<!--"+i+"-->"+d+"<!-- /react-text -->"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getHostNode();i.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=u.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n&&r("67",this._domID),8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,u.uncacheNode(this)}}),e.exports=c},function(e,t,n){"use strict";function r(){this._rootNodeID&&l.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);return c.asap(r,this),n}var i=n(6),a=n(9),u=n(160),s=n(12),c=n(35),l=(n(1),n(4),{getHostProps:function(e,t){return null!=t.dangerouslySetInnerHTML&&i("91"),a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=u.getValue(t),r=n;if(null==n){var a=t.defaultValue,s=t.children;null!=s&&(null!=a&&i("92"),Array.isArray(s)&&(s.length<=1||i("93"),s=s[0]),a=""+s),null==a&&(a=""),r=a}e._wrapperState={initialValue:""+r,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=s.getNodeFromInstance(e),r=u.getValue(t);if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=s.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}});e.exports=l},function(e,t,n){"use strict";function r(e,t){"_hostNode"in e||s("33"),"_hostNode"in t||s("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var o=0,i=t;i;i=i._hostParent)o++;for(;n-o>0;)e=e._hostParent,n--;for(;o-n>0;)t=t._hostParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function o(e,t){"_hostNode"in e||s("35"),"_hostNode"in t||s("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function i(e){return"_hostNode"in e||s("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var o;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o<r.length;o++)t(r[o],"bubbled",n)}function u(e,t,n,o,i){for(var a=e&&t?r(e,t):null,u=[];e&&e!==a;)u.push(e),e=e._hostParent;for(var s=[];t&&t!==a;)s.push(t),t=t._hostParent;var c;for(c=0;c<u.length;c++)n(u[c],"bubbled",o);for(c=s.length;c-- >0;)n(s[c],"captured",i)}var s=n(6);n(1);e.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:u}},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(9),i=n(35),a=n(106),u=n(28),s={initialize:u,close:function(){p.isBatchingUpdates=!1}},c={initialize:u,close:i.flushBatchedUpdates.bind(i)},l=[c,s];o(r.prototype,a,{getTransactionWrappers:function(){return l}});var f=new r,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=p.isBatchingUpdates;return p.isBatchingUpdates=!0,a?e(t,n,r,o,i):f.perform(e,null,t,n,r,o,i)}};e.exports=p},function(e,t,n){"use strict";function r(){x||(x=!0,g.EventEmitter.injectReactEventListener(y),g.EventPluginHub.injectEventPluginOrder(u),g.EventPluginUtils.injectComponentTree(p),g.EventPluginUtils.injectTreeTraversal(h),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:w,EnterLeaveEventPlugin:s,ChangeEventPlugin:a,SelectEventPlugin:E,BeforeInputEventPlugin:i}),g.HostComponent.injectGenericComponentClass(f),g.HostComponent.injectTextComponentClass(v),g.DOMProperty.injectDOMPropertyConfig(o),g.DOMProperty.injectDOMPropertyConfig(c),g.DOMProperty.injectDOMPropertyConfig(_),g.EmptyComponent.injectEmptyComponentFactory(function(e){return new d(e)}),g.Updates.injectReconcileTransaction(b),g.Updates.injectBatchingStrategy(m),g.Component.injectEnvironment(l))}var o=n(568),i=n(570),a=n(572),u=n(574),s=n(575),c=n(577),l=n(579),f=n(582),p=n(12),d=n(584),h=n(592),v=n(590),m=n(593),y=n(597),g=n(598),b=n(603),_=n(608),E=n(609),w=n(610),x=!1;e.exports={inject:r}},function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=r},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(79),i={handleTopLevel:function(e,t,n,i){r(o.extractEvents(e,t,n,i))}};e.exports=i},function(e,t,n){"use strict";function r(e){for(;e._hostParent;)e=e._hostParent;var t=f.getNodeFromInstance(e),n=t.parentNode;return f.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=d(e.nativeEvent),n=f.getClosestInstanceFromNode(t),o=n;do{e.ancestors.push(o),o=o&&r(o)}while(o);for(var i=0;i<e.ancestors.length;i++)n=e.ancestors[i],v._handleTopLevel(e.topLevelType,n,e.nativeEvent,d(e.nativeEvent))}function a(e){e(h(window))}var u=n(9),s=n(205),c=n(17),l=n(58),f=n(12),p=n(35),d=n(167),h=n(462);u(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){return n?s.listen(n,t,v.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){return n?s.capture(n,t,v.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(v._enabled){var n=o.getPooled(e,t);try{p.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=v},function(e,t,n){"use strict";var r=n(66),o=n(79),i=n(158),a=n(161),u=n(235),s=n(104),c=n(237),l=n(35),f={Component:a.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventPluginUtils:i.injection,EventEmitter:s.injection,HostComponent:c.injection,Updates:l.injection};e.exports=f},function(e,t,n){"use strict";var r=n(621),o=/^<\!\-\-/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return o.test(e)?e:e.replace(/\/?>/," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);return n=n&&parseInt(n,10),r(e)===n}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){return{type:"INSERT_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:"MOVE_EXISTING",content:null,fromIndex:e._mountIndex,fromNode:p.getHostNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:"REMOVE_NODE",content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:"SET_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e){return{type:"TEXT_CONTENT",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function s(e,t){return t&&(e=e||[],e.push(t)),e}function c(e,t){f.processChildrenUpdates(e,t)}var l=n(6),f=n(161),p=(n(81),n(29),n(41),n(67)),d=n(578),h=(n(28),n(624)),v=(n(1),{Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return d.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o,i){var a,u=0;return a=h(t,u),d.updateChildren(e,a,n,r,o,this,this._hostContainerInfo,i,u),a},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=0,c=p.mountComponent(u,t,this,this._hostContainerInfo,n,s);u._mountIndex=i++,o.push(c)}return o},updateTextContent:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");c(this,[u(e)])},updateMarkup:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");c(this,[a(e)])},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=[],a=this._reconcilerUpdateChildren(r,e,i,o,t,n);if(a||r){var u,l=null,f=0,d=0,h=0,v=null;for(u in a)if(a.hasOwnProperty(u)){var m=r&&r[u],y=a[u];m===y?(l=s(l,this.moveChild(m,v,f,d)),d=Math.max(m._mountIndex,d),m._mountIndex=f):(m&&(d=Math.max(m._mountIndex,d)),l=s(l,this._mountChildAtIndex(y,i[h],v,f,t,n)),h++),f++,v=p.getHostNode(y)}for(u in o)o.hasOwnProperty(u)&&(l=s(l,this._unmountChild(r[u],o[u])));l&&c(this,l),this._renderedChildren=a}},unmountChildren:function(e){var t=this._renderedChildren;d.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){if(e._mountIndex<r)return o(e,t,n)},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return i(e,t)},_mountChildAtIndex:function(e,t,n,r,o,i){return e._mountIndex=r,this.createChild(e,n,t)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}});e.exports=v},function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)}var o=n(6),i=(n(1),{addComponentAsRefTo:function(e,t,n){r(n)||o("119"),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(n)||o("120");var i=n.getPublicInstance();i&&i.refs[t]===e.getPublicInstance()&&n.detachRef(t)}});e.exports=i},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.useCreateElement=e}var o=n(9),i=n(231),a=n(58),u=n(104),s=n(238),c=(n(29),n(106)),l=n(163),f={initialize:s.getSelectionInformation,close:s.restoreSelection},p={initialize:function(){var e=u.isEnabled();return u.setEnabled(!1),e},close:function(e){u.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[f,p,d],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},getUpdateQueue:function(){return l},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};o(r.prototype,c,v),a.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(601),a={};a.attachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null,r=null;null!==e&&"object"==typeof e&&(n=e.ref,r=e._owner);var o=null,i=null;return null!==t&&"object"==typeof t&&(o=t.ref,i=t._owner),n!==o||"string"==typeof o&&i!==r},a.detachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1,this.updateQueue=new u(this)}var o=n(9),i=n(58),a=n(106),u=(n(29),n(606)),s=[],c={enqueue:function(){}},l={getTransactionWrappers:function(){return s},getReactMountReady:function(){return c},getUpdateQueue:function(){return this.updateQueue},destructor:function(){},checkpoint:function(){},rollback:function(){}};o(r.prototype,a,l),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(163),i=(n(4),function(){function e(t){r(this,e),this.transaction=t}return e.prototype.isMounted=function(e){return!1},e.prototype.enqueueCallback=function(e,t,n){this.transaction.isInTransaction()&&o.enqueueCallback(e,t,n)},e.prototype.enqueueForceUpdate=function(e){this.transaction.isInTransaction()&&o.enqueueForceUpdate(e)},e.prototype.enqueueReplaceState=function(e,t){this.transaction.isInTransaction()&&o.enqueueReplaceState(e,t)},e.prototype.enqueueSetState=function(e,t){this.transaction.isInTransaction()&&o.enqueueSetState(e,t)},e}());e.exports=i},function(e,t,n){"use strict";e.exports="15.4.2"},function(e,t,n){"use strict";var r={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},o={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},i={Properties:{},DOMAttributeNamespaces:{xlinkActuate:r.xlink,xlinkArcrole:r.xlink,xlinkHref:r.xlink,xlinkRole:r.xlink,xlinkShow:r.xlink,xlinkTitle:r.xlink,xlinkType:r.xlink,xmlBase:r.xml,xmlLang:r.xml,xmlSpace:r.xml},DOMAttributeNames:{}};Object.keys(o).forEach(function(e){i.Properties[e]=0,o[e]&&(i.DOMAttributeNames[e]=o[e])}),e.exports=i},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&s.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(g||null==v||v!==l())return null;var n=r(v);if(!y||!p(y,n)){y=n;var o=c.getPooled(h.select,m,e,t);return o.type="select",o.target=v,i.accumulateTwoPhaseDispatches(o),o}return null}var i=n(80),a=n(17),u=n(12),s=n(238),c=n(40),l=n(207),f=n(247),p=n(138),d=a.canUseDOM&&"documentMode"in document&&document.documentMode<=11,h={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},v=null,m=null,y=null,g=!1,b=!1,_={eventTypes:h,extractEvents:function(e,t,n,r){if(!b)return null;var i=t?u.getNodeFromInstance(t):window;switch(e){case"topFocus":(f(i)||"true"===i.contentEditable)&&(v=i,m=t,y=null);break;case"topBlur":v=null,m=null,y=null;break;case"topMouseDown":g=!0;break;case"topContextMenu":case"topMouseUp":return g=!1,o(n,r);case"topSelectionChange":if(d)break;case"topKeyDown":case"topKeyUp":return o(n,r)}return null},didPutListener:function(e,t,n){"onSelect"===t&&(b=!0)}};e.exports=_},function(e,t,n){"use strict";function r(e){return"."+e._rootNodeID}function o(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var i=n(6),a=n(205),u=n(80),s=n(12),c=n(611),l=n(612),f=n(40),p=n(615),d=n(617),h=n(105),v=n(614),m=n(618),y=n(619),g=n(82),b=n(620),_=n(28),E=n(165),w=(n(1),{}),x={};["abort","animationEnd","animationIteration","animationStart","blur","canPlay","canPlayThrough","click","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,r="top"+t,o={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};w[e]=o,x[r]=o});var C={},S={eventTypes:w,extractEvents:function(e,t,n,r){var o=x[e];if(!o)return null;var a;switch(e){case"topAbort":case"topCanPlay":case"topCanPlayThrough":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topVolumeChange":case"topWaiting":a=f;break;case"topKeyPress":if(0===E(n))return null;case"topKeyDown":case"topKeyUp":a=d;break;case"topBlur":case"topFocus":a=p;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":a=h;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":a=v;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=m;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":a=c;break;case"topTransitionEnd":a=y;break;case"topScroll":a=g;break;case"topWheel":a=b;break;case"topCopy":case"topCut":case"topPaste":a=l}a||i("86",e);var s=a.getPooled(o,t,n,r);return u.accumulateTwoPhaseDispatches(s),s},didPutListener:function(e,t,n){if("onClick"===t&&!o(e._tag)){var i=r(e),u=s.getNodeFromInstance(e);C[i]||(C[i]=a.listen(u,"click",_))}},willDeleteListener:function(e,t){if("onClick"===t&&!o(e._tag)){var n=r(e);C[n].remove(),delete C[n]}}};e.exports=S},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i={animationName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(105),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(82),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(82),i=n(165),a=n(625),u=n(166),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(82),i=n(166),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(40),i={propertyName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(105),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0,i=e.length,a=-4&i;r<a;){for(var u=Math.min(r+4096,a);r<u;r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=o,n%=o}for(;r<i;r++)n+=t+=e.charCodeAt(r);return t%=o,n%=o,t|n<<16}var o=65521;e.exports=r},function(e,t,n){"use strict";function r(e,t,n){if(null==t||"boolean"==typeof t||""===t)return"";if(isNaN(t)||0===t||i.hasOwnProperty(e)&&i[e])return""+t;if("string"==typeof t){t=t.trim()}return t+"px"}var o=n(230),i=(n(4),o.isUnitlessNumber);e.exports=r},function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=a.get(e);if(t)return t=u(t),t?i.getNodeFromInstance(t):null;"function"==typeof e.render?o("44"):o("45",Object.keys(e))}var o=n(6),i=(n(41),n(12)),a=n(81),u=n(244);n(1),n(4);e.exports=r},function(e,t,n){"use strict";(function(t){function r(e,t,n,r){if(e&&"object"==typeof e){var o=e,i=void 0===o[n];i&&null!=t&&(o[n]=t)}}function o(e,t){if(null==e)return e;var n={};return i(e,r,n),n}var i=(n(159),n(249));n(4);void 0!==t&&n.i({NODE_ENV:"production"}),e.exports=o}).call(t,n(154))},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(165),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";e.exports=r},function(e,t,n){"use strict";function r(){return o++}var o=1;e.exports=r},function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,i<=t&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}e.exports=i},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(u[e])return u[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in s)return u[e]=t[n];return""}var i=n(17),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},u={},s={};i.canUseDOM&&(s=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(107);e.exports=r},function(e,t,n){"use strict";var r=n(239);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(15),u=(n.n(a),n(252));n(171);n.d(t,"a",function(){return s});var s=function(e){function t(n,i){r(this,t);var a=o(this,e.call(this,n,i));return a.store=n.store,a}return i(t,e),t.prototype.getChildContext=function(){return{store:this.store,storeSubscription:null}},t.prototype.render=function(){return a.Children.only(this.props.children)},t}(a.Component);s.propTypes={store:u.a.isRequired,children:a.PropTypes.element.isRequired},s.childContextTypes={store:u.a.isRequired,storeSubscription:u.b},s.displayName="Provider"},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n){for(var r=t.length-1;r>=0;r--){var o=t[r](e);if(o)return o}return function(t,r){throw new Error("Invalid value of type "+typeof e+" for "+n+" argument when connecting component "+r.wrappedComponentName+".")}}function i(e,t){return e===t}var a=n(250),u=n(640),s=n(634),c=n(635),l=n(636),f=n(637),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.a=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.connectHOC,n=void 0===t?a.a:t,d=e.mapStateToPropsFactories,h=void 0===d?c.a:d,v=e.mapDispatchToPropsFactories,m=void 0===v?s.a:v,y=e.mergePropsFactories,g=void 0===y?l.a:y,b=e.selectorFactory,_=void 0===b?f.a:b;return function(e,t,a){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},c=s.pure,l=void 0===c||c,f=s.areStatesEqual,d=void 0===f?i:f,v=s.areOwnPropsEqual,y=void 0===v?u.a:v,b=s.areStatePropsEqual,E=void 0===b?u.a:b,w=s.areMergedPropsEqual,x=void 0===w?u.a:w,C=r(s,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),S=o(e,h,"mapStateToProps"),P=o(t,m,"mapDispatchToProps"),O=o(a,g,"mergeProps");return n(_,p({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:Boolean(e),initMapStateToProps:S,initMapDispatchToProps:P,initMergeProps:O,pure:l,areStatesEqual:d,areOwnPropsEqual:y,areStatePropsEqual:E,areMergedPropsEqual:x},C))}}()},function(e,t,n){"use strict";function r(e){return"function"==typeof e?n.i(u.a)(e,"mapDispatchToProps"):void 0}function o(e){return e?void 0:n.i(u.b)(function(e){return{dispatch:e}})}function i(e){return e&&"object"==typeof e?n.i(u.b)(function(t){return n.i(a.bindActionCreators)(e,t)}):void 0}var a=n(110),u=n(251);t.a=[r,o,i]},function(e,t,n){"use strict";function r(e){return"function"==typeof e?n.i(i.a)(e,"mapStateToProps"):void 0}function o(e){return e?void 0:n.i(i.b)(function(){return{}})}var i=n(251);t.a=[r,o]},function(e,t,n){"use strict";function r(e,t,n){return u({},n,e,t)}function o(e){return function(t,n){var r=(n.displayName,n.pure),o=n.areMergedPropsEqual,i=!1,a=void 0;return function(t,n,u){var s=e(t,n,u);return i?r&&o(s,a)||(a=s):(i=!0,a=s),a}}}function i(e){return"function"==typeof e?o(e):void 0}function a(e){return e?void 0:function(){return r}}var u=(n(253),Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e});t.a=[i,a]},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n,r){return function(o,i){return n(e(o,i),t(r,i),i)}}function i(e,t,n,r,o){function i(o,i){return h=o,v=i,m=e(h,v),y=t(r,v),g=n(m,y,v),d=!0,g}function a(){return m=e(h,v),t.dependsOnOwnProps&&(y=t(r,v)),g=n(m,y,v)}function u(){return e.dependsOnOwnProps&&(m=e(h,v)),t.dependsOnOwnProps&&(y=t(r,v)),g=n(m,y,v)}function s(){var t=e(h,v),r=!p(t,m);return m=t,r&&(g=n(m,y,v)),g}function c(e,t){var n=!f(t,v),r=!l(e,h);return h=e,v=t,n&&r?a():n?u():r?s():g}var l=o.areStatesEqual,f=o.areOwnPropsEqual,p=o.areStatePropsEqual,d=!1,h=void 0,v=void 0,m=void 0,y=void 0,g=void 0;return function(e,t){return d?c(e,t):i(e,t)}}function a(e,t){var n=t.initMapStateToProps,a=t.initMapDispatchToProps,u=t.initMergeProps,s=r(t,["initMapStateToProps","initMapDispatchToProps","initMergeProps"]),c=n(e,s),l=a(e,s),f=u(e,s);return(s.pure?i:o)(c,l,f,e,s)}n(638);t.a=a},function(e,t,n){"use strict";n(171)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(){var e=[],t=[];return{clear:function(){t=i,e=i},notify:function(){for(var n=e=t,r=0;r<n.length;r++)n[r]()},subscribe:function(n){var r=!0;return t===e&&(t=e.slice()),t.push(n),function(){r&&e!==i&&(r=!1,t===e&&(t=e.slice()),t.splice(t.indexOf(n),1))}}}}n.d(t,"a",function(){return u});var i=null,a={notify:function(){}},u=function(){function e(t,n,o){r(this,e),this.store=t,this.parentSub=n,this.onStateChange=o,this.unsubscribe=null,this.listeners=a}return e.prototype.addNestedSub=function(e){return this.trySubscribe(),this.listeners.subscribe(e)},e.prototype.notifyNestedSubs=function(){this.listeners.notify()},e.prototype.isSubscribed=function(){return Boolean(this.unsubscribe)},e.prototype.trySubscribe=function(){this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.onStateChange):this.store.subscribe(this.onStateChange),this.listeners=o())},e.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=a)},e}()},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}t.a=o;var i=Object.prototype.hasOwnProperty},function(e,t,n){"use strict";function r(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}function o(e){var t={"=0":"=","=2":":"};return(""+("."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1))).replace(/(=0|=2)/g,function(e){return t[e]})}var i={escape:r,unescape:o};e.exports=i},function(e,t,n){"use strict";var r=n(71),o=(n(1),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},s=function(e){var t=this;e instanceof t||r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=o,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=10),n.release=s,n},f={addPoolingTo:l,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:u};e.exports=f},function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);y(e,i,r),o.release(r)}function u(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function s(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,u=e.context,s=a.call(u,t,e.count++);Array.isArray(s)?c(s,o,n,m.thatReturnsArgument):null!=s&&(v.isValidElement(s)&&(s=v.cloneAndReplaceKey(s,i+(!s.key||t&&t.key===s.key?"":r(s.key)+"/")+n)),o.push(s))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=u.getPooled(t,a,o,i);y(e,s,c),u.release(c)}function l(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function f(e,t,n){return null}function p(e,t){return y(e,f,null)}function d(e){var t=[];return c(e,t,null,m.thatReturnsArgument),t}var h=n(642),v=n(70),m=n(28),y=n(651),g=h.twoArgumentPooler,b=h.fourArgumentPooler,_=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,g),u.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(u,b);var E={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:p,toArray:d};e.exports=E},function(e,t,n){"use strict";function r(e){return e}function o(e,t){var n=_.hasOwnProperty(t)?_[t]:null;w.hasOwnProperty(t)&&"OVERRIDE_BASE"!==n&&p("73",t),e&&"DEFINE_MANY"!==n&&"DEFINE_MANY_MERGED"!==n&&p("74",t)}function i(e,t){if(t){"function"==typeof t&&p("75"),v.isValidElement(t)&&p("76");var n=e.prototype,r=n.__reactAutoBindPairs;t.hasOwnProperty(g)&&E.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==g){var a=t[i],u=n.hasOwnProperty(i);if(o(u,i),E.hasOwnProperty(i))E[i](e,a);else{var l=_.hasOwnProperty(i),f="function"==typeof a,d=f&&!l&&!u&&!1!==t.autobind;if(d)r.push(i,a),n[i]=a;else if(u){var h=_[i];(!l||"DEFINE_MANY_MERGED"!==h&&"DEFINE_MANY"!==h)&&p("77",h,i),"DEFINE_MANY_MERGED"===h?n[i]=s(n[i],a):"DEFINE_MANY"===h&&(n[i]=c(n[i],a))}else n[i]=a}}}else;}function a(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in E;o&&p("78",n);var i=n in e;i&&p("79",n),e[n]=r}}}function u(e,t){e&&t&&"object"==typeof e&&"object"==typeof t||p("80");for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]&&p("81",n),e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return u(o,n),u(o,r),o}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function f(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=l(e,o)}}var p=n(71),d=n(9),h=n(172),v=n(70),m=(n(256),n(173)),y=n(75),g=(n(1),n(4),"mixins"),b=[],_={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},E={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=d({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=d({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=d({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},w={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},x=function(){};d(x.prototype,h.prototype,w);var C={createClass:function(e){var t=r(function(e,n,r){this.__reactAutoBindPairs.length&&f(this),this.props=e,this.context=n,this.refs=y,this.updater=r||m,this.state=null;var o=this.getInitialState?this.getInitialState():null;("object"!=typeof o||Array.isArray(o))&&p("82",t.displayName||"ReactCompositeComponent"),this.state=o});t.prototype=new x,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],b.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render||p("83");for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){b.push(e)}}};e.exports=C},function(e,t,n){"use strict";var r=n(70),o=r.createFactory,i={a:o("a"),abbr:o("abbr"),address:o("address"),area:o("area"),article:o("article"),aside:o("aside"),audio:o("audio"),b:o("b"),base:o("base"),bdi:o("bdi"),bdo:o("bdo"),big:o("big"),blockquote:o("blockquote"),body:o("body"),br:o("br"),button:o("button"),canvas:o("canvas"),caption:o("caption"),cite:o("cite"),code:o("code"),col:o("col"),colgroup:o("colgroup"),data:o("data"),datalist:o("datalist"),dd:o("dd"),del:o("del"),details:o("details"),dfn:o("dfn"),dialog:o("dialog"),div:o("div"),dl:o("dl"),dt:o("dt"),em:o("em"),embed:o("embed"),fieldset:o("fieldset"),figcaption:o("figcaption"),figure:o("figure"),footer:o("footer"),form:o("form"),h1:o("h1"),h2:o("h2"),h3:o("h3"),h4:o("h4"),h5:o("h5"),h6:o("h6"),head:o("head"),header:o("header"),hgroup:o("hgroup"),hr:o("hr"),html:o("html"),i:o("i"),iframe:o("iframe"),img:o("img"),input:o("input"),ins:o("ins"),kbd:o("kbd"),keygen:o("keygen"),label:o("label"),legend:o("legend"),li:o("li"),link:o("link"),main:o("main"),map:o("map"),mark:o("mark"),menu:o("menu"),menuitem:o("menuitem"),meta:o("meta"),meter:o("meter"),nav:o("nav"),noscript:o("noscript"),object:o("object"),ol:o("ol"),optgroup:o("optgroup"),option:o("option"),output:o("output"),p:o("p"),param:o("param"),picture:o("picture"),pre:o("pre"),progress:o("progress"),q:o("q"),rp:o("rp"),rt:o("rt"),ruby:o("ruby"),s:o("s"),samp:o("samp"),script:o("script"),section:o("section"),select:o("select"),small:o("small"),source:o("source"),span:o("span"),strong:o("strong"),style:o("style"),sub:o("sub"),summary:o("summary"),sup:o("sup"),table:o("table"),tbody:o("tbody"),td:o("td"),textarea:o("textarea"),tfoot:o("tfoot"),th:o("th"),thead:o("thead"),time:o("time"),title:o("title"),tr:o("tr"),track:o("track"),u:o("u"),ul:o("ul"),var:o("var"),video:o("video"),wbr:o("wbr"),circle:o("circle"),clipPath:o("clipPath"),defs:o("defs"),ellipse:o("ellipse"),g:o("g"),image:o("image"),line:o("line"),linearGradient:o("linearGradient"),mask:o("mask"),path:o("path"),pattern:o("pattern"),polygon:o("polygon"),polyline:o("polyline"),radialGradient:o("radialGradient"),rect:o("rect"),stop:o("stop"),svg:o("svg"),text:o("text"),tspan:o("tspan")};e.exports=i},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e==1/t:e!==e&&t!==t}function o(e){this.message=e,this.stack=""}function i(e){function t(t,n,r,i,a,u,s){i=i||x,u=u||r;if(null==n[r]){var c=b[a];return t?new o(null===n[r]?"The "+c+" `"+u+"` is marked as required in `"+i+"`, but its value is `null`.":"The "+c+" `"+u+"` is marked as required in `"+i+"`, but its value is `undefined`."):null}return e(n,r,i,a,u)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function a(e){function t(t,n,r,i,a,u){var s=t[n];if(v(s)!==e)return new o("Invalid "+b[i]+" `"+a+"` of type `"+m(s)+"` supplied to `"+r+"`, expected `"+e+"`.");return null}return i(t)}function u(e){function t(t,n,r,i,a){if("function"!=typeof e)return new o("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var u=t[n];if(!Array.isArray(u)){return new o("Invalid "+b[i]+" `"+a+"` of type `"+v(u)+"` supplied to `"+r+"`, expected an array.")}for(var s=0;s<u.length;s++){var c=e(u,s,r,i,a+"["+s+"]",_);if(c instanceof Error)return c}return null}return i(t)}function s(e){function t(t,n,r,i,a){if(!(t[n]instanceof e)){var u=b[i],s=e.name||x;return new o("Invalid "+u+" `"+a+"` of type `"+y(t[n])+"` supplied to `"+r+"`, expected instance of `"+s+"`.")}return null}return i(t)}function c(e){function t(t,n,i,a,u){for(var s=t[n],c=0;c<e.length;c++)if(r(s,e[c]))return null;return new o("Invalid "+b[a]+" `"+u+"` of value `"+s+"` supplied to `"+i+"`, expected one of "+JSON.stringify(e)+".")}return Array.isArray(e)?i(t):E.thatReturnsNull}function l(e){function t(t,n,r,i,a){if("function"!=typeof e)return new o("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var u=t[n],s=v(u);if("object"!==s){return new o("Invalid "+b[i]+" `"+a+"` of type `"+s+"` supplied to `"+r+"`, expected an object.")}for(var c in u)if(u.hasOwnProperty(c)){var l=e(u,c,r,i,a+"."+c,_);if(l instanceof Error)return l}return null}return i(t)}function f(e){function t(t,n,r,i,a){for(var u=0;u<e.length;u++){if(null==(0,e[u])(t,n,r,i,a,_))return null}return new o("Invalid "+b[i]+" `"+a+"` supplied to `"+r+"`.")}return Array.isArray(e)?i(t):E.thatReturnsNull}function p(e){function t(t,n,r,i,a){var u=t[n],s=v(u);if("object"!==s){return new o("Invalid "+b[i]+" `"+a+"` of type `"+s+"` supplied to `"+r+"`, expected `object`.")}for(var c in e){var l=e[c];if(l){var f=l(u,c,r,i,a+"."+c,_);if(f)return f}}return null}return i(t)}function d(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(d);if(null===e||g.isValidElement(e))return!0;var t=w(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!d(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!d(o[1]))return!1}return!0;default:return!1}}function h(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":h(t,e)?"symbol":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function y(e){return e.constructor&&e.constructor.name?e.constructor.name:x}var g=n(70),b=n(256),_=n(647),E=n(28),w=n(258),x=(n(4),"<<anonymous>>"),C={array:a("array"),bool:a("boolean"),func:a("function"),number:a("number"),object:a("object"),string:a("string"),symbol:a("symbol"),any:function(){return i(E.thatReturns(null))}(),arrayOf:u,element:function(){function e(e,t,n,r,i){var a=e[t];if(!g.isValidElement(a)){return new o("Invalid "+b[r]+" `"+i+"` of type `"+v(a)+"` supplied to `"+n+"`, expected a single ReactElement.")}return null}return i(e)}(),instanceOf:s,node:function(){function e(e,t,n,r,i){if(!d(e[t])){return new o("Invalid "+b[r]+" `"+i+"` supplied to `"+n+"`, expected a ReactNode.")}return null}return i(e)}(),objectOf:l,oneOf:c,oneOfType:f,shape:p};o.prototype=Error.prototype,e.exports=C},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=s,this.updater=n||u}function o(){}var i=n(9),a=n(172),u=n(173),s=n(75);o.prototype=a.prototype,r.prototype=new o,r.prototype.constructor=r,i(r.prototype,a.prototype),r.prototype.isPureReactComponent=!0,e.exports=r},function(e,t,n){"use strict";e.exports="15.4.2"},function(e,t,n){"use strict";function r(e){return i.isValidElement(e)||o("143"),e}var o=n(71),i=n(70);n(1);e.exports=r},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===u)return n(i,e,""===t?l+r(e,0):t),1;var d,h,v=0,m=""===t?l:t+f;if(Array.isArray(e))for(var y=0;y<e.length;y++)d=e[y],h=m+r(d,y),v+=o(d,h,n,i);else{var g=s(e);if(g){var b,_=g.call(e);if(g!==e.entries)for(var E=0;!(b=_.next()).done;)d=b.value,h=m+r(d,E++),v+=o(d,h,n,i);else for(;!(b=_.next()).done;){var w=b.value;w&&(d=w[1],h=m+c.escape(w[0])+f+r(d,0),v+=o(d,h,n,i))}}else if("object"===p){var x="",C=String(e);a("31","[object Object]"===C?"object with keys {"+Object.keys(e).join(", ")+"}":C,x)}}return v}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(71),u=(n(41),n(255)),s=n(258),c=(n(1),n(641)),l=(n(4),"."),f=":";e.exports=i},function(e,t,n){!function(t,r){e.exports=r(n(15))}(0,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){n(177),e.exports=n(185)},function(e,t,n){"use strict";function r(e,t,n,r,o,i,a,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,u],l=0;s=new Error(t.replace(/%s/g,function(){return c[l++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}}e.exports=r},function(e,t,n){"use strict";var r=n(9),o=r;e.exports=o},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var r=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var i,a,u=n(e),s=1;s<arguments.length;s++){i=Object(arguments[s]);for(var c in i)r.call(i,c)&&(u[c]=i[c]);if(Object.getOwnPropertySymbols){a=Object.getOwnPropertySymbols(i);for(var l=0;l<a.length;l++)o.call(i,a[l])&&(u[a[l]]=i[a[l]])}}return u}},function(e,t,n){"use strict";function r(e){for(var t;t=e._renderedComponent;)e=t;return e}function o(e,t){var n=r(e);n._nativeNode=t,t[v]=n}function i(e){var t=e._nativeNode;t&&(delete t[v],e._nativeNode=null)}function a(e,t){if(!(e._flags&h.hasCachedChildNodes)){var n=e._renderedChildren,i=t.firstChild;e:for(var a in n)if(n.hasOwnProperty(a)){var u=n[a],s=r(u)._domID;if(null!=s){for(;null!==i;i=i.nextSibling)if(1===i.nodeType&&i.getAttribute(d)===String(s)||8===i.nodeType&&i.nodeValue===" react-text: "+s+" "||8===i.nodeType&&i.nodeValue===" react-empty: "+s+" "){o(u,i);continue e}p(!1)}}e._flags|=h.hasCachedChildNodes}}function u(e){if(e[v])return e[v];for(var t=[];!e[v];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[v]);e=t.pop())n=r,t.length&&a(r,e);return n}function s(e){var t=u(e);return null!=t&&t._nativeNode===e?t:null}function c(e){if(void 0===e._nativeNode&&p(!1),e._nativeNode)return e._nativeNode;for(var t=[];!e._nativeNode;)t.push(e),e._nativeParent||p(!1),e=e._nativeParent;for(;t.length;e=t.pop())a(e,e._nativeNode);return e._nativeNode}var l=n(19),f=n(139),p=n(1),d=l.ID_ATTRIBUTE_NAME,h=f,v="__reactInternalInstance$"+Math.random().toString(36).slice(2),m={getClosestInstanceFromNode:u,getInstanceFromNode:s,getNodeFromInstance:c,precacheChildNodes:a,precacheNode:o,uncacheNode:i};e.exports=m},function(t,n){t.exports=e},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t,n){"use strict";var r=n(326);e.exports={debugTool:r}},function(e,t,n){(function(t){var r=n(226),o=r("object"==typeof t&&t),i=r("object"==typeof self&&self),a=r("object"==typeof this&&this),u=o||i||a||Function("return this")();e.exports=u}).call(t,function(){return this}())},function(e,t){"use strict";function n(e){return function(){return e}}var r=function(){};r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";function r(){O.ReactReconcileTransaction&&E||m(!1)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=f.getPooled(),this.reconcileTransaction=O.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){r(),E.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;t!==y.length&&m(!1),y.sort(a),g++;for(var n=0;n<t;n++){var r=y[n],o=r._pendingCallbacks;r._pendingCallbacks=null;var i;if(d.logTopLevelRenders){var u=r;r._currentElement.props===r._renderedComponent._currentElement&&(u=r._renderedComponent),i="React update: "+u.getName(),console.time(i)}if(h.performUpdateIfNecessary(r,e.reconcileTransaction,g),i&&console.timeEnd(i),o)for(var s=0;s<o.length;s++)e.callbackQueue.enqueue(o[s],r.getPublicInstance())}}function s(e){return r(),E.isBatchingUpdates?(y.push(e),void(null==e._updateBatchNumber&&(e._updateBatchNumber=g+1))):void E.batchedUpdates(s,e)}function c(e,t){E.isBatchingUpdates||m(!1),b.enqueue(e,t),_=!0}var l=n(3),f=n(136),p=n(16),d=n(145),h=(n(7),n(21)),v=n(51),m=n(1),y=[],g=0,b=f.getPooled(),_=!1,E=null,w={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),S()):y.length=0}},x={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},C=[w,x];l(o.prototype,v.Mixin,{getTransactionWrappers:function(){return C},destructor:function(){this.dirtyComponentsLength=null,f.release(this.callbackQueue),this.callbackQueue=null,O.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return v.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),p.addPoolingTo(o);var S=function(){for(;y.length||_;){if(y.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(_){_=!1;var t=b;b=f.getPooled(),t.notifyAll(),f.release(t)}}},P={injectReconcileTransaction:function(e){e||m(!1),O.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e||m(!1),"function"!=typeof e.batchedUpdates&&m(!1),"boolean"!=typeof e.isBatchingUpdates&&m(!1),E=e}},O={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:S,injection:P,asap:c};e.exports=O},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){"use strict";var r=n(32),o=r({bubbled:null,captured:null}),i=r({topAbort:null,topAnimationEnd:null,topAnimationIteration:null,topAnimationStart:null,topBlur:null,topCanPlay:null,topCanPlayThrough:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topInvalid:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topTransitionEnd:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:o};e.exports=a},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var u=o[i];u?this[i]=u(n):"target"===i?this.target=r:this[i]=n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue;return this.isDefaultPrevented=s?a.thatReturnsTrue:a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var o=n(3),i=n(16),a=n(9),u=(n(2),["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),s={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n<u.length;n++)this[u[n]]=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;o(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.fourArgumentPooler)},i.addPoolingTo(r,i.fourArgumentPooler),e.exports=r},function(e,t){"use strict";var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=n},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){"use strict";var r=n(1),o=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},s=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},c=function(e){var t=this;e instanceof t||r(!1),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=o,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||l,n.poolSize||(n.poolSize=10),n.release=c,n},p={addPoolingTo:f,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:u,fiveArgumentPooler:s};e.exports=p},function(e,t,n){"use strict";var r=n(3),o=n(20),i=(n(2),n(158),"function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103),a={key:!0,ref:!0,__self:!0,__source:!0},u=function(e,t,n,r,o,a,u){return{$$typeof:i,type:e,key:t,ref:n,props:u,_owner:a}};u.createElement=function(e,t,n){var r,i={},s=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,s=void 0===t.key?null:""+t.key,void 0===t.__self?null:t.__self,void 0===t.__source?null:t.__source;for(r in t)t.hasOwnProperty(r)&&!a.hasOwnProperty(r)&&(i[r]=t[r])}var l=arguments.length-2;if(1===l)i.children=n;else if(l>1){for(var f=Array(l),p=0;p<l;p++)f[p]=arguments[p+2];i.children=f}if(e&&e.defaultProps){var d=e.defaultProps;for(r in d)void 0===i[r]&&(i[r]=d[r])}return u(e,s,c,0,0,o.current,i)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceKey=function(e,t){return u(e.type,t,e.ref,e._self,e._source,e._owner,e.props)},u.cloneElement=function(e,t,n){var i,s=r({},e.props),c=e.key,l=e.ref,f=(e._self,e._source,e._owner);if(null!=t){void 0!==t.ref&&(l=t.ref,f=o.current),void 0!==t.key&&(c=""+t.key);var p;e.type&&e.type.defaultProps&&(p=e.type.defaultProps);for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(void 0===t[i]&&void 0!==p?s[i]=p[i]:s[i]=t[i])}var d=arguments.length-2;if(1===d)s.children=n;else if(d>1){for(var h=Array(d),v=0;v<d;v++)h[v]=arguments[v+2];s.children=h}return u(e.type,c,l,0,0,f,s)},u.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===i},e.exports=u},function(e,t){function n(e){return!!e&&"object"==typeof e}e.exports=n},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(1),i={MUST_USE_PROPERTY:1,HAS_SIDE_EFFECTS:2,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},s=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var f in n){u.properties.hasOwnProperty(f)&&o(!1);var p=f.toLowerCase(),d=n[f],h={attributeName:p,attributeNamespace:null,propertyName:f,mutationMethod:null,mustUseProperty:r(d,t.MUST_USE_PROPERTY),hasSideEffects:r(d,t.HAS_SIDE_EFFECTS),hasBooleanValue:r(d,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(d,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(d,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(d,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(!h.mustUseProperty&&h.hasSideEffects&&o(!1),h.hasBooleanValue+h.hasNumericValue+h.hasOverloadedBooleanValue<=1||o(!1),s.hasOwnProperty(f)){var v=s[f];h.attributeName=v}a.hasOwnProperty(f)&&(h.attributeNamespace=a[f]),c.hasOwnProperty(f)&&(h.propertyName=c[f]),l.hasOwnProperty(f)&&(h.mutationMethod=l[f]),u.properties[f]=h}}},a=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",u={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:a,ATTRIBUTE_NAME_CHAR:a+"\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){if((0,u._isCustomAttributeFunctions[t])(e))return!0}return!1},injection:i};e.exports=u},function(e,t){"use strict";var n={current:null};e.exports=n},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(334),i=(n(7),n(1)),a={mountComponent:function(e,t,n,o,i){var a=e.mountComponent(t,n,o,i);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),a},getNativeNode:function(e){return e.getNativeNode()},unmountComponent:function(e,t){o.detachRefs(e,e._currentElement),e.unmountComponent(t)},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var u=o.shouldUpdateRefs(a,t);u&&o.detachRefs(e,a),e.receiveComponent(t,n,i),u&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t,n){return e._updateBatchNumber!==n?void(null!=e._updateBatchNumber&&e._updateBatchNumber!==n+1&&i(!1)):void e.performUpdateIfNecessary(t)}};e.exports=a},function(e,t,n){function r(e,t){var n=i(e,t);return o(n)?n:void 0}var o=n(218),i=n(240);e.exports=r},function(e,t,n){"use strict";function r(e){if(d){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)h(t,n[r],null);else null!=e.html?t.innerHTML=e.html:null!=e.text&&p(t,e.text)}}function o(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function i(e,t){d?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){d?e.html=t:e.node.innerHTML=t}function u(e,t){d?e.text=t:p(e.node,t)}function s(){return this.node.nodeName}function c(e){return{node:e,children:[],html:null,text:null,toString:s}}var l=n(137),f=n(80),p=n(164),d="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),h=f(function(e,t,n){11===t.node.nodeType||1===t.node.nodeType&&"object"===t.node.nodeName.toLowerCase()&&(null==t.node.namespaceURI||t.node.namespaceURI===l.html)?(r(t),e.insertBefore(t.node,n)):(e.insertBefore(t.node,n),r(t))});c.insertTreeBefore=h,c.replaceChildWithTree=o,c.queueChild=i,c.queueHTML=a,c.queueText=u,e.exports=c},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t){function n(e,t){for(var n=-1,o=e.length,i=0,a=[];++n<o;){var u=e[n];u!==t&&u!==r||(e[n]=r,a[i++]=n)}return a}var r="__lodash_placeholder__";e.exports=n},function(e,t,n){function r(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-i?"-0":t}var o=n(27),i=1/0;e.exports=r},function(e,t,n){function r(e){return"symbol"==typeof e||o(e)&&u.call(e)==i}var o=n(18),i="[object Symbol]",a=Object.prototype,u=a.toString;e.exports=r},function(e,t,n){"use strict";var r=n(48),o=n(72),i=n(76),a=n(157),u=n(159),s=n(1),c={},l=null,f=function(e,t){e&&(o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},p=function(e){return f(e,!0)},d=function(e){return f(e,!1)},h={injection:{injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n&&s(!1),(c[t]||(c[t]={}))[e._rootNodeID]=n;var o=r.registrationNameModules[t];o&&o.didPutListener&&o.didPutListener(e,t,n)},getListener:function(e,t){var n=c[t];return n&&n[e._rootNodeID]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=c[t];o&&delete o[e._rootNodeID]},deleteAllListeners:function(e){for(var t in c)if(c[t][e._rootNodeID]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete c[t][e._rootNodeID]}},extractEvents:function(e,t,n,o){for(var i,u=r.plugins,s=0;s<u.length;s++){var c=u[s];if(c){var l=c.extractEvents(e,t,n,o);l&&(i=a(i,l))}}return i},enqueueEvents:function(e){e&&(l=a(l,e))},processEventQueue:function(e){var t=l;l=null,e?u(t,p):u(t,d),l&&s(!1),i.rethrowCaughtError()},__purge:function(){c={}},__getListenerBank:function(){return c}};e.exports=h},function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return b(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,i=r(e,n,o);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&v.traverseTwoPhase(e._targetInst,o,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?v.getParentInstance(t):null;v.traverseTwoPhase(n,o,e)}}function u(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=b(e,r);o&&(n._dispatchListeners=m(n._dispatchListeners,o),n._dispatchInstances=m(n._dispatchInstances,e))}}function s(e){e&&e.dispatchConfig.registrationName&&u(e._targetInst,null,e)}function c(e){y(e,i)}function l(e){y(e,a)}function f(e,t,n,r){v.traverseEnterLeave(n,r,u,e,t)}function p(e){y(e,s)}var d=n(12),h=n(28),v=n(72),m=n(157),y=n(159),g=(n(2),d.PropagationPhases),b=h.getListener,_={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:p,accumulateEnterLeaveDispatches:f};e.exports=_},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i=n(83),a={view:function(e){if(e.view)return e.view;var t=i(e);if(null!=t&&t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(285),i=r(o),a=n(386),u=r(a),s=n(172),c=r(s),l=n(385),f=r(l),p=n(383),d=r(p),h=n(384),v=r(h),m={empty:{},getIn:c.default,setIn:f.default,deepEqual:d.default,deleteIn:v.default,fromJS:function(e){return e},size:function(e){return e?e.length:0},some:i.default,splice:u.default};t.default=m},function(e,t,n){"use strict";var r=n(1),o=function(e){var t,n={};e instanceof Object&&!Array.isArray(e)||r(!1);for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};e.exports=o},function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,u],l=0;s=new Error(t.replace(/%s/g,function(){return c[l++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}};e.exports=r},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(253),i=n(254),a=n(255),u=n(256),s=n(257);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=u,r.prototype.set=s,e.exports=r},function(e,t,n){function r(e,t){for(var n=e.length;n--;)if(o(e[n][0],t))return n;return-1}var o=n(126);e.exports=r},function(e,t,n){function r(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=o(e.prototype),r=e.apply(n,t);return i(r)?r:n}}var o=n(59),i=n(15);e.exports=r},function(e,t){function n(e){return e.placeholder}e.exports=n},function(e,t,n){function r(e,t){var n=e.__data__;return o(t)?n["string"==typeof t?"string":"hash"]:n.map}var o=n(249);e.exports=r},function(e,t){function n(e,t){return!!(t=null==t?r:t)&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var r=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=n},function(e,t,n){function r(e,t){if(o(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!i(e))||u.test(e)||!a.test(e)||null!=t&&e in Object(t)}var o=n(11),i=n(27),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,u=/^\w*$/;e.exports=r},function(e,t,n){var r=n(22),o=r(Object,"create");e.exports=o},function(e,t,n){function r(e){return null!=e&&a(o(e))&&!i(e)}var o=n(237),i=n(64),a=n(43);e.exports=r},function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=r}var r=9007199254740991;e.exports=n},function(e,t,n){var r=n(116),o=n(37),i=n(25),a=n(131),u=a(function(e,t){var n=i(t,o(u));return r(e,32,void 0,t,n)});u.placeholder={},e.exports=u},function(e,t,n){function r(e){return a(e)?o(e,c):u(e)?[e]:i(s(e))}var o=n(212),i=n(62),a=n(11),u=n(27),s=n(124),c=n(26);e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.connect=t.Provider=void 0;var o=n(292),i=r(o),a=n(293),u=r(a);t.Provider=i.default,t.connect=u.default},function(e,t){"use strict";var n={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},r={getNativeProps:function(e,t){if(!t.disabled)return t;var r={};for(var o in t)!n[o]&&t.hasOwnProperty(o)&&(r[o]=t[o]);return r}};e.exports=r},function(e,t,n){"use strict";function r(){if(u)for(var e in s){var t=s[e],n=u.indexOf(e);if(n>-1||a(!1),!c.plugins[n]){t.extractEvents||a(!1),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)||a(!1)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)&&a(!1),c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var u=r[o];i(u,t,n)}return!0}return!!e.registrationName&&(i(e.registrationName,t,n),!0)}function i(e,t,n){c.registrationNameModules[e]&&a(!1),c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(1),u=null,s={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){u&&a(!1),u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(s[n]&&a(!1),s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=c.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=c},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=h++,p[e[m]]={}),p[e[m]]}var o,i=n(3),a=n(12),u=n(48),s=n(327),c=n(156),l=n(356),f=n(85),p={},d=!1,h=0,v={topAbort:"abort",topAnimationEnd:l("animationend")||"animationend",topAnimationIteration:l("animationiteration")||"animationiteration",topAnimationStart:l("animationstart")||"animationstart",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topTransitionEnd:l("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),y=i({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(y.handleTopLevel),y.ReactEventListener=e}},setEnabled:function(e){y.ReactEventListener&&y.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!y.ReactEventListener||!y.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,o=r(n),i=u.registrationNameDependencies[e],s=a.topLevelTypes,c=0;c<i.length;c++){var l=i[c];o.hasOwnProperty(l)&&o[l]||(l===s.topWheel?f("wheel")?y.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):f("mousewheel")?y.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):y.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):l===s.topScroll?f("scroll",!0)?y.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):y.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",y.ReactEventListener.WINDOW_HANDLE):l===s.topFocus||l===s.topBlur?(f("focus",!0)?(y.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n),y.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):f("focusin")&&(y.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),y.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),o[s.topBlur]=!0,o[s.topFocus]=!0):v.hasOwnProperty(l)&&y.ReactEventListener.trapBubbledEvent(l,v[l],n),o[l]=!0)}},trapBubbledEvent:function(e,t,n){return y.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return y.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(void 0===o&&(o=document.createEvent&&"pageX"in document.createEvent("MouseEvent")),!o&&!d){var e=c.refreshScrollValues;y.ReactEventListener.monitorScrollValue(e),d=!0}}});e.exports=y},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(30),i=n(156),a=n(82),u={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,u),e.exports=r},function(e,t,n){"use strict";var r=n(1),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,u,s){this.isInTransaction()&&r(!1);var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,n,o,i,a,u,s),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(e){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(e){}}}},closeAll:function(e){this.isInTransaction()||r(!1);for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],u=this.wrapperInitData[n];try{o=!0,u!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,u),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(e){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};e.exports=i},function(e,t){"use strict";function n(e){return o[e]}function r(e){return(""+e).replace(i,n)}var o={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(5),a=r(i),u=n(189),s=r(u),c=n(180),l=r(c),f=n(181),p=r(f),d=n(178),h=r(d),v=n(182),m=r(v),y=n(93),g=r(y),b=function(e){var t=e.children,n=e.path,r=e.version,i=e.breadcrumbs,u="/"===n,c="https://redux-form.com/"+r;return a.default.createElement("div",{className:(0,g.default)(s.default.app,o({},s.default.hasNav,!u))},!u&&a.default.createElement(p.default,{path:n,url:c}),a.default.createElement("div",{className:s.default.contentAndFooter},a.default.createElement("div",{className:s.default.topNav},a.default.createElement("a",{href:"https://redux-form.com",className:s.default.brand}),a.default.createElement("a",{className:s.default.github,href:"https://github.com/erikras/redux-form",title:"Github",target:"_blank"},a.default.createElement("i",{className:"fa fa-fw fa-github"}))),a.default.createElement("div",{className:(0,g.default)(s.default.content,o({},s.default.home,u))},u?a.default.createElement(l.default,{version:r}):a.default.createElement("div",null,a.default.createElement(h.default,{items:i}),t)),a.default.createElement("div",{className:s.default.footer},a.default.createElement("div",null,"Created by Erik Rasmussen"),a.default.createElement("div",null,"Got questions? Ask for help:",a.default.createElement("a",{className:s.default.help,href:"https://stackoverflow.com/questions/ask?tags=redux-form",title:"Stack Overflow",target:"_blank"},a.default.createElement("i",{className:"fa fa-fw fa-stack-overflow"})),a.default.createElement("a",{className:s.default.help,href:"https://github.com/erikras/redux-form/issues/new",title:"Github",target:"_blank"},a.default.createElement("i",{className:"fa fa-fw fa-github"}))),a.default.createElement("div",null,a.default.createElement(m.default,{username:"erikras",showUsername:!0,large:!0}),a.default.createElement(m.default,{username:"ReduxForm",showUsername:!0,large:!0})))))};t.default=b},function(e,t){"use strict";function n(e,t){return e===t?0!==e||1/e==1/t:e!==e&&t!==t}function r(e,t){if(n(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var a=0;a<r.length;a++)if(!o.call(t,r[a])||!n(e[r[a]],t[r[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=n},function(e,t,n){function r(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=a,this.__views__=[]}var o=n(59),i=n(61),a=4294967295;r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(258),i=n(259),a=n(260),u=n(261),s=n(262);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=u,r.prototype.set=s,e.exports=r},function(e,t){function n(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}e.exports=n},function(e,t,n){function r(e){return o(e)?i(e):{}}var o=n(15),i=Object.create;e.exports=r},function(e,t,n){function r(e,t,n,u,s){return e===t||(null==e||null==t||!i(e)&&!a(t)?e!==e&&t!==t:o(e,t,r,n,u,s))}var o=n(216),i=n(15),a=n(18);e.exports=r},function(e,t){function n(){}e.exports=n},function(e,t){function n(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}e.exports=n},function(e,t){function n(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}e.exports=n},function(e,t,n){function r(e){var t=o(e)?s.call(e):"";return t==i||t==a}var o=n(15),i="[object Function]",a="[object GeneratorFunction]",u=Object.prototype,s=u.toString;e.exports=r},function(e,t,n){function r(e){if(!a(e)||p.call(e)!=u||i(e))return!1;var t=o(e);if(null===t)return!0;var n=l.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==f}var o=n(119),i=n(63),a=n(18),u="[object Object]",s=Object.prototype,c=Function.prototype.toString,l=s.hasOwnProperty,f=c.call(Object),p=s.toString;e.exports=r},function(e,t,n){function r(e){var t=c(e);if(!t&&!u(e))return i(e);var n=a(e),r=!!n,l=n||[],f=l.length;for(var p in e)!o(e,p)||r&&("length"==p||s(p,f))||t&&"constructor"==p||l.push(p);return l}var o=n(107),i=n(219),a=n(247),u=n(42),s=n(39),c=n(252);e.exports=r},function(e,t,n){function r(e,t){var n={};return t=i(t,3),o(e,function(e,r,o){n[r]=t(e,r,o)}),n}var o=n(105),i=n(108);e.exports=r},function(e,t,n){(function(t){(function(){function t(e){this.tokens=[],this.tokens.links={},this.options=e||l.defaults,this.rules=f.normal,this.options.gfm&&(this.options.tables?this.rules=f.tables:this.rules=f.gfm)}function n(e,t){if(this.options=t||l.defaults,this.links=e,this.rules=p.normal,this.renderer=this.options.renderer||new r,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.gfm?this.options.breaks?this.rules=p.breaks:this.rules=p.gfm:this.options.pedantic&&(this.rules=p.pedantic)}function r(e){this.options=e||{}}function o(e){this.tokens=[],this.token=null,this.options=e||l.defaults,this.options.renderer=this.options.renderer||new r,this.renderer=this.options.renderer,this.renderer.options=this.options}function i(e,t){return e.replace(t?/&/g:/&(?!#?\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function a(e){return e.replace(/&([#\w]+);/g,function(e,t){return t=t.toLowerCase(),"colon"===t?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""})}function u(e,t){return e=e.source,t=t||"",function n(r,o){return r?(o=o.source||o,o=o.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,o),n):new RegExp(e,t)}}function s(){}function c(e){for(var t,n,r=1;r<arguments.length;r++){t=arguments[r];for(n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}function l(e,n,r){if(r||"function"==typeof n){r||(r=n,n=null),n=c({},l.defaults,n||{});var a,u,s=n.highlight,f=0;try{a=t.lex(e,n)}catch(e){return r(e)}u=a.length;var p=function(e){if(e)return n.highlight=s,r(e);var t;try{t=o.parse(a,n)}catch(t){e=t}return n.highlight=s,e?r(e):r(null,t)};if(!s||s.length<3)return p();if(delete n.highlight,!u)return p();for(;f<a.length;f++)!function(e){"code"!==e.type?--u||p():s(e.text,e.lang,function(t,n){return t?p(t):null==n||n===e.text?--u||p():(e.text=n,e.escaped=!0,void(--u||p()))})}(a[f])}else try{return n&&(n=c({},l.defaults,n)),o.parse(t.lex(e,n),n)}catch(e){if(e.message+="\nPlease report this to https://github.com/chjj/marked.",(n||l.defaults).silent)return"<p>An error occured:</p><pre>"+i(e.message+"",!0)+"</pre>";throw e}}var f={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:s,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:s,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:s,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};f.bullet=/(?:[*+-]|\d+\.)/,f.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,f.item=u(f.item,"gm")(/bull/g,f.bullet)(),f.list=u(f.list)(/bull/g,f.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+f.def.source+")")(),f.blockquote=u(f.blockquote)("def",f.def)(),f._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b",f.html=u(f.html)("comment",/<!--[\s\S]*?-->/)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g,f._tag)(),f.paragraph=u(f.paragraph)("hr",f.hr)("heading",f.heading)("lheading",f.lheading)("blockquote",f.blockquote)("tag","<"+f._tag)("def",f.def)(),f.normal=c({},f),f.gfm=c({},f.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),f.gfm.paragraph=u(f.paragraph)("(?!","(?!"+f.gfm.fences.source.replace("\\1","\\2")+"|"+f.list.source.replace("\\1","\\3")+"|")(),f.tables=c({},f.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/}),t.rules=f,t.lex=function(e,n){return new t(n).lex(e)},t.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},t.prototype.token=function(e,t,n){for(var r,o,i,a,u,s,c,l,p,e=e.replace(/^ +$/gm,"");e;)if((i=this.rules.newline.exec(e))&&(e=e.substring(i[0].length),i[0].length>1&&this.tokens.push({type:"space"})),i=this.rules.code.exec(e))e=e.substring(i[0].length),i=i[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?i:i.replace(/\n+$/,"")});else if(i=this.rules.fences.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"code",lang:i[2],text:i[3]||""});else if(i=this.rules.heading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:i[1].length,text:i[2]});else if(t&&(i=this.rules.nptable.exec(e))){for(e=e.substring(i[0].length),s={type:"table",header:i[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3].replace(/\n$/,"").split("\n")},l=0;l<s.align.length;l++)/^ *-+: *$/.test(s.align[l])?s.align[l]="right":/^ *:-+: *$/.test(s.align[l])?s.align[l]="center":/^ *:-+ *$/.test(s.align[l])?s.align[l]="left":s.align[l]=null;for(l=0;l<s.cells.length;l++)s.cells[l]=s.cells[l].split(/ *\| */);this.tokens.push(s)}else if(i=this.rules.lheading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:"="===i[2]?1:2,text:i[1]});else if(i=this.rules.hr.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"hr"});else if(i=this.rules.blockquote.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"blockquote_start"}),i=i[0].replace(/^ *> ?/gm,""),this.token(i,t,!0),this.tokens.push({type:"blockquote_end"});else if(i=this.rules.list.exec(e)){for(e=e.substring(i[0].length),a=i[2],this.tokens.push({type:"list_start",ordered:a.length>1}),i=i[0].match(this.rules.item),r=!1,p=i.length,l=0;l<p;l++)s=i[l],c=s.length,s=s.replace(/^ *([*+-]|\d+\.) +/,""),~s.indexOf("\n ")&&(c-=s.length,s=this.options.pedantic?s.replace(/^ {1,4}/gm,""):s.replace(new RegExp("^ {1,"+c+"}","gm"),"")),this.options.smartLists&&l!==p-1&&(u=f.bullet.exec(i[l+1])[0],a===u||a.length>1&&u.length>1||(e=i.slice(l+1).join("\n")+e,l=p-1)),o=r||/\n\n(?!\s*$)/.test(s),l!==p-1&&(r="\n"===s.charAt(s.length-1),o||(o=r)),this.tokens.push({type:o?"loose_item_start":"list_item_start"}),this.token(s,!1,n),this.tokens.push({type:"list_item_end"});this.tokens.push({type:"list_end"})}else if(i=this.rules.html.exec(e))e=e.substring(i[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&("pre"===i[1]||"script"===i[1]||"style"===i[1]),text:i[0]});else if(!n&&t&&(i=this.rules.def.exec(e)))e=e.substring(i[0].length),this.tokens.links[i[1].toLowerCase()]={href:i[2],title:i[3]};else if(t&&(i=this.rules.table.exec(e))){for(e=e.substring(i[0].length),s={type:"table",header:i[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3].replace(/(?: *\| *)?\n$/,"").split("\n")},l=0;l<s.align.length;l++)/^ *-+: *$/.test(s.align[l])?s.align[l]="right":/^ *:-+: *$/.test(s.align[l])?s.align[l]="center":/^ *:-+ *$/.test(s.align[l])?s.align[l]="left":s.align[l]=null;for(l=0;l<s.cells.length;l++)s.cells[l]=s.cells[l].replace(/^ *\| *| *\| *$/g,"").split(/ *\| */);this.tokens.push(s)}else if(t&&(i=this.rules.paragraph.exec(e)))e=e.substring(i[0].length),this.tokens.push({type:"paragraph",text:"\n"===i[1].charAt(i[1].length-1)?i[1].slice(0,-1):i[1]});else if(i=this.rules.text.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"text",text:i[0]});else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0));return this.tokens};var p={escape:/^\\([\\`*{}\[\]()#+\-.!_>])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:s,tag:/^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:s,text:/^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/};p._inside=/(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/,p._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/,p.link=u(p.link)("inside",p._inside)("href",p._href)(),p.reflink=u(p.reflink)("inside",p._inside)(),p.normal=c({},p),p.pedantic=c({},p.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),p.gfm=c({},p.normal,{escape:u(p.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:u(p.text)("]|","~]|")("|","|https?://|")()}),p.breaks=c({},p.gfm,{br:u(p.br)("{2,}","*")(),text:u(p.gfm.text)("{2,}","*")()}),n.rules=p,n.output=function(e,t,r){return new n(t,r).output(e)},n.prototype.output=function(e){for(var t,n,r,o,a="";e;)if(o=this.rules.escape.exec(e))e=e.substring(o[0].length),a+=o[1];else if(o=this.rules.autolink.exec(e))e=e.substring(o[0].length),"@"===o[2]?(n=":"===o[1].charAt(6)?this.mangle(o[1].substring(7)):this.mangle(o[1]),r=this.mangle("mailto:")+n):(n=i(o[1]),r=n),a+=this.renderer.link(r,null,n);else if(this.inLink||!(o=this.rules.url.exec(e))){if(o=this.rules.tag.exec(e))!this.inLink&&/^<a /i.test(o[0])?this.inLink=!0:this.inLink&&/^<\/a>/i.test(o[0])&&(this.inLink=!1),e=e.substring(o[0].length),a+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(o[0]):i(o[0]):o[0];else if(o=this.rules.link.exec(e))e=e.substring(o[0].length),this.inLink=!0,a+=this.outputLink(o,{href:o[2],title:o[3]}),this.inLink=!1;else if((o=this.rules.reflink.exec(e))||(o=this.rules.nolink.exec(e))){if(e=e.substring(o[0].length),t=(o[2]||o[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){a+=o[0].charAt(0),e=o[0].substring(1)+e;continue}this.inLink=!0,a+=this.outputLink(o,t),this.inLink=!1}else if(o=this.rules.strong.exec(e))e=e.substring(o[0].length),a+=this.renderer.strong(this.output(o[2]||o[1]));else if(o=this.rules.em.exec(e))e=e.substring(o[0].length),a+=this.renderer.em(this.output(o[2]||o[1]));else if(o=this.rules.code.exec(e))e=e.substring(o[0].length),a+=this.renderer.codespan(i(o[2],!0));else if(o=this.rules.br.exec(e))e=e.substring(o[0].length),a+=this.renderer.br();else if(o=this.rules.del.exec(e))e=e.substring(o[0].length),a+=this.renderer.del(this.output(o[1]));else if(o=this.rules.text.exec(e))e=e.substring(o[0].length),a+=this.renderer.text(i(this.smartypants(o[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else e=e.substring(o[0].length),n=i(o[1]),r=n,a+=this.renderer.link(r,null,n);return a},n.prototype.outputLink=function(e,t){var n=i(t.href),r=t.title?i(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,i(e[1]))},n.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014\/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014\/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},n.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",r=e.length,o=0;o<r;o++)t=e.charCodeAt(o),Math.random()>.5&&(t="x"+t.toString(16)),n+="&#"+t+";";return n},r.prototype.code=function(e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);null!=r&&r!==e&&(n=!0,e=r)}return t?'<pre><code class="'+this.options.langPrefix+i(t,!0)+'">'+(n?e:i(e,!0))+"\n</code></pre>\n":"<pre><code>"+(n?e:i(e,!0))+"\n</code></pre>"},r.prototype.blockquote=function(e){return"<blockquote>\n"+e+"</blockquote>\n"},r.prototype.html=function(e){return e},r.prototype.heading=function(e,t,n){return"<h"+t+' id="'+this.options.headerPrefix+n.toLowerCase().replace(/[^\w]+/g,"-")+'">'+e+"</h"+t+">\n"},r.prototype.hr=function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"},r.prototype.list=function(e,t){var n=t?"ol":"ul";return"<"+n+">\n"+e+"</"+n+">\n"},r.prototype.listitem=function(e){return"<li>"+e+"</li>\n"},r.prototype.paragraph=function(e){return"<p>"+e+"</p>\n"},r.prototype.table=function(e,t){return"<table>\n<thead>\n"+e+"</thead>\n<tbody>\n"+t+"</tbody>\n</table>\n"},r.prototype.tablerow=function(e){return"<tr>\n"+e+"</tr>\n"},r.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' style="text-align:'+t.align+'">':"<"+n+">")+e+"</"+n+">\n"},r.prototype.strong=function(e){return"<strong>"+e+"</strong>"},r.prototype.em=function(e){return"<em>"+e+"</em>"},r.prototype.codespan=function(e){return"<code>"+e+"</code>"},r.prototype.br=function(){return this.options.xhtml?"<br/>":"<br>"},r.prototype.del=function(e){return"<del>"+e+"</del>"},r.prototype.link=function(e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(a(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(0===r.indexOf("javascript:")||0===r.indexOf("vbscript:"))return""}var o='<a href="'+e+'"';return t&&(o+=' title="'+t+'"'),o+=">"+n+"</a>"},r.prototype.image=function(e,t,n){var r='<img src="'+e+'" alt="'+n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>":">"},r.prototype.text=function(e){return e},o.parse=function(e,t,n){return new o(t,n).parse(e)},o.prototype.parse=function(e){this.inline=new n(e.links,this.options,this.renderer),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},o.prototype.next=function(){return this.token=this.tokens.pop()},o.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},o.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},o.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,o="",i="";for(n="",e=0;e<this.token.header.length;e++)({header:!0,align:this.token.align[e]}),n+=this.renderer.tablecell(this.inline.output(this.token.header[e]),{header:!0,align:this.token.align[e]});for(o+=this.renderer.tablerow(n),e=0;e<this.token.cells.length;e++){for(t=this.token.cells[e],n="",r=0;r<t.length;r++)n+=this.renderer.tablecell(this.inline.output(t[r]),{header:!1,align:this.token.align[r]});i+=this.renderer.tablerow(n)}return this.renderer.table(o,i);case"blockquote_start":for(var i="";"blockquote_end"!==this.next().type;)i+=this.tok();return this.renderer.blockquote(i);case"list_start":for(var i="",a=this.token.ordered;"list_end"!==this.next().type;)i+=this.tok();return this.renderer.list(i,a);case"list_item_start":for(var i="";"list_item_end"!==this.next().type;)i+="text"===this.token.type?this.parseText():this.tok();return this.renderer.listitem(i);case"loose_item_start":for(var i="";"list_item_end"!==this.next().type;)i+=this.tok();return this.renderer.listitem(i);case"html":var u=this.token.pre||this.options.pedantic?this.token.text:this.inline.output(this.token.text);return this.renderer.html(u);case"paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case"text":return this.renderer.paragraph(this.parseText())}},s.exec=s,l.options=l.setOptions=function(e){return c(l.defaults,e),l},l.defaults={gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new r,xhtml:!1},l.Parser=o,l.parser=o.parse,l.Renderer=r,l.Lexer=t,l.lexer=t.lex,l.InlineLexer=n,l.inlineLexer=n.output,l.parse=l,e.exports=l}).call(function(){return this||("undefined"!=typeof window?window:t)}())}).call(t,function(){return this}())},function(e,t,n){e.exports=n(359)},function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){l.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?u(e,t[0],t[1],n):m(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],s(e,t,n),e.removeChild(n)}e.removeChild(t)}function u(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(m(e,o,r),o===n)break;o=i}}function s(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function c(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&m(r,document.createTextNode(n),o):n?(v(o,n),s(r,o,t)):s(r,e,t)}var l=n(23),f=n(300),p=n(149),d=(n(4),n(7),n(80)),h=n(86),v=n(164),m=d(function(e,t,n){e.insertBefore(t,n)}),y=f.dangerouslyReplaceNodeWithMarkup,g={dangerouslyReplaceNodeWithMarkup:y,replaceDelimitedText:c,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var u=t[n];switch(u.type){case p.INSERT_MARKUP:o(e,u.content,r(e,u.afterNode));break;case p.MOVE_EXISTING:i(e,u.fromNode,r(e,u.afterNode));break;case p.SET_MARKUP:h(e,u.content);break;case p.TEXT_CONTENT:v(e,u.content);break;case p.REMOVE_NODE:a(e,u.fromNode)}}}};e.exports=g},function(e,t,n){"use strict";function r(e){return!!c.hasOwnProperty(e)||!s.hasOwnProperty(e)&&(u.test(e)?(c[e]=!0,!0):(s[e]=!0,!1))}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&!1===t}var i=n(19),a=(n(4),n(318),n(7),n(357)),u=(n(2),new RegExp("^["+i.ATTRIBUTE_NAME_START_CHAR+"]["+i.ATTRIBUTE_NAME_CHAR+"]*$")),s={},c={},l={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return i.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(i.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&!0===t?r+'=""':r+"="+a(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+a(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+a(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else{if(o(r,n))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty){var u=r.propertyName;r.hasSideEffects&&""+e[u]==""+n||(e[u]=n)}else{var s=r.attributeName,c=r.attributeNamespace;c?e.setAttributeNS(c,s,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&!0===n?e.setAttribute(s,""):e.setAttribute(s,""+n)}}}else if(i.isCustomAttribute(t))return void l.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){r(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:n.hasSideEffects&&""+e[o]==""||(e[o]="")}else e.removeAttribute(n.attributeName)}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};e.exports=l},function(e,t,n){"use strict";function r(e){return e===g.topMouseUp||e===g.topTouchEnd||e===g.topTouchCancel}function o(e){return e===g.topMouseMove||e===g.topTouchMove}function i(e){return e===g.topMouseDown||e===g.topTouchStart}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=b.getNodeFromInstance(r),t?v.invokeGuardedCallbackWithCatch(o,n,e):v.invokeGuardedCallback(o,n,e),e.currentTarget=null}function u(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function s(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=s(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)&&m(!1),e.currentTarget=t?b.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function f(e){return!!e._dispatchListeners}var p,d,h=n(12),v=n(76),m=n(1),y=(n(2),{injectComponentTree:function(e){p=e},injectTreeTraversal:function(e){d=e}}),g=h.topLevelTypes,b={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:l,executeDispatchesInOrder:u,executeDispatchesInOrderStopAtTrue:c,hasDispatches:f,getInstanceFromNode:function(e){return p.getInstanceFromNode(e)},getNodeFromInstance:function(e){return p.getNodeFromInstance(e)},isAncestor:function(e,t){return d.isAncestor(e,t)},getLowestCommonAncestor:function(e,t){return d.getLowestCommonAncestor(e,t)},getParentInstance:function(e){return d.getParentInstance(e)},traverseTwoPhase:function(e,t,n){return d.traverseTwoPhase(e,t,n)},traverseEnterLeave:function(e,t,n,r,o){return d.traverseEnterLeave(e,t,n,r,o)},injection:y};e.exports=b},function(e,t){"use strict";function n(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,function(e){return t[e]})}function r(e){var t={"=0":"=","=2":":"};return(""+("."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1))).replace(/(=0|=2)/g,function(e){return t[e]})}var o={escape:n,unescape:r};e.exports=o},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink&&c(!1)}function o(e){r(e),(null!=e.value||null!=e.onChange)&&c(!1)}function i(e){r(e),(null!=e.checked||null!=e.onChange)&&c(!1)}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var u=n(332),s=n(79),c=n(1),l=(n(2),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),f={value:function(e,t,n){return!e[t]||l[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:u.func},p={},d={checkPropTypes:function(e,t,n){for(var r in f){if(f.hasOwnProperty(r))var o=f[r](t,r,e,s.prop);o instanceof Error&&!(o.message in p)&&(p[o.message]=!0,a(n))}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=d},function(e,t,n){"use strict";var r=n(1),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o&&r(!1),i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkup=e.replaceNodeWithMarkup,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n,r){try{return t(n,r)}catch(e){return void(null===o&&(o=e))}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};e.exports=i},function(e,t){"use strict";var n={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=n},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";var r=n(32),o=r({prop:null,context:null,childContext:null});e.exports=o},function(e,t){"use strict";var n=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e};e.exports=n},function(e,t){"use strict";function n(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,t>=32||13===t?t:0}e.exports=n},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return!!r&&!!n[r]}function r(e){return n}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=r},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t,n){"use strict";function r(e){return"function"==typeof e&&void 0!==e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e){var t;if(null===e||!1===e)t=u.create(o);else if("object"==typeof e){var n=e;(!n||"function"!=typeof n.type&&"string"!=typeof n.type)&&c(!1),t="string"==typeof n.type?s.createInternalComponent(n):r(n.type)?new n.type(n):new l(n)}else"string"==typeof e||"number"==typeof e?t=s.createInstanceForText(e):c(!1);return t._mountIndex=0,t._mountImage=null,t}var i=n(3),a=n(309),u=n(144),s=n(150),c=(n(7),n(1)),l=(n(2),function(e){this.construct(e)});i(l.prototype,a.Mixin,{_instantiateReactComponent:o}),e.exports=o},function(e,t,n){"use strict";/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(6);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&!0!==document.implementation.hasFeature("","")),e.exports=r},function(e,t,n){"use strict";var r=n(6),o=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=n(80),u=a(function(e,t){e.innerHTML=t});if(r.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(u=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),s=null}e.exports=u},function(e,t){"use strict";function n(e,t){var n=null===e||!1===e,r=null===t||!1===t;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=n},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||a.isValidElement(e))return n(i,e,""===t?l+r(e,0):t),1;var d,h,v=0,m=""===t?l:t+f;if(Array.isArray(e))for(var y=0;y<e.length;y++)d=e[y],h=m+r(d,y),v+=o(d,h,n,i);else{var g=u(e);if(g){var b,_=g.call(e);if(g!==e.entries)for(var E=0;!(b=_.next()).done;)d=b.value,h=m+r(d,E++),v+=o(d,h,n,i);else for(;!(b=_.next()).done;){var w=b.value;w&&(d=w[1],h=m+c.escape(w[0])+f+r(d,0),v+=o(d,h,n,i))}}else"object"===p&&(String(e),s(!1))}return v}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=(n(20),n(17)),u=n(160),s=n(1),c=n(73),l=(n(2),"."),f=":";e.exports=i},function(e,t,n){"use strict";var r=(n(3),n(9)),o=(n(2),r);e.exports=o},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ARRAY_INSERT="redux-form/ARRAY_INSERT",t.ARRAY_POP="redux-form/ARRAY_POP",t.ARRAY_PUSH="redux-form/ARRAY_PUSH",t.ARRAY_REMOVE="redux-form/ARRAY_REMOVE",t.ARRAY_SHIFT="redux-form/ARRAY_SHIFT",t.ARRAY_SPLICE="redux-form/ARRAY_SPLICE",t.ARRAY_UNSHIFT="redux-form/ARRAY_UNSHIFT",t.ARRAY_SWAP="redux-form/ARRAY_SWAP",t.BLUR="redux-form/BLUR",t.CHANGE="redux-form/CHANGE",t.DESTROY="redux-form/DESTROY",t.FOCUS="redux-form/FOCUS",t.INITIALIZE="redux-form/INITIALIZE",t.REGISTER_FIELD="redux-form/REGISTER_FIELD",t.RESET="redux-form/RESET",t.SET_SUBMIT_FAILED="redux-form/SET_SUBMIT_FAILED",t.START_ASYNC_VALIDATION="redux-form/START_ASYNC_VALIDATION",t.START_SUBMIT="redux-form/START_SUBMIT",t.STOP_ASYNC_VALIDATION="redux-form/STOP_ASYNC_VALIDATION",t.STOP_SUBMIT="redux-form/STOP_SUBMIT",t.TOUCH="redux-form/TOUCH",t.UNREGISTER_FIELD="redux-form/UNREGISTER_FIELD",t.UNTOUCH="redux-form/UNTOUCH"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(92),u=r(a),s=function(e){var t=e.source,n=e.language;return i.default.createElement(u.default,{content:"```"+n+t+"```"})};s.defaultProps={language:"js"},t.default=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(68),u=r(a),s=n(187),c=r(s),l=function(e){return e.replace(/```(?:javascript|js)([\s\S]+?)```/g,function(e,t){return'<pre class="language-jsx"><code class="language-jsx">'+c.default.highlight(t,c.default.languages.jsx)+"</code></pre>"})},f=function(e){var t=e.content;return i.default.createElement("div",{dangerouslySetInnerHTML:{__html:(0,u.default)(l(t))}})};t.default=f},function(e,t,n){var r,o;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;void 0!==e&&e.exports?e.exports=n:(r=[],void 0!==(o=function(){return n}.apply(t,r))&&(e.exports=o))}()},function(e,t,n){"use strict";var r=n(9),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e,t){"use strict";function n(e){try{e.focus()}catch(e){}}e.exports=n},function(e,t){"use strict";function n(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=n},function(e,t,n){"use strict";function r(e){return a||i(!1),p.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||(a.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",u[e]=!a.firstChild),u[e]?p[e]:null}var o=n(6),i=n(1),a=o.canUseDOM?document.createElement("div"):null,u={},s=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],l=[3,"<table><tbody><tr>","</tr></tbody></table>"],f=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l};["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"].forEach(function(e){p[e]=f,u[e]=!0}),e.exports=r},function(e,t){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},r={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,i){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var u=0;u<a.length;++u)if(!(n[a[u]]||r[a[u]]||i&&i[a[u]]))try{e[a[u]]=t[a[u]]}catch(e){}}return e}},function(e,t,n){function r(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}var o=n(59),i=n(61);r.prototype=o(i.prototype),r.prototype.constructor=r,e.exports=r},function(e,t,n){var r=n(22),o=n(8),i=r(o,"Map");e.exports=i},function(e,t,n){function r(e){this.__data__=new o(e)}var o=n(34),i=n(270),a=n(271),u=n(272),s=n(273),c=n(274);r.prototype.clear=i,r.prototype.delete=a,r.prototype.get=u,r.prototype.has=s,r.prototype.set=c,e.exports=r},function(e,t,n){var r=n(8),o=r.Symbol;e.exports=o},function(e,t,n){var r=n(22),o=n(8),i=r(o,"WeakMap");e.exports=i},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=n},function(e,t,n){function r(e,t){return e&&o(e,t,i)}var o=n(214),i=n(66);e.exports=r},function(e,t,n){function r(e,t){t=i(t,e)?[t]:o(t);for(var n=0,r=t.length;null!=e&&n<r;)e=e[a(t[n++])];return n&&n==r?e:void 0}var o=n(111),i=n(40),a=n(26);e.exports=r},function(e,t,n){function r(e,t){return null!=e&&(a.call(e,t)||"object"==typeof e&&t in e&&null===o(e))}var o=n(119),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){return"function"==typeof e?e:null==e?a:"object"==typeof e?u(e)?i(e[0],e[1]):o(e):s(e)}var o=n(220),i=n(221),a=n(127),u=n(11),s=n(284);e.exports=r},function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}e.exports=n},function(e,t,n){var r=n(127),o=n(122),i=o?function(e,t){return o.set(e,t),e}:r;e.exports=i},function(e,t,n){function r(e){return o(e)?e:i(e)}var o=n(11),i=n(124);e.exports=r},function(e,t){function n(e,t,n,o){for(var i=-1,a=e.length,u=n.length,s=-1,c=t.length,l=r(a-u,0),f=Array(c+l),p=!o;++s<c;)f[s]=t[s];for(;++i<u;)(p||i<a)&&(f[n[i]]=e[i]);for(;l--;)f[s++]=e[i++];return f}var r=Math.max;e.exports=n},function(e,t){function n(e,t,n,o){for(var i=-1,a=e.length,u=-1,s=n.length,c=-1,l=t.length,f=r(a-s,0),p=Array(f+l),d=!o;++i<f;)p[i]=e[i];for(var h=i;++c<l;)p[h+c]=t[c];for(;++u<s;)(d||i<a)&&(p[h+n[u]]=e[i++]);return p}var r=Math.max;e.exports=n},function(e,t,n){function r(e,t,n,b,_,E,w,x,C,S){function P(){for(var d=arguments.length,h=Array(d),v=d;v--;)h[v]=arguments[v];if(A)var m=c(P),y=a(h,m);if(b&&(h=o(h,b,_,A)),E&&(h=i(h,E,w,A)),d-=y,A&&d<S){var g=f(h,m);return s(e,t,r,P.placeholder,n,h,g,x,C,S-d)}var N=T?n:this,M=k?N[e]:e;return d=h.length,x?h=l(h,x):R&&d>1&&h.reverse(),O&&C<d&&(h.length=C),this&&this!==p&&this instanceof P&&(M=I||u(M)),M.apply(N,h)}var O=t&y,T=t&d,k=t&h,A=t&(v|m),R=t&g,I=k?void 0:u(e);return P}var o=n(112),i=n(113),a=n(228),u=n(36),s=n(115),c=n(37),l=n(266),f=n(25),p=n(8),d=1,h=2,v=8,m=16,y=128,g=512;e.exports=r},function(e,t,n){function r(e,t,n,r,p,d,h,v,m,y){var g=t&c,b=g?h:void 0,_=g?void 0:h,E=g?d:void 0,w=g?void 0:d;t|=g?l:f,(t&=~(g?f:l))&s||(t&=~(a|u));var x=[e,t,p,E,b,w,_,v,m,y],C=n.apply(void 0,x);return o(e)&&i(C,x),C.placeholder=r,C}var o=n(250),i=n(123),a=1,u=2,s=4,c=8,l=32,f=64;e.exports=r},function(e,t,n){function r(e,t,n,r,E,w,x,C){var S=t&v;if(!S&&"function"!=typeof e)throw new TypeError(d);var P=r?r.length:0;if(P||(t&=~(g|b),r=E=void 0),x=void 0===x?x:_(p(x),0),C=void 0===C?C:p(C),P-=E?E.length:0,t&b){var O=r,T=E;r=E=void 0}var k=S?void 0:c(e),A=[e,t,n,r,E,O,T,w,x,C];if(k&&l(A,k),e=A[0],t=A[1],n=A[2],r=A[3],E=A[4],C=A[9]=null==A[9]?S?0:e.length:_(A[9]-P,0),!C&&t&(m|y)&&(t&=~(m|y)),t&&t!=h)R=t==m||t==y?a(e,t,C):t!=g&&t!=(h|g)||E.length?u.apply(void 0,A):s(e,t,n,r);else var R=i(e,t,n);return(k?o:f)(R,A)}var o=n(110),i=n(231),a=n(232),u=n(114),s=n(233),c=n(118),l=n(264),f=n(123),p=n(132),d="Expected a function",h=1,v=2,m=8,y=16,g=32,b=64,_=Math.max;e.exports=r},function(e,t,n){function r(e,t,n,r,s,c){var l=s&u,f=e.length,p=t.length;if(f!=p&&!(l&&p>f))return!1;var d=c.get(e);if(d)return d==t;var h=-1,v=!0,m=s&a?new o:void 0;for(c.set(e,t);++h<f;){var y=e[h],g=t[h];if(r)var b=l?r(g,y,h,t,e,c):r(y,g,h,e,t,c);if(void 0!==b){if(b)continue;v=!1;break}if(m){if(!i(t,function(e,t){if(!m.has(t)&&(y===e||n(y,e,r,s,c)))return m.add(t)})){v=!1;break}}else if(y!==g&&!n(y,g,r,s,c)){v=!1;break}}return c.delete(e),v}var o=n(210),i=n(104),a=1,u=2;e.exports=r},function(e,t,n){var r=n(122),o=n(130),i=r?function(e){return r.get(e)}:o;e.exports=i},function(e,t){function n(e){return r(Object(e))}var r=Object.getPrototypeOf;e.exports=n},function(e,t,n){function r(e){return e===e&&!o(e)}var o=n(15);e.exports=r},function(e,t){function n(e,t){return function(n){return null!=n&&n[e]===t&&(void 0!==t||e in Object(n))}}e.exports=n},function(e,t,n){var r=n(103),o=r&&new r;e.exports=o},function(e,t,n){var r=n(110),o=n(282),i=function(){var e=0,t=0;return function(n,i){var a=o(),u=16-(a-t);if(t=a,u>0){if(++e>=150)return n}else e=0;return r(n,i)}}();e.exports=i},function(e,t,n){var r=n(281),o=n(288),i=r(function(e){var t=[];return o(e).replace(/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(\.|\[\])(?:\4|$))/g,function(e,n,r,o){t.push(r?o.replace(/\\(\\)?/g,"$1"):n||e)}),t});e.exports=i},function(e,t){function n(e){if(null!=e){try{return r.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var r=Function.prototype.toString;e.exports=n},function(e,t){function n(e,t){return e===t||e!==e&&t!==t}e.exports=n},function(e,t){function n(e){return e}e.exports=n},function(e,t,n){function r(e){return o(e)&&u.call(e,"callee")&&(!c.call(e,"callee")||s.call(e)==i)}var o=n(278),i="[object Arguments]",a=Object.prototype,u=a.hasOwnProperty,s=a.toString,c=a.propertyIsEnumerable;e.exports=r},function(e,t,n){function r(e){return"string"==typeof e||!o(e)&&i(e)&&s.call(e)==a}var o=n(11),i=n(18),a="[object String]",u=Object.prototype,s=u.toString;e.exports=r},function(e,t){function n(){}e.exports=n},function(e,t,n){function r(e,t){if("function"!=typeof e)throw new TypeError(a);return t=u(void 0===t?e.length-1:i(t),0),function(){for(var n=arguments,r=-1,i=u(n.length-t,0),a=Array(i);++r<i;)a[r]=n[t+r];switch(t){case 0:return e.call(this,a);case 1:return e.call(this,n[0],a);case 2:return e.call(this,n[0],n[1],a)}var s=Array(t+1);for(r=-1;++r<t;)s[r]=n[r];return s[t]=a,o(e,this,s)}}var o=n(58),i=n(132),a="Expected a function",u=Math.max;e.exports=r},function(e,t,n){function r(e){var t=o(e),n=t%1;return t===t?n?t-n:t:0}var o=n(286);e.exports=r},function(e,t,n){"use strict";t.__esModule=!0;var r=n(5);t.default=r.PropTypes.shape({subscribe:r.PropTypes.func.isRequired,dispatch:r.PropTypes.func.isRequired,getState:r.PropTypes.func.isRequired})},function(e,t){"use strict";function n(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}t.__esModule=!0,t.default=n},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};e.exports=a},function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=n(3),i=n(16),a=n(1);o(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){e.length!==t.length&&a(!1),this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},checkpoint:function(){return this._callbacks?this._callbacks.length:0},rollback:function(e){this._callbacks&&(this._callbacks.length=e,this._contexts.length=e)},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),i.addPoolingTo(r),e.exports=r},function(e,t){"use strict";var n={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};e.exports=n},function(e,t,n){"use strict";var r=n(70),o=n(316),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,unmountIDFromEnvironment:function(e){}};e.exports=i},function(e,t){"use strict";var n={hasCachedChildNodes:1};e.exports=n},function(e,t,n){"use strict";function r(e,t){return{_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===o?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null}}var o=(n(89),9);e.exports=r},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=s.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=c.getNodeFromInstance(e).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),l.asap(r,this),n}var a=n(3),u=n(47),s=n(74),c=n(4),l=n(10),f=(n(2),!1),p={getNativeProps:function(e,t){return a({},u.getNativeProps(e,t),{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=s.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,listeners:null,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)},void 0===t.value||void 0===t.defaultValue||f||(f=!0)},getSelectValueContext:function(e){return e._wrapperState.initialValue},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=s.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=p},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(3),i=n(10),a=n(51),u=n(9),s={initialize:u,close:function(){p.isBatchingUpdates=!1}},c={initialize:u,close:i.flushBatchedUpdates.bind(i)},l=[c,s];o(r.prototype,a.Mixin,{getTransactionWrappers:function(){return l}});var f=new r,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=p.isBatchingUpdates;p.isBatchingUpdates=!0,a?e(t,n,r,o,i):f.perform(e,null,t,n,r,o,i)}};e.exports=p},function(e,t,n){"use strict";function r(){w||(w=!0,y.EventEmitter.injectReactEventListener(m),y.EventPluginHub.injectEventPluginOrder(a),y.EventPluginUtils.injectComponentTree(f),y.EventPluginUtils.injectTreeTraversal(d),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:E,EnterLeaveEventPlugin:u,ChangeEventPlugin:i,SelectEventPlugin:_,BeforeInputEventPlugin:o}),y.NativeComponent.injectGenericComponentClass(l),y.NativeComponent.injectTextComponentClass(h),y.DOMProperty.injectDOMPropertyConfig(s),y.DOMProperty.injectDOMPropertyConfig(b),y.EmptyComponent.injectEmptyComponentFactory(function(e){return new p(e)}),y.Updates.injectReconcileTransaction(g),y.Updates.injectBatchingStrategy(v),y.Component.injectEnvironment(c))}var o=n(297),i=n(299),a=n(301),u=n(302),s=n(304),c=n(138),l=n(312),f=n(4),p=n(314),d=n(324),h=n(322),v=n(142),m=n(328),y=n(329),g=n(333),b=n(337),_=n(338),E=n(339),w=!1;e.exports={inject:r}},function(e,t){"use strict";var n,r={injectEmptyComponentFactory:function(e){n=e}},o={create:function(e){return n(e)}};o.injection=r,e.exports=o},function(e,t){"use strict";var n={logTopLevelRenders:!1};e.exports=n},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(320),i=n(195),a=n(95),u=n(96),s={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if(void 0===r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=s},function(e,t,n){"use strict";var r=n(350),o=/^<\!\-\-/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return o.test(e)?e:e.replace(/\/?>/," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);return n=n&&parseInt(n,10),r(e)===n}};e.exports=i},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===R?e.documentElement:e.firstChild:null}function i(e){return e.getAttribute&&e.getAttribute(k)||""}function a(e,t,n,r,o){var i;if(b.logTopLevelRenders){var a=e._currentElement.props,u=a.type;i="React mount: "+("string"==typeof u?u:u.displayName||u.name),console.time(i)}var s=E.mountComponent(e,n,null,m(e,t),o);i&&console.timeEnd(i),e._renderedComponent._topLevelWrapper=e,j._mountImageIntoNode(s,t,e,r,n)}function u(e,t,n,r){var o=x.ReactReconcileTransaction.getPooled(!n&&y.useCreateElement);o.perform(a,null,e,t,o,n,r),x.ReactReconcileTransaction.release(o)}function s(e,t,n){for(E.unmountComponent(e,n),t.nodeType===R&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function c(e){var t=o(e);if(t){var n=v.getInstanceFromNode(t);return!(!n||!n._nativeParent)}}function l(e){var t=o(e),n=t&&v.getInstanceFromNode(t);return n&&!n._nativeParent?n:null}function f(e){var t=l(e);return t?t._nativeContainerInfo._topLevelWrapper:null}var p=n(23),d=n(19),h=n(49),v=(n(20),n(4)),m=n(140),y=n(315),g=n(17),b=n(145),_=(n(7),n(147)),E=n(21),w=n(154),x=n(10),C=n(24),S=n(84),P=n(1),O=n(86),T=n(87),k=(n(2),d.ID_ATTRIBUTE_NAME),A=d.ROOT_ATTRIBUTE_NAME,R=9,I={},N=1,M=function(){this.rootID=N++};M.prototype.isReactComponent={},M.prototype.render=function(){return this.props};var j={TopLevelWrapper:M,_instancesByReactRootID:I,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return j.scrollMonitor(n,function(){w.enqueueElementInternal(e,t),r&&w.enqueueCallbackInternal(e,r)}),e},_renderNewRootComponent:function(e,t,n,r){(!t||1!==t.nodeType&&t.nodeType!==R&&11!==t.nodeType)&&P(!1),h.ensureScrollValueMonitoring();var o=S(e);x.batchedUpdates(u,o,t,n,r);var i=o._instance.rootID;return I[i]=o,o},renderSubtreeIntoContainer:function(e,t,n,r){return(null==e||null==e._reactInternalInstance)&&P(!1),j._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){w.validateCallback(r,"ReactDOM.render"),g.isValidElement(t)||P(!1);var a=g(M,null,null,null,null,null,t),u=f(n);if(u){var s=u._currentElement,l=s.props;if(T(l,t)){var p=u._renderedComponent.getPublicInstance(),d=r&&function(){r.call(p)};return j._updateRootComponent(u,a,n,d),p}j.unmountComponentAtNode(n)}var h=o(n),v=h&&!!i(h),m=c(n),y=v&&!u&&!m,b=j._renderNewRootComponent(a,n,y,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):C)._renderedComponent.getPublicInstance();return r&&r.call(b),b},render:function(e,t,n){return j._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){(!e||1!==e.nodeType&&e.nodeType!==R&&11!==e.nodeType)&&P(!1);var t=f(e);return t?(delete I[t._instance.rootID],x.batchedUpdates(s,t,e,!1),!0):(c(e),1===e.nodeType&&e.hasAttribute(A),!1)},_mountImageIntoNode:function(e,t,n,i,a){if((!t||1!==t.nodeType&&t.nodeType!==R&&11!==t.nodeType)&&P(!1),i){var u=o(t);if(_.canReuseMarkup(e,u))return void v.precacheNode(n,u);var s=u.getAttribute(_.CHECKSUM_ATTR_NAME);u.removeAttribute(_.CHECKSUM_ATTR_NAME);var c=u.outerHTML;u.setAttribute(_.CHECKSUM_ATTR_NAME,s);var l=e,f=r(l,c);l.substring(f-20,f+20),c.substring(f-20,f+20),t.nodeType===R&&P(!1)}if(t.nodeType===R&&P(!1),a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);p.insertTreeBefore(t,e,null)}else O(t,e),v.precacheNode(n,t.firstChild)}};e.exports=j},function(e,t,n){"use strict";var r=n(32),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=o},function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=f[t];return null==n&&(f[t]=n=c(t)),n}function o(e){return l||s(!1),new l(e)}function i(e){return new p(e)}function a(e){return e instanceof p}var u=n(3),s=n(1),c=null,l=null,f={},p=null,d={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){p=e},injectComponentClasses:function(e){u(f,e)}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:d};e.exports=h},function(e,t,n){"use strict";var r=n(17),o=n(1),i={NATIVE:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||!1===e?i.EMPTY:r.isValidElement(e)?"function"==typeof e.type?i.COMPOSITE:i.NATIVE:void o(!1)}};e.exports=i},function(e,t,n){"use strict";var r=(n(2),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){},enqueueReplaceState:function(e,t){},enqueueSetState:function(e,t){}});e.exports=r},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1}var o=n(3),i=n(16),a=n(51),u=[],s={enqueue:function(){}},c={getTransactionWrappers:function(){return u},getReactMountReady:function(){return s},destructor:function(){},checkpoint:function(){},rollback:function(){}};o(r.prototype,a.Mixin,c),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e){a.enqueueUpdate(e)}function o(e,t){var n=i.get(e);return n||null}var i=(n(20),n(77)),a=n(10),u=n(1),s=(n(2),{isMounted:function(e){var t=i.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){s.validateCallback(t,n);var i=o(e);return i?(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],void r(i)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){(n._pendingStateQueue||(n._pendingStateQueue=[])).push(t),r(n)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e&&u(!1)}});e.exports=s},function(e,t){"use strict";e.exports="15.1.0"},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t,n){"use strict";function r(e,t){if(null==t&&o(!1),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=n(1);e.exports=r},function(e,t,n){"use strict";e.exports=!1},function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=n},function(e,t){"use strict";function n(e){var t=e&&(r&&e[r]||e[o]);if("function"==typeof t)return t}var r="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";e.exports=n},function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.NATIVE?e._renderedComponent:t===o.EMPTY?null:void 0}var o=n(151);e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(6),i=null;e.exports=r},function(e,t){"use strict";function n(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&r[e.type]||"textarea"===t)}var r={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=n},function(e,t,n){"use strict";var r=n(6),o=n(52),i=n(86),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),e.exports=a},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(188),u=function(e){return e&&e.__esModule?e:{default:e}}(a),s=function(e){function t(e){r(this,t);var n=o(this,Object.getPrototypeOf(t).call(this,"Submit Validation Failed"));return n.errors=e,n}return i(t,e),t}(u.default);t.default=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.untouch=t.unregisterField=t.touch=t.setSubmitFailed=t.stopSubmit=t.stopAsyncValidation=t.startSubmit=t.startAsyncValidation=t.reset=t.registerField=t.initialize=t.focus=t.destroy=t.change=t.blur=t.arrayUnshift=t.arraySwap=t.arraySplice=t.arrayShift=t.arrayRemove=t.arrayPush=t.arrayPop=t.arrayInsert=void 0;var r=n(90);t.arrayInsert=function(e,t,n,o){return{type:r.ARRAY_INSERT,meta:{form:e,field:t,index:n},payload:o}},t.arrayPop=function(e,t){return{type:r.ARRAY_POP,meta:{form:e,field:t}}},t.arrayPush=function(e,t,n){return{type:r.ARRAY_PUSH,meta:{form:e,field:t},payload:n}},t.arrayRemove=function(e,t,n){return{type:r.ARRAY_REMOVE,meta:{form:e,field:t,index:n}}},t.arrayShift=function(e,t){return{type:r.ARRAY_SHIFT,meta:{form:e,field:t}}},t.arraySplice=function(e,t,n,o,i){var a={type:r.ARRAY_SPLICE,meta:{form:e,field:t,index:n,removeNum:o}};return void 0!==i&&(a.payload=i),a},t.arraySwap=function(e,t,n,o){if(n===o)throw new Error("Swap indices cannot be equal");if(n<0||o<0)throw new Error("Swap indices cannot be negative");return{type:r.ARRAY_SWAP,meta:{form:e,field:t,indexA:n,indexB:o}}},t.arrayUnshift=function(e,t,n){return{type:r.ARRAY_UNSHIFT,meta:{form:e,field:t},payload:n}},t.blur=function(e,t,n,o){return{type:r.BLUR,meta:{form:e,field:t,touch:o},payload:n}},t.change=function(e,t,n,o){return{type:r.CHANGE,meta:{form:e,field:t,touch:o},payload:n}},t.destroy=function(e){return{type:r.DESTROY,meta:{form:e}}},t.focus=function(e,t){return{type:r.FOCUS,meta:{form:e,field:t}}},t.initialize=function(e,t){return{type:r.INITIALIZE,meta:{form:e},payload:t}},t.registerField=function(e,t,n){return{type:r.REGISTER_FIELD,meta:{form:e},payload:{name:t,type:n}}},t.reset=function(e){return{type:r.RESET,meta:{form:e}}},t.startAsyncValidation=function(e,t){return{type:r.START_ASYNC_VALIDATION,meta:{form:e,field:t}}},t.startSubmit=function(e){return{type:r.START_SUBMIT,meta:{form:e}}},t.stopAsyncValidation=function(e,t){var n={type:r.STOP_ASYNC_VALIDATION,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(n.error=!0),n},t.stopSubmit=function(e,t){var n={type:r.STOP_SUBMIT,meta:{form:e},payload:t};return t&&Object.keys(t).length&&(n.error=!0),n},t.setSubmitFailed=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.SET_SUBMIT_FAILED,meta:{form:e,fields:n},error:!0}},t.touch=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.TOUCH,meta:{form:e,fields:n}}},t.unregisterField=function(e,t){return{type:r.UNREGISTER_FIELD,meta:{form:e},payload:{name:t}}},t.untouch=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),o=1;o<t;o++)n[o-1]=arguments[o];return{type:r.UNTOUCH,meta:{form:e,fields:n}}}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=t.dataKey="value",r=function(e,t){return function(e){e.dataTransfer.setData(n,t)}};t.default=r},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(169),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e){var t=[];if(e)for(var n=0;n<e.length;n++){var r=e[n];r.selected&&t.push(r.value)}return t},a=function(e,t){if((0,o.default)(e)){if(!t&&e.nativeEvent&&void 0!==e.nativeEvent.text)return e.nativeEvent.text;if(t&&void 0!==e.nativeEvent)return e.nativeEvent.text;var n=e.target,r=n.type,a=n.value,u=n.checked,s=n.files,c=e.dataTransfer;return"checkbox"===r?u:"file"===r?s||c&&c.files:"select-multiple"===r?i(e.target.options):a}return e&&void 0!==e.value?e.value:e};t.default=a},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){return!!(e&&e.stopPropagation&&e.preventDefault)};t.default=n},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(169),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e){var t=(0,o.default)(e);return t&&e.preventDefault(),t};t.default=i},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product;t.default=n},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var o=n(45),i=function(e){return e&&e.__esModule?e:{default:e}}(o),a=function e(t,n){for(var r=arguments.length,o=Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];if(!t)return t;var a=t[n];return o.length?e.apply(void 0,[a].concat(o)):a},u=function(e,t){return a.apply(void 0,[e].concat(r((0,i.default)(t))))};t.default=u},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0===t.length)return function(e){return e};var r=function(){var e=t[t.length-1],n=t.slice(0,-1);return{v:function(){return n.reduceRight(function(e,t){return t(e)},e.apply(void 0,arguments))}}}();return"object"==typeof r?r.v:void 0}t.__esModule=!0,t.default=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){function r(){y===m&&(y=m.slice())}function i(){return v}function u(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return r(),y.push(e),function(){if(t){t=!1,r();var n=y.indexOf(e);y.splice(n,1)}}}function l(e){if(!(0,a.default)(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(g)throw new Error("Reducers may not dispatch actions.");try{g=!0,v=h(v,e)}finally{g=!1}for(var t=m=y,n=0;n<t.length;n++)t[n]();return e}function f(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");h=e,l({type:c.INIT})}function p(){var e,t=u;return e={subscribe:function(e){function n(){e.next&&e.next(i())}if("object"!=typeof e)throw new TypeError("Expected the observer to be an object.");return n(),{unsubscribe:t(n)}}},e[s.default]=function(){return this},e}var d;if("function"==typeof t&&void 0===n&&(n=t,t=void 0),void 0!==n){if("function"!=typeof n)throw new Error("Expected the enhancer to be a function.");return n(o)(e,t)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");var h=e,v=t,m=[],y=m,g=!1;return l({type:c.INIT}),d={dispatch:l,subscribe:u,getState:i,replaceReducer:f},d[s.default]=p,d}t.__esModule=!0,t.ActionTypes=void 0,t.default=o;var i=n(65),a=r(i),u=n(392),s=r(u),c=t.ActionTypes={INIT:"@@redux/INIT"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.compose=t.applyMiddleware=t.bindActionCreators=t.combineReducers=t.createStore=void 0;var o=n(174),i=r(o),a=n(391),u=r(a),s=n(390),c=r(s),l=n(389),f=r(l),p=n(173),d=r(p);r(n(176)),t.createStore=i.default,t.combineReducers=u.default,t.bindActionCreators=c.default,t.applyMiddleware=f.default,t.compose=d.default},function(e,t){"use strict";function n(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}t.__esModule=!0,t.default=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o=n(5),i=r(o),a=n(290),u=r(a),s=n(53),c=r(s);"undefined"!=typeof window&&(window.initReact=function(e){return u.default.render(i.default.createElement(c.default,e),document.getElementById("content"))})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(68),u=r(a),s=n(190),c=r(s),l=function(e){return/<p>(.+)<\/p>/.exec((0,u.default)(e))[1]},f=function(e){var t=e.items;return!(!t||!t.length)&&i.default.createElement("ol",{className:c.default.breadcrumbs},t.map(function(e,n){var r=e.path,o=e.title;return n===t.length-1?i.default.createElement("li",{key:n,dangerouslySetInnerHTML:{__html:l(o)}}):i.default.createElement("li",{key:n},i.default.createElement("a",{href:r,dangerouslySetInnerHTML:{__html:l(o)}}))}))};t.default=f},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(5),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e){var t=e.user,n=e.repo,r=e.type,i=e.width,a=e.height,u=e.count,s=e.large,c="https://ghbtns.com/github-btn.html?user="+t+"&repo="+n+"&type="+r;return u&&(c+="&count=true"),s&&(c+="&size=large"),o.default.createElement("iframe",{src:c,frameBorder:"0",allowTransparency:"true",scrolling:"0",width:i,height:a,style:{border:"none",width:i,height:a}})};i.propTypes={user:r.PropTypes.string.isRequired,repo:r.PropTypes.string.isRequired,type:r.PropTypes.oneOf(["star","watch","fork","follow"]).isRequired,width:r.PropTypes.number.isRequired,height:r.PropTypes.number.isRequired,count:r.PropTypes.bool,large:r.PropTypes.bool},t.default=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(179),u=r(a),s=function(e){var t=e.version,r=n(191);return i.default.createElement("div",{className:r.home},i.default.createElement("div",{className:r.masthead},i.default.createElement("div",{className:r.logo}),i.default.createElement("h1",null,"Redux Form"),i.default.createElement("div",{className:r.version},"v",t),i.default.createElement("h2",null,"The best way to manage your form state in Redux."),i.default.createElement(u.default,{user:"erikras",repo:"redux-form",type:"star",width:160,height:30,count:!0,large:!0}),i.default.createElement(u.default,{user:"erikras",repo:"redux-form",type:"fork",width:160,height:30,count:!0,large:!0})),i.default.createElement("div",{className:r.options},i.default.createElement("a",{href:"docs/GettingStarted.md"},i.default.createElement("i",{className:r.start}),"Start Here"),i.default.createElement("a",{href:"docs/api"},i.default.createElement("i",{className:r.api}),"API"),i.default.createElement("a",{href:"examples"},i.default.createElement("i",{className:r.examples}),"Examples"),i.default.createElement("a",{href:"docs/faq"},i.default.createElement("i",{className:r.faq}),"FAQ")))};t.default=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(5),l=r(c),f=n(93),p=r(f),d=n(68),h=r(d),v=n(192),m=r(v),y=function(e){return/<p>(.+)<\/p>/.exec((0,h.default)(e))[1]},g=function(e){function t(e){i(this,t);var n=a(this,Object.getPrototypeOf(t).call(this,e));return n.open=n.open.bind(n),n.close=n.close.bind(n),n.state={open:!1},n}return u(t,e),s(t,[{key:"renderItem",value:function(e,t){var n=arguments.length<=2||void 0===arguments[2]?0:arguments[2],r=this.props,i=r.path,a=r.url;return l.default.createElement("a",{href:""+(a||"")+e,className:(0,p.default)(m.default["indent"+n],o({},m.default.active,e===i)),dangerouslySetInnerHTML:{__html:y(t)}})}},{key:"open",value:function(){this.setState({open:!0})}},{key:"close",value:function(){this.setState({open:!1})}},{key:"render",value:function(){var e=this.state.open,t=this.props.url;return l.default.createElement("div",{className:(0,p.default)(m.default.nav,o({},m.default.open,e))},l.default.createElement("button",{type:"button",onClick:this.open}),l.default.createElement("div",{className:m.default.overlay,onClick:this.close},l.default.createElement("i",{className:"fa fa-times"})," Close"),l.default.createElement("div",{className:m.default.placeholder}),l.default.createElement("nav",{className:m.default.menu},l.default.createElement("a",{href:t,className:m.default.brand},"Redux Form"),this.renderItem("/docs/GettingStarted.md","Getting Started"),this.renderItem("/docs/MigrationGuide.md","`v6` Migration Guide"),this.renderItem("/docs/ValueLifecycle.md","Value Lifecycle"),this.renderItem("/docs/api","API"),this.renderItem("/docs/api/ReduxForm.md","`reduxForm()`",1),this.renderItem("/docs/api/Props.md","`props`",1),this.renderItem("/docs/api/Field.md","`Field`",1),this.renderItem("/docs/api/Fields.md","`Fields`",1),this.renderItem("/docs/api/FieldArray.md","`FieldArray`",1),this.renderItem("/docs/api/Form.md","`Form`",1),this.renderItem("/docs/api/FormSection.md","`FormSection`",1),this.renderItem("/docs/api/FormValueSelector.md","`formValueSelector()`",1),this.renderItem("/docs/api/Reducer.md","`reducer`",1),this.renderItem("/docs/api/ReducerPlugin.md","`reducer.plugin()`",2),this.renderItem("/docs/api/SubmissionError.md","`SubmissionError`",1),this.renderItem("/docs/api/ActionCreators.md","Action Creators",1),this.renderItem("/docs/api/Selectors.md","Selectors",1),this.renderItem("/docs/faq","FAQ"),this.renderItem("/examples","Examples"),this.renderItem("/examples/simple","Simple Form",1),this.renderItem("/examples/syncValidation","Sync Validation",1),this.renderItem("/examples/fieldLevelValidation","Field-Level Validation",1),this.renderItem("/examples/submitValidation","Submit Validation",1),this.renderItem("/examples/asyncValidation","Async Validation",1),this.renderItem("/examples/initializeFromState","Initializing from State",1),this.renderItem("/examples/selectingFormValues","Selecting Form Values",1),this.renderItem("/examples/fieldArrays","Field Arrays",1),this.renderItem("/examples/remoteSubmit","Remote Submit",1),this.renderItem("/examples/normalizing","Normalizing",1),this.renderItem("/examples/immutable","Immutable JS",1),this.renderItem("/examples/wizard","Wizard Form",1),this.renderItem("/examples/material-ui","Material UI",1),this.renderItem("/examples/react-widgets","React Widgets",1),this.renderItem("/docs/DocumentationVersions.md","Older Versions")))}}]),t}(c.Component);g.propTypes={path:c.PropTypes.string.isRequired,url:c.PropTypes.string.isRequired},t.default=g},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(5),i=function(e){return e&&e.__esModule?e:{default:e}}(o),a=function(e){var t=e.username,n=e.showUsername,o=e.showCount,a=e.large,u={};return n||(u["data-show-screen-name"]="false"),o||(u["data-show-count"]="false"),a&&(u["data-size"]="large"),i.default.createElement("a",r({href:"https://twitter.com/"+t,className:"twitter-follow-button"},u),"Follow @",t)};a.propTypes={username:o.PropTypes.string.isRequired,showUserName:o.PropTypes.bool,showCount:o.PropTypes.bool,large:o.PropTypes.bool},t.default=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(379),u=n(91),s=r(u),c=function(e){var t=e.form,n=e.format,r=void 0===n?function(e){return JSON.stringify(e,null,2)}:n,o=(0,a.values)({form:t}),u=function(e){var t=e.values;return i.default.createElement("div",null,i.default.createElement("h2",null,"Values"),i.default.createElement(s.default,{source:r(t)}))},c=o(u);return i.default.createElement(c,null)};t.default=c},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t,n){return[{path:"https://redux-form.com/"+n+"/",title:"Redux Form"},{path:"https://redux-form.com/"+n+"/examples",title:"Examples"},{path:"https://redux-form.com/"+n+"/examples/"+e,title:t}]};t.default=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Values=t.Markdown=t.Code=t.App=t.generateExampleBreadcrumbs=t.render=void 0;var o=n(186),i=r(o),a=n(184),u=r(a),s=n(53),c=r(s),l=n(91),f=r(l),p=n(92),d=r(p),h=n(183),v=r(h);t.render=i.default,t.generateExampleBreadcrumbs=u.default,t.App=c.default,t.Code=f.default,t.Markdown=d.default,t.Values=v.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(5),i=r(o),a=n(291),u=n(53),s=r(u),c=function(e){var t=e.component,n=e.title,r=e.path,o=e.version,u=e.breadcrumbs;return'<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charSet="utf-8"/>\n <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>\n <title>Redux Form'+(n&&" - "+n)+'</title>\n <link href="https://redux-form.com/'+o+'/bundle.css"\n media="screen, projection" rel="stylesheet" type="text/css"/>\n <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"\n media="screen, projection" rel="stylesheet" type="text/css"/>\n <meta itemprop="name" content="Redux Form"/>\n <meta property="og:type" content="website"/>\n <meta property="og:title" content="Redux Form"/>\n <meta property="og:site_name" content="Redux Form"/>\n <meta property="og:description" content="The best way to manage your form state in Redux."/>\n <meta property="og:image" content="logo.png"/>\n <meta property="twitter:site" content="@erikras"/>\n <meta property="twitter:creator" content="@erikras"/>\n <style type="text/css">\n body {\n margin: 0;\n }\n </style>\n </head>\n <body>\n <div id="content">\n '+(0,a.renderToString)(i.default.createElement(s.default,{version:o,path:r,breadcrumbs:u},t))+'\n </div>\n <script src="https://redux-form.com/'+o+'/bundle.js"></script>\n <script>initReact('+JSON.stringify({version:o,path:r,breadcrumbs:u})+")</script>\n <script>\n (function(i,s,o,g,r,a,m){i[ 'GoogleAnalyticsObject' ] = r;i[r]=i[r]||function(){\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n ga('create', 'UA-69298417-1', 'auto');\n ga('send', 'pageview');\n </script>\n <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>\n </body>\n </html>"};t.default=c},function(e,t){(function(t){"use strict";var n="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},r=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,r=n.Prism={util:{encode:function(e){return e instanceof o?new o(e.type,r.util.encode(e.content),e.alias):"Array"===r.util.type(e)?e.map(r.util.encode):e.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function(e){switch(r.util.type(e)){case"Object":var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=r.util.clone(e[n]));return t;case"Array":return e.map&&e.map(function(e){return r.util.clone(e)})}return e}},languages:{extend:function(e,t){var n=r.util.clone(r.languages[e]);for(var o in t)n[o]=t[o];return n},insertBefore:function(e,t,n,o){o=o||r.languages;var i=o[e];if(2==arguments.length){n=arguments[1];for(var a in n)n.hasOwnProperty(a)&&(i[a]=n[a]);return i}var u={};for(var s in i)if(i.hasOwnProperty(s)){if(s==t)for(var a in n)n.hasOwnProperty(a)&&(u[a]=n[a]);u[s]=i[s]}return r.languages.DFS(r.languages,function(t,n){n===o[e]&&t!=e&&(this[t]=u)}),o[e]=u},DFS:function(e,t,n,o){o=o||{};for(var i in e)e.hasOwnProperty(i)&&(t.call(e,i,e[i],n||i),"Object"!==r.util.type(e[i])||o[r.util.objId(e[i])]?"Array"!==r.util.type(e[i])||o[r.util.objId(e[i])]||(o[r.util.objId(e[i])]=!0,r.languages.DFS(e[i],t,i,o)):(o[r.util.objId(e[i])]=!0,r.languages.DFS(e[i],t,null,o)))}},plugins:{},highlightAll:function(e,t){var n={callback:t,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};r.hooks.run("before-highlightall",n);for(var o,i=n.elements||document.querySelectorAll(n.selector),a=0;o=i[a++];)r.highlightElement(o,!0===e,n.callback)},highlightElement:function(t,o,i){for(var a,u,s=t;s&&!e.test(s.className);)s=s.parentNode;s&&(a=(s.className.match(e)||[,""])[1],u=r.languages[a]),t.className=t.className.replace(e,"").replace(/\s+/g," ")+" language-"+a,s=t.parentNode,/pre/i.test(s.nodeName)&&(s.className=s.className.replace(e,"").replace(/\s+/g," ")+" language-"+a);var c=t.textContent,l={element:t,language:a,grammar:u,code:c};if(!c||!u)return void r.hooks.run("complete",l);if(r.hooks.run("before-highlight",l),o&&n.Worker){var f=new Worker(r.filename);f.onmessage=function(e){l.highlightedCode=e.data,r.hooks.run("before-insert",l),l.element.innerHTML=l.highlightedCode,i&&i.call(l.element),r.hooks.run("after-highlight",l),r.hooks.run("complete",l)},f.postMessage(JSON.stringify({language:l.language,code:l.code,immediateClose:!0}))}else l.highlightedCode=r.highlight(l.code,l.grammar,l.language),r.hooks.run("before-insert",l),l.element.innerHTML=l.highlightedCode,i&&i.call(t),r.hooks.run("after-highlight",l),r.hooks.run("complete",l)},highlight:function(e,t,n){var i=r.tokenize(e,t);return o.stringify(r.util.encode(i),n)},tokenize:function(e,t){var n=r.Token,o=[e],i=t.rest;if(i){for(var a in i)t[a]=i[a];delete t.rest}e:for(var a in t)if(t.hasOwnProperty(a)&&t[a]){var u=t[a];u="Array"===r.util.type(u)?u:[u];for(var s=0;s<u.length;++s){var c=u[s],l=c.inside,f=!!c.lookbehind,p=!!c.greedy,d=0,h=c.alias;c=c.pattern||c;for(var v=0;v<o.length;v++){var m=o[v];if(o.length>e.length)break e;if(!(m instanceof n)){c.lastIndex=0;var y=c.exec(m),g=1;if(!y&&p&&v!=o.length-1){var b=o[v+1].matchedStr||o[v+1],_=m+b;if(v<o.length-2&&(_+=o[v+2].matchedStr||o[v+2]),c.lastIndex=0,!(y=c.exec(_)))continue;var E=y.index+(f?y[1].length:0);if(E>=m.length)continue;var w=y.index+y[0].length,x=m.length+b.length;g=3,x>=w&&(g=2,_=_.slice(0,x)),m=_}if(y){f&&(d=y[1].length);var E=y.index+d,y=y[0].slice(d),w=E+y.length,C=m.slice(0,E),S=m.slice(w),P=[v,g];C&&P.push(C);var O=new n(a,l?r.tokenize(y,l):y,h,y);P.push(O),S&&P.push(S),Array.prototype.splice.apply(o,P)}}}}}return o},hooks:{all:{},add:function(e,t){var n=r.hooks.all;n[e]=n[e]||[],n[e].push(t)},run:function(e,t){var n=r.hooks.all[e];if(n&&n.length)for(var o,i=0;o=n[i++];)o(t)}}},o=r.Token=function(e,t,n,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=r||null};if(o.stringify=function(e,t,n){if("string"==typeof e)return e;if("Array"===r.util.type(e))return e.map(function(n){return o.stringify(n,t,e)}).join("");var i={type:e.type,content:o.stringify(e.content,t,n),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:n};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var a="Array"===r.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,a)}r.hooks.run("wrap",i);var u="";for(var s in i.attributes)u+=(u?" ":"")+s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+u+">"+i.content+"</"+i.tag+">"},!n.document)return n.addEventListener?(n.addEventListener("message",function(e){var t=JSON.parse(e.data),o=t.language,i=t.code,a=t.immediateClose;n.postMessage(r.highlight(i,r.languages[o],o)),a&&n.close()},!1),n.Prism):n.Prism;var i=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return i&&(r.filename=i.src,document.addEventListener&&!i.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",r.highlightAll)),n.Prism}();void 0!==e&&e.exports&&(e.exports=r),void 0!==t&&(t.Prism=r),r.languages.markup={comment:/<!--[\w\W]*?-->/,prolog:/<\?[\w\W]+?\?>/,doctype:/<!DOCTYPE[\w\W]+?>/,cdata:/<!\[CDATA\[[\w\W]*?]]>/i,tag:{pattern:/<\/?(?!\d)[^\s>\/=.$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,inside:{punctuation:/[=>"']/}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/&#?[\da-z]{1,8};/i},r.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),r.languages.xml=r.languages.markup,r.languages.html=r.languages.markup,r.languages.mathml=r.languages.markup,r.languages.svg=r.languages.markup,r.languages.css={comment:/\/\*[\w\W]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^\{\}\s][^\{\};]*?(?=\s*\{)/,string:/("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,property:/(\b|\B)[\w-]+(?=\s*:)/i,important:/\B!important\b/i,function:/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},r.languages.css.atrule.inside.rest=r.util.clone(r.languages.css),r.languages.markup&&(r.languages.insertBefore("markup","tag",{style:{pattern:/(<style[\w\W]*?>)[\w\W]*?(?=<\/style>)/i,lookbehind:!0,inside:r.languages.css,alias:"language-css"}}),r.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|').*?\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:r.languages.markup.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:r.languages.css}},alias:"language-css"}},r.languages.markup.tag)),r.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0}],string:{pattern:/(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,boolean:/\b(true|false)\b/,function:/[a-z0-9_]+(?=\()/i,number:/\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,operator:/--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,punctuation:/[{}[\];(),.:]/},r.languages.javascript=r.languages.extend("clike",{keyword:/\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/,number:/\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,function:/[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i}),r.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^\/])\/(?!\/)(\[.+?]|\\.|[^\/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,lookbehind:!0,greedy:!0}}),r.languages.insertBefore("javascript","class-name",{"template-string":{pattern:/`(?:\\\\|\\?[^\\])*?`/,inside:{interpolation:{pattern:/\$\{[^}]+\}/,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:r.languages.javascript}},string:/[\s\S]+/}}}),r.languages.markup&&r.languages.insertBefore("markup","tag",{script:{pattern:/(<script[\w\W]*?>)[\w\W]*?(?=<\/script>)/i,lookbehind:!0,inside:r.languages.javascript,alias:"language-javascript"}}),r.languages.js=r.languages.javascript,r.languages.json={property:/".*?"(?=\s*:)/gi,string:/"(?!:)(\\?[^"])*?"(?!:)/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,punctuation:/[{}[\]);,]/g,operator:/:/g,boolean:/\b(true|false)\b/gi,null:/\bnull\b/gi},r.languages.jsonp=r.languages.json,function(e){var t=e.util.clone(e.languages.javascript);e.languages.jsx=e.languages.extend("markup",t),e.languages.jsx.tag.pattern=/<\/?[\w\.:-]+\s*(?:\s+[\w\.:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+|(\{[\w\W]*?\})))?\s*)*\/?>/i,e.languages.jsx.tag.inside["attr-value"].pattern=/=[^\{](?:('|")[\w\W]*?(\1)|[^\s>]+)/i;var n=e.util.clone(e.languages.jsx);delete n.punctuation,n=e.languages.insertBefore("jsx","operator",{punctuation:/=(?={)|[{}[\];(),.:]/},{jsx:n}),e.languages.insertBefore("inside","attr-value",{script:{pattern:/=(\{(?:\{[^}]*\}|[^}])+\})/i,inside:n,alias:"language-javascript"}},e.languages.jsx.tag)}(r)}).call(t,function(){return this}())},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var o=function(e,t,n){for(var r=!0;r;){var o=e,i=t,a=n;r=!1,null===o&&(o=Function.prototype);var u=Object.getOwnPropertyDescriptor(o,i);if(void 0!==u){if("value"in u)return u.value;var s=u.get;if(void 0===s)return;return s.call(a)}var c=Object.getPrototypeOf(o);if(null===c)return;e=c,t=i,n=a,r=!0,u=c=void 0}},i=function(e){function t(){var e=arguments.length<=0||void 0===arguments[0]?"":arguments[0];return n(this,t),o(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),Object.defineProperty(this,"message",{enumerable:!1,value:e,writable:!0}),Object.defineProperty(this,"name",{enumerable:!1,value:this.constructor.name,writable:!0}),Error.hasOwnProperty("captureStackTrace")?void Error.captureStackTrace(this,this.constructor):void Object.defineProperty(this,"stack",{enumerable:!1,value:new Error(e).stack,writable:!0})}return r(t,e),t}(Error);t.default=i,e.exports=t.default},function(e,t){e.exports={app:"app___3P8ep",topNav:"topNav___sBW8S",brand:"brand___YAZl-",github:"github___3-vRv",contentAndFooter:"contentAndFooter___kE2nt",content:"content___3TVHp",home:"home___2XyPG",hasNav:"hasNav___1KF_W",footer:"footer___1oh0h",help:"help___3OayI"}},function(e,t){e.exports={breadcrumbs:"breadcrumbs___1BHo6"}},function(e,t){e.exports={home:"home___381a9",masthead:"masthead___MGNF0",logo:"logo___hP7wi",content:"content___2vYdp",version:"version___2mbZo",github:"github___mrRv3",options:"options___2Tyc4",start:"start___1WlUb",api:"api___1hCrr",examples:"examples___2H_mp",faq:"faq___2mIT0"}},function(e,t){e.exports={nav:"nav___11xa5",placeholder:"placeholder___TzF1K",overlay:"overlay___1GMox",menu:"menu___12xDU",active:"active___2eU59",brand:"brand___1qRUu",indent1:"indent1___4iVnL",indent2:"indent2___2PiOO",open:"open___3Bk_k"}},function(e,t){"use strict";function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(193),i=/^-ms-/;e.exports=r},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!o(e)&&(o(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var o=n(202);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.length;if((Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e)&&a(!1),"number"!=typeof t&&a(!1),0===t||t-1 in e||a(!1),"function"==typeof e.callee&&a(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=n(1);e.exports=i},function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function o(e,t){var n=c;c||s(!1);var o=r(e),i=o&&u(o);if(i){n.innerHTML=i[1]+e+i[2];for(var l=i[0];l--;)n=n.lastChild}else n.innerHTML=e;var f=n.getElementsByTagName("script");f.length&&(t||s(!1),a(f).forEach(t));for(var p=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return p}var i=n(6),a=n(196),u=n(97),s=n(1),c=i.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;e.exports=o},function(e,t){"use strict";function n(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=n},function(e,t){"use strict";function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(199),i=/^ms-/;e.exports=r},function(e,t){"use strict";function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(201);e.exports=r},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t,n){"use strict";var r;n(6).canUseDOM&&(r=window.performance||window.msPerformance||window.webkitPerformance),e.exports=r||{}},function(e,t,n){"use strict";var r,o=n(204);r=o.now?function(){return o.now()}:function(){return Date.now()},e.exports=r},function(e,t,n){var r=n(22),o=n(8),i=r(o,"DataView");e.exports=i},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(242),i=n(243),a=n(244),u=n(245),s=n(246);r.prototype.clear=o,r.prototype.delete=i,r.prototype.get=a,r.prototype.has=u,r.prototype.set=s,e.exports=r},function(e,t,n){var r=n(22),o=n(8),i=r(o,"Promise");e.exports=i},function(e,t,n){var r=n(22),o=n(8),i=r(o,"Set");e.exports=i},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.__data__=new o;++t<n;)this.add(e[t])}var o=n(57),i=n(267),a=n(268);r.prototype.add=r.prototype.push=i,r.prototype.has=a,e.exports=r},function(e,t,n){var r=n(8),o=r.Uint8Array;e.exports=o},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=n},function(e,t,n){var r=n(105),o=n(229),i=o(r);e.exports=i},function(e,t,n){var r=n(230),o=r();e.exports=o},function(e,t){function n(e,t){return null!=e&&t in Object(e)}e.exports=n},function(e,t,n){function r(e,t,n,r,m,g){var b=c(e),_=c(t),E=h,w=h;b||(E=s(e),E=E==d?v:E),_||(w=s(t),w=w==d?v:w);var x=E==v&&!l(e),C=w==v&&!l(t),S=E==w;if(S&&!x)return g||(g=new o),b||f(e)?i(e,t,n,r,m,g):a(e,t,E,n,r,m,g);if(!(m&p)){var P=x&&y.call(e,"__wrapped__"),O=C&&y.call(t,"__wrapped__");if(P||O){var T=P?e.value():e,k=O?t.value():t;return g||(g=new o),n(T,k,r,m,g)}}return!!S&&(g||(g=new o),u(e,t,n,r,m,g))}var o=n(101),i=n(117),a=n(234),u=n(235),s=n(239),c=n(11),l=n(63),f=n(280),p=2,d="[object Arguments]",h="[object Array]",v="[object Object]",m=Object.prototype,y=m.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t,n,r){var s=n.length,c=s,l=!r;if(null==e)return!c;for(e=Object(e);s--;){var f=n[s];if(l&&f[2]?f[1]!==e[f[0]]:!(f[0]in e))return!1}for(;++s<c;){f=n[s];var p=f[0],d=e[p],h=f[1];if(l&&f[2]){if(void 0===d&&!(p in e))return!1}else{var v=new o;if(r)var m=r(d,h,p,e,t,v);if(!(void 0===m?i(h,d,r,a|u,v):m))return!1}}return!0}var o=n(101),i=n(60),a=1,u=2;e.exports=r},function(e,t,n){function r(e){return!(!u(e)||a(e))&&(o(e)||i(e)?d:c).test(s(e))}var o=n(64),i=n(63),a=n(251),u=n(15),s=n(125),c=/^\[object .+?Constructor\]$/,l=Object.prototype,f=Function.prototype.toString,p=l.hasOwnProperty,d=RegExp("^"+f.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t){function n(e){return r(Object(e))}var r=Object.keys;e.exports=n},function(e,t,n){function r(e){var t=i(e);return 1==t.length&&t[0][2]?a(t[0][0],t[0][1]):function(n){return n===e||o(n,e,t)}}var o=n(217),i=n(238),a=n(121);e.exports=r},function(e,t,n){function r(e,t){return u(e)&&s(t)?c(l(e),t):function(n){var r=i(n,e);return void 0===r&&r===t?a(n,e):o(t,r,void 0,f|p)}}var o=n(60),i=n(276),a=n(277),u=n(40),s=n(120),c=n(121),l=n(26),f=1,p=2;e.exports=r},function(e,t,n){function r(e){return function(t){return o(t,e)}}var o=n(106);e.exports=r},function(e,t,n){function r(e,t){var n;return o(e,function(e,r,o){return!(n=t(e,r,o))}),!!n}var o=n(213);e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}e.exports=n},function(e,t,n){function r(e){if("string"==typeof e)return e;if(i(e))return s?s.call(e):"";var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=n(102),i=n(27),a=1/0,u=o?o.prototype:void 0,s=u?u.toString:void 0;e.exports=r},function(e,t){function n(e){return e&&e.Object===Object?e:null}e.exports=n},function(e,t,n){var r=n(8),o=r["__core-js_shared__"];e.exports=o},function(e,t){function n(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&r++;return r}e.exports=n},function(e,t,n){function r(e,t){return function(n,r){if(null==n)return n;if(!o(n))return e(n,r);for(var i=n.length,a=t?i:-1,u=Object(n);(t?a--:++a<i)&&!1!==r(u[a],a,u););return n}}var o=n(42);e.exports=r},function(e,t){function n(e){return function(t,n,r){for(var o=-1,i=Object(t),a=r(t),u=a.length;u--;){var s=a[e?u:++o];if(!1===n(i[s],s,i))break}return t}}e.exports=n},function(e,t,n){function r(e,t,n){function r(){return(this&&this!==i&&this instanceof r?s:e).apply(u?n:this,arguments)}var u=t&a,s=o(e);return r}var o=n(36),i=n(8),a=1;e.exports=r},function(e,t,n){function r(e,t,n){function r(){for(var i=arguments.length,p=Array(i),d=i,h=s(r);d--;)p[d]=arguments[d];var v=i<3&&p[0]!==h&&p[i-1]!==h?[]:c(p,h);return(i-=v.length)<n?u(e,t,a,r.placeholder,void 0,p,v,void 0,void 0,n-i):o(this&&this!==l&&this instanceof r?f:e,this,p)}var f=i(e);return r}var o=n(58),i=n(36),a=n(114),u=n(115),s=n(37),c=n(25),l=n(8);e.exports=r},function(e,t,n){function r(e,t,n,r){function s(){for(var t=-1,i=arguments.length,u=-1,f=r.length,p=Array(f+i),d=this&&this!==a&&this instanceof s?l:e;++u<f;)p[u]=r[u];for(;i--;)p[u++]=arguments[++t];return o(d,c?n:this,p)}var c=t&u,l=i(e);return s}var o=n(58),i=n(36),a=n(8),u=1;e.exports=r},function(e,t,n){function r(e,t,n,r,o,w,C){switch(n){case E:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case _:return!(e.byteLength!=t.byteLength||!r(new i(e),new i(t)));case f:case p:return+e==+t;case d:return e.name==t.name&&e.message==t.message;case v:return e!=+e?t!=+t:e==+t;case m:case g:return e==t+"";case h:var S=u;case y:var P=w&l;if(S||(S=s),e.size!=t.size&&!P)return!1;var O=C.get(e);return O?O==t:(w|=c,C.set(e,t),a(S(e),S(t),r,o,w,C));case b:if(x)return x.call(e)==x.call(t)}return!1}var o=n(102),i=n(211),a=n(117),u=n(263),s=n(269),c=1,l=2,f="[object Boolean]",p="[object Date]",d="[object Error]",h="[object Map]",v="[object Number]",m="[object RegExp]",y="[object Set]",g="[object String]",b="[object Symbol]",_="[object ArrayBuffer]",E="[object DataView]",w=o?o.prototype:void 0,x=w?w.valueOf:void 0;e.exports=r},function(e,t,n){function r(e,t,n,r,u,s){var c=u&a,l=i(e),f=l.length;if(f!=i(t).length&&!c)return!1;for(var p=f;p--;){var d=l[p];if(!(c?d in t:o(t,d)))return!1}var h=s.get(e);if(h)return h==t;var v=!0;s.set(e,t);for(var m=c;++p<f;){d=l[p];var y=e[d],g=t[d];if(r)var b=c?r(g,y,d,t,e,s):r(y,g,d,e,t,s);if(!(void 0===b?y===g||n(y,g,r,u,s):b)){v=!1;break}m||(m="constructor"==d)}if(v&&!m){var _=e.constructor,E=t.constructor;_!=E&&"constructor"in e&&"constructor"in t&&!("function"==typeof _&&_ instanceof _&&"function"==typeof E&&E instanceof E)&&(v=!1)}return s.delete(e),v}var o=n(107),i=n(66),a=2;e.exports=r},function(e,t,n){function r(e){for(var t=e.name+"",n=o[t],r=a.call(o,t)?n.length:0;r--;){var i=n[r],u=i.func;if(null==u||u==e)return i.name}return t}var o=n(265),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){var r=n(109),o=r("length");e.exports=o},function(e,t,n){function r(e){for(var t=i(e),n=t.length;n--;){var r=t[n],a=e[r];t[n]=[r,a,o(a)]}return t}var o=n(120),i=n(66);e.exports=r},function(e,t,n){function r(e){return m.call(e)}var o=n(206),i=n(100),a=n(208),u=n(209),s=n(103),c=n(125),l="[object Map]",f="[object Promise]",p="[object Set]",d="[object WeakMap]",h="[object DataView]",v=Object.prototype,m=v.toString,y=c(o),g=c(i),b=c(a),_=c(u),E=c(s);(o&&r(new o(new ArrayBuffer(1)))!=h||i&&r(new i)!=l||a&&r(a.resolve())!=f||u&&r(new u)!=p||s&&r(new s)!=d)&&(r=function(e){var t=m.call(e),n="[object Object]"==t?e.constructor:void 0,r=n?c(n):void 0;if(r)switch(r){case y:return h;case g:return l;case b:return f;case _:return p;case E:return d}return t}),e.exports=r},function(e,t){function n(e,t){return null==e?void 0:e[t]}e.exports=n},function(e,t,n){function r(e,t,n){t=s(t,e)?[t]:o(t);for(var r,p=-1,d=t.length;++p<d;){var h=f(t[p]);if(!(r=null!=e&&n(e,h)))break;e=e[h]}if(r)return r;var d=e?e.length:0;return!!d&&c(d)&&u(h,d)&&(a(e)||l(e)||i(e))}var o=n(111),i=n(128),a=n(11),u=n(39),s=n(40),c=n(43),l=n(129),f=n(26);e.exports=r},function(e,t,n){function r(){this.__data__=o?o(null):{}}var o=n(41);e.exports=r},function(e,t){function n(e){return this.has(e)&&delete this.__data__[e]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__;if(o){var n=t[e];return n===i?void 0:n}return u.call(t,e)?t[e]:void 0}var o=n(41),i="__lodash_hash_undefined__",a=Object.prototype,u=a.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){var t=this.__data__;return o?void 0!==t[e]:a.call(t,e)}var o=n(41),i=Object.prototype,a=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){return this.__data__[e]=o&&void 0===t?i:t,this}var o=n(41),i="__lodash_hash_undefined__";e.exports=r},function(e,t,n){function r(e){var t=e?e.length:void 0;return u(t)&&(a(e)||s(e)||i(e))?o(t,String):null}var o=n(224),i=n(128),a=n(11),u=n(43),s=n(129);e.exports=r},function(e,t,n){function r(e,t,n){if(!u(n))return!1;var r=typeof t;return!!("number"==r?i(n)&&a(t,n.length):"string"==r&&t in n)&&o(n[t],e)}var o=n(126),i=n(42),a=n(39),u=n(15);e.exports=r},function(e,t){function n(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=n},function(e,t,n){function r(e){var t=a(e),n=u[t];if("function"!=typeof n||!(t in o.prototype))return!1;if(e===n)return!0;var r=i(n);return!!r&&e===r[0]}var o=n(56),i=n(118),a=n(236),u=n(289);e.exports=r},function(e,t,n){function r(e){return!!i&&i in e}var o=n(227),i=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=r},function(e,t){function n(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||r)}var r=Object.prototype;e.exports=n},function(e,t){function n(){this.__data__=[]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return!(n<0)&&(n==t.length-1?t.pop():a.call(t,n,1),!0)}var o=n(35),i=Array.prototype,a=i.splice;e.exports=r},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return n<0?void 0:t[n][1]}var o=n(35);e.exports=r},function(e,t,n){function r(e){return o(this.__data__,e)>-1}var o=n(35);e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__,r=o(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}var o=n(35);e.exports=r},function(e,t,n){function r(){this.__data__={hash:new o,map:new(a||i),string:new o}}var o=n(207),i=n(34),a=n(100);e.exports=r},function(e,t,n){function r(e){return o(this,e).delete(e)}var o=n(38);e.exports=r},function(e,t,n){function r(e){return o(this,e).get(e)}var o=n(38);e.exports=r},function(e,t,n){function r(e){return o(this,e).has(e)}var o=n(38);e.exports=r},function(e,t,n){function r(e,t){return o(this,e).set(e,t),this}var o=n(38);e.exports=r},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}e.exports=n},function(e,t,n){function r(e,t){var n=e[1],r=t[1],v=n|r,m=v<(s|c|p),y=r==p&&n==f||r==p&&n==d&&e[7].length<=t[8]||r==(p|d)&&t[7].length<=t[8]&&n==f;if(!m&&!y)return e;r&s&&(e[2]=t[2],v|=n&s?0:l);var g=t[3];if(g){var b=e[3];e[3]=b?o(b,g,t[4]):g,e[4]=b?a(e[3],u):t[4]}return g=t[5],g&&(b=e[5],e[5]=b?i(b,g,t[6]):g,e[6]=b?a(e[5],u):t[6]),g=t[7],g&&(e[7]=g),r&p&&(e[8]=null==e[8]?t[8]:h(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=v,e}var o=n(112),i=n(113),a=n(25),u="__lodash_placeholder__",s=1,c=2,l=4,f=8,p=128,d=256,h=Math.min;e.exports=r},function(e,t){var n={};e.exports=n},function(e,t,n){function r(e,t){for(var n=e.length,r=a(t.length,n),u=o(e);r--;){var s=t[r];e[r]=i(s,n)?u[s]:void 0}return e}var o=n(62),i=n(39),a=Math.min;e.exports=r},function(e,t){function n(e){return this.__data__.set(e,r),this}var r="__lodash_hash_undefined__";e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}e.exports=n},function(e,t,n){function r(){this.__data__=new o}var o=n(34);e.exports=r},function(e,t){function n(e){return this.__data__.delete(e)}e.exports=n},function(e,t){function n(e){return this.__data__.get(e)}e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t,n){function r(e,t){var n=this.__data__;return n instanceof o&&n.__data__.length==a&&(n=this.__data__=new i(n.__data__)),n.set(e,t),this}var o=n(34),i=n(57),a=200;e.exports=r},function(e,t,n){function r(e){if(e instanceof o)return e.clone();var t=new i(e.__wrapped__,e.__chain__);return t.__actions__=a(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var o=n(56),i=n(99),a=n(62);e.exports=r},function(e,t,n){function r(e,t,n){var r=null==e?void 0:o(e,t);return void 0===r?n:r}var o=n(106);e.exports=r},function(e,t,n){function r(e,t){return null!=e&&i(e,t,o)}var o=n(215),i=n(241);e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e)}var o=n(42),i=n(18);e.exports=r},function(e,t,n){function r(e,t,n){n="function"==typeof n?n:void 0;var r=n?n(e,t):void 0;return void 0===r?o(e,t,n):!!r}var o=n(60);e.exports=r},function(e,t,n){function r(e){return i(e)&&o(e.length)&&!!a[s.call(e)]}var o=n(43),i=n(18),a={};a["[object Float32Array]"]=a["[object Float64Array]"]=a["[object Int8Array]"]=a["[object Int16Array]"]=a["[object Int32Array]"]=a["[object Uint8Array]"]=a["[object Uint8ClampedArray]"]=a["[object Uint16Array]"]=a["[object Uint32Array]"]=!0,a["[object Arguments]"]=a["[object Array]"]=a["[object ArrayBuffer]"]=a["[object Boolean]"]=a["[object DataView]"]=a["[object Date]"]=a["[object Error]"]=a["[object Function]"]=a["[object Map]"]=a["[object Number]"]=a["[object Object]"]=a["[object RegExp]"]=a["[object Set]"]=a["[object String]"]=a["[object WeakMap]"]=!1;var u=Object.prototype,s=u.toString;e.exports=r},function(e,t,n){function r(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var a=e.apply(this,r);return n.cache=i.set(o,a),a};return n.cache=new(r.Cache||o),n}var o=n(57),i="Expected a function";r.Cache=o,e.exports=r},function(e,t){function n(){return Date.now()}e.exports=n},function(e,t,n){var r=n(116),o=n(37),i=n(25),a=n(131),u=a(function(e,t){var n=i(t,o(u));return r(e,64,void 0,t,n)});u.placeholder={},e.exports=u},function(e,t,n){function r(e){return a(e)?o(u(e)):i(e)}var o=n(109),i=n(222),a=n(40),u=n(26);e.exports=r},function(e,t,n){function r(e,t,n){var r=u(e)?o:a;return n&&s(e,t,n)&&(t=void 0),r(e,i(t,3))}var o=n(104),i=n(108),a=n(223),u=n(11),s=n(248);e.exports=r},function(e,t,n){function r(e){if(!e)return 0===e?e:0;if((e=o(e))===i||e===-i){return(e<0?-1:1)*a}return e===e?e:0}var o=n(287),i=1/0,a=1.7976931348623157e308;e.exports=r},function(e,t,n){function r(e){if("number"==typeof e)return e;if(a(e))return u;if(i(e)){var t=o(e.valueOf)?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(s,"");var n=l.test(e);return n||f.test(e)?p(e.slice(2),n?2:8):c.test(e)?u:+e}var o=n(64),i=n(15),a=n(27),u=NaN,s=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,f=/^0o[0-7]+$/i,p=parseInt;e.exports=r},function(e,t,n){function r(e){return null==e?"":o(e)}var o=n(225);e.exports=r},function(e,t,n){function r(e){if(s(e)&&!u(e)&&!(e instanceof o)){if(e instanceof i)return e;if(f.call(e,"__wrapped__"))return c(e)}return new i(e)}var o=n(56),i=n(99),a=n(61),u=n(11),s=n(18),c=n(275),l=Object.prototype,f=l.hasOwnProperty;r.prototype=a.prototype,r.prototype.constructor=r,e.exports=r},function(e,t,n){"use strict";e.exports=n(310)},function(e,t,n){"use strict";e.exports=n(321)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0,t.default=void 0;var u=n(5),s=n(133),c=r(s),l=n(134),f=(r(l),function(e){function t(n,r){o(this,t);var a=i(this,e.call(this,n,r));return a.store=n.store,a}return a(t,e),t.prototype.getChildContext=function(){return{store:this.store}},t.prototype.render=function(){var e=this.props.children;return u.Children.only(e)},t}(u.Component));t.default=f,f.propTypes={store:c.default.isRequired,children:u.PropTypes.element.isRequired},f.childContextTypes={store:c.default.isRequired}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){return e.displayName||e.name||"Component"}function s(e,t){try{return e.apply(t)}catch(e){return O.value=e,O}}function c(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],c=Boolean(e),p=e||C,h=void 0;h="function"==typeof t?t:t?(0,y.default)(t):S;var m=n||P,g=r.pure,b=void 0===g||g,_=r.withRef,w=void 0!==_&&_,k=b&&m!==P,A=T++;return function(e){function t(e,t,n){return m(e,t,n)}var n="Connect("+u(e)+")",r=function(r){function u(e,t){o(this,u);var a=i(this,r.call(this,e,t));a.version=A,a.store=e.store||t.store,(0,x.default)(a.store,'Could not find "store" in either the context or props of "'+n+'". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "'+n+'".');var s=a.store.getState();return a.state={storeState:s},a.clearCache(),a}return a(u,r),u.prototype.shouldComponentUpdate=function(){return!b||this.haveOwnPropsChanged||this.hasStoreStateChanged},u.prototype.computeStateProps=function(e,t){if(!this.finalMapStateToProps)return this.configureFinalMapState(e,t);var n=e.getState();return this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(n,t):this.finalMapStateToProps(n)},u.prototype.configureFinalMapState=function(e,t){var n=p(e.getState(),t),r="function"==typeof n;return this.finalMapStateToProps=r?n:p,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,r?this.computeStateProps(e,t):n},u.prototype.computeDispatchProps=function(e,t){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(e,t);var n=e.dispatch;return this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(n,t):this.finalMapDispatchToProps(n)},u.prototype.configureFinalMapDispatch=function(e,t){var n=h(e.dispatch,t),r="function"==typeof n;return this.finalMapDispatchToProps=r?n:h,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,r?this.computeDispatchProps(e,t):n},u.prototype.updateStatePropsIfNeeded=function(){var e=this.computeStateProps(this.store,this.props);return!(this.stateProps&&(0,v.default)(e,this.stateProps)||(this.stateProps=e,0))},u.prototype.updateDispatchPropsIfNeeded=function(){var e=this.computeDispatchProps(this.store,this.props);return!(this.dispatchProps&&(0,v.default)(e,this.dispatchProps)||(this.dispatchProps=e,0))},u.prototype.updateMergedPropsIfNeeded=function(){var e=t(this.stateProps,this.dispatchProps,this.props);return!(this.mergedProps&&k&&(0,v.default)(e,this.mergedProps)||(this.mergedProps=e,0))},u.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},u.prototype.trySubscribe=function(){c&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},u.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},u.prototype.componentDidMount=function(){this.trySubscribe()},u.prototype.componentWillReceiveProps=function(e){b&&(0,v.default)(e,this.props)||(this.haveOwnPropsChanged=!0)},u.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},u.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},u.prototype.handleChange=function(){if(this.unsubscribe){var e=this.store.getState(),t=this.state.storeState;if(!b||t!==e){if(b&&!this.doStatePropsDependOnOwnProps){var n=s(this.updateStatePropsIfNeeded,this);if(!n)return;n===O&&(this.statePropsPrecalculationError=O.value),this.haveStatePropsBeenPrecalculated=!0}this.hasStoreStateChanged=!0,this.setState({storeState:e})}}},u.prototype.getWrappedInstance=function(){return(0,x.default)(w,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},u.prototype.render=function(){var t=this.haveOwnPropsChanged,n=this.hasStoreStateChanged,r=this.haveStatePropsBeenPrecalculated,o=this.statePropsPrecalculationError,i=this.renderedElement;if(this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,o)throw o;var a=!0,u=!0;b&&i&&(a=n||t&&this.doStatePropsDependOnOwnProps,u=t&&this.doDispatchPropsDependOnOwnProps);var s=!1,c=!1;r?s=!0:a&&(s=this.updateStatePropsIfNeeded()),u&&(c=this.updateDispatchPropsIfNeeded());var p=!0;return p=!!(s||c||t)&&this.updateMergedPropsIfNeeded(),!p&&i?i:(this.renderedElement=w?(0,f.createElement)(e,l({},this.mergedProps,{ref:"wrappedInstance"})):(0,f.createElement)(e,this.mergedProps),this.renderedElement)},u}(f.Component);return r.displayName=n,r.WrappedComponent=e,r.contextTypes={store:d.default},r.propTypes={store:d.default},(0,E.default)(r,e)}}var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.__esModule=!0,t.default=c;var f=n(5),p=n(133),d=r(p),h=n(294),v=r(h),m=n(295),y=r(m),g=n(134),b=(r(g),n(65)),_=(r(b),n(98)),E=r(_),w=n(33),x=r(w),C=function(e){return{}},S=function(e){return{dispatch:e}},P=function(e,t,n){return l({},n,e,t)},O={value:null},T=0},function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,i=0;i<n.length;i++)if(!o.call(t,n[i])||e[n[i]]!==t[n[i]])return!1;return!0}t.__esModule=!0,t.default=n},function(e,t,n){"use strict";function r(e){return function(t){return(0,o.bindActionCreators)(e,t)}}t.__esModule=!0,t.default=r;var o=n(175)},function(e,t,n){"use strict";var r=n(4),o=n(95),i={focusDOMComponent:function(){o(r.getNodeFromInstance(this))}};e.exports=i},function(e,t,n){"use strict";function r(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function o(e){switch(e){case O.topCompositionStart:return T.compositionStart;case O.topCompositionEnd:return T.compositionEnd;case O.topCompositionUpdate:return T.compositionUpdate}}function i(e,t){return e===O.topKeyDown&&t.keyCode===_}function a(e,t){switch(e){case O.topKeyUp:return-1!==b.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==_;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function u(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function s(e,t,n,r){var s,c;if(E?s=o(e):A?a(e,n)&&(s=T.compositionEnd):i(e,n)&&(s=T.compositionStart),!s)return null;C&&(A||s!==T.compositionStart?s===T.compositionEnd&&A&&(c=A.getData()):A=v.getPooled(r));var l=m.getPooled(s,t,n,r);if(c)l.data=c;else{var f=u(n);null!==f&&(l.data=f)}return d.accumulateTwoPhaseDispatches(l),l}function c(e,t){switch(e){case O.topCompositionEnd:return u(t);case O.topKeyPress:return t.which!==S?null:(k=!0,P);case O.topTextInput:var n=t.data;return n===P&&k?null:n;default:return null}}function l(e,t){if(A){if(e===O.topCompositionEnd||a(e,t)){var n=A.getData();return v.release(A),A=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!r(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return C?null:t.data;default:return null}}function f(e,t,n,r){var o;if(!(o=x?c(e,n):l(e,n)))return null;var i=y.getPooled(T.beforeInput,t,n,r);return i.data=o,d.accumulateTwoPhaseDispatches(i),i}var p=n(12),d=n(29),h=n(6),v=n(303),m=n(342),y=n(345),g=n(14),b=[9,13,27,32],_=229,E=h.canUseDOM&&"CompositionEvent"in window,w=null;h.canUseDOM&&"documentMode"in document&&(w=document.documentMode);var x=h.canUseDOM&&"TextEvent"in window&&!w&&!function(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}(),C=h.canUseDOM&&(!E||w&&w>8&&w<=11),S=32,P=String.fromCharCode(S),O=p.topLevelTypes,T={beforeInput:{phasedRegistrationNames:{bubbled:g({onBeforeInput:null}),captured:g({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:g({onCompositionEnd:null}),captured:g({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:g({onCompositionStart:null}),captured:g({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:g({onCompositionUpdate:null}),captured:g({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},k=!1,A=null,R={eventTypes:T,extractEvents:function(e,t,n,r){return[s(e,t,n,r),f(e,t,n,r)]}};e.exports=R},function(e,t,n){"use strict";var r=n(135),o=n(6),i=(n(7),n(194),n(351)),a=n(200),u=n(203),s=(n(2),u(function(e){return a(e)})),c=!1,l="cssFloat";if(o.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(e){c=!0}void 0===document.documentElement.style.cssFloat&&(l="styleFloat")}var p={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=s(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var u=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=l),u)o[a]=u;else{var s=c&&r.shorthandPropertyExpansions[a];if(s)for(var f in s)o[f]="";else o[a]=""}}}};e.exports=p},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=C.getPooled(A.change,I,e,S(e));_.accumulateTwoPhaseDispatches(t),x.batchedUpdates(i,t)}function i(e){b.enqueueEvents(e),b.processEventQueue(!1)}function a(e,t){R=e,I=t,R.attachEvent("onchange",o)}function u(){R&&(R.detachEvent("onchange",o),R=null,I=null)}function s(e,t){if(e===k.topChange)return t}function c(e,t,n){e===k.topFocus?(u(),a(t,n)):e===k.topBlur&&u()}function l(e,t){R=e,I=t,N=e.value,M=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(R,"value",D),R.attachEvent?R.attachEvent("onpropertychange",p):R.addEventListener("propertychange",p,!1)}function f(){R&&(delete R.value,R.detachEvent?R.detachEvent("onpropertychange",p):R.removeEventListener("propertychange",p,!1),R=null,I=null,N=null,M=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==N&&(N=t,o(e))}}function d(e,t){if(e===k.topInput)return t}function h(e,t,n){e===k.topFocus?(f(),l(t,n)):e===k.topBlur&&f()}function v(e,t){if((e===k.topSelectionChange||e===k.topKeyUp||e===k.topKeyDown)&&R&&R.value!==N)return N=R.value,I}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function y(e,t){if(e===k.topClick)return t}var g=n(12),b=n(28),_=n(29),E=n(6),w=n(4),x=n(10),C=n(13),S=n(83),P=n(85),O=n(163),T=n(14),k=g.topLevelTypes,A={change:{phasedRegistrationNames:{bubbled:T({onChange:null}),captured:T({onChangeCapture:null})},dependencies:[k.topBlur,k.topChange,k.topClick,k.topFocus,k.topInput,k.topKeyDown,k.topKeyUp,k.topSelectionChange]}},R=null,I=null,N=null,M=null,j=!1;E.canUseDOM&&(j=P("change")&&(!("documentMode"in document)||document.documentMode>8));var F=!1;E.canUseDOM&&(F=P("input")&&(!("documentMode"in document)||document.documentMode>11));var D={get:function(){return M.get.call(this)},set:function(e){N=""+e,M.set.call(this,e)}},U={eventTypes:A,extractEvents:function(e,t,n,o){var i,a,u=t?w.getNodeFromInstance(t):window;if(r(u)?j?i=s:a=c:O(u)?F?i=d:(i=v,a=h):m(u)&&(i=y),i){var l=i(e,t);if(l){var f=C.getPooled(A.change,l,n,o);return f.type="change",_.accumulateTwoPhaseDispatches(f),f}}a&&a(e,u,t)}};e.exports=U},function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=n(23),i=n(6),a=n(197),u=n(9),s=n(97),c=n(1),l="data-danger-index",f={dangerouslyRenderMarkup:function(e){i.canUseDOM||c(!1);for(var t,n={},o=0;o<e.length;o++)e[o]||c(!1),t=r(e[o]),t=s(t)?t:"*",n[t]=n[t]||[],n[t][o]=e[o];var f=[],p=0;for(t in n)if(n.hasOwnProperty(t)){var d,h=n[t];for(d in h)if(h.hasOwnProperty(d)){var v=h[d];h[d]=v.replace(/^(<[^ \/>]+)/,"$1 "+l+'="'+d+'" ')}for(var m=a(h.join(""),u),y=0;y<m.length;++y){var g=m[y];g.hasAttribute&&g.hasAttribute(l)&&(d=+g.getAttribute(l),g.removeAttribute(l),f.hasOwnProperty(d)&&c(!1),f[d]=g,p+=1)}}return p!==f.length&&c(!1),f.length!==e.length&&c(!1),f},dangerouslyReplaceNodeWithMarkup:function(e,t){if(i.canUseDOM||c(!1),t||c(!1),"HTML"===e.nodeName&&c(!1),"string"==typeof t){var n=a(t,u)[0];e.parentNode.replaceChild(n,e)}else o.replaceChildWithTree(e,t)}};e.exports=f},function(e,t,n){"use strict";var r=n(14),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null})];e.exports=o},function(e,t,n){"use strict";var r=n(12),o=n(29),i=n(4),a=n(50),u=n(14),s=r.topLevelTypes,c={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l={eventTypes:c,extractEvents:function(e,t,n,r){if(e===s.topMouseOver&&(n.relatedTarget||n.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var u;if(r.window===r)u=r;else{var l=r.ownerDocument;u=l?l.defaultView||l.parentWindow:window}var f,p;if(e===s.topMouseOut){f=t;var d=n.relatedTarget||n.toElement;p=d?i.getClosestInstanceFromNode(d):null}else f=null,p=t;if(f===p)return null;var h=null==f?u:i.getNodeFromInstance(f),v=null==p?u:i.getNodeFromInstance(p),m=a.getPooled(c.mouseLeave,f,n,r);m.type="mouseleave",m.target=h,m.relatedTarget=v;var y=a.getPooled(c.mouseEnter,p,n,r);return y.type="mouseenter",y.target=v,y.relatedTarget=h,o.accumulateEnterLeaveDispatches(m,y,f,p),[m,y]}};e.exports=l},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(3),i=n(16),a=n(162);o(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(19),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_SIDE_EFFECTS,u=r.injection.HAS_NUMERIC_VALUE,s=r.injection.HAS_POSITIVE_NUMERIC_VALUE,c=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,l={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:s,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,default:i,defer:i,dir:0,disabled:i,download:c,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,rel:0,required:i,reversed:i,role:0,rows:s,rowSpan:u,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:s,sizes:0,span:s,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:u,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:o|a,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};e.exports=l},function(e,t,n){"use strict";function r(e,t,n){var r=void 0===e[n];null!=t&&r&&(e[n]=i(t))}var o=n(21),i=n(84),a=(n(73),n(87)),u=n(88),s=(n(2),{instantiateChildren:function(e,t,n){if(null==e)return null;var o={};return u(e,r,o),o},updateChildren:function(e,t,n,r,u){if(t||e){var s,c;for(s in t)if(t.hasOwnProperty(s)){c=e&&e[s];var l=c&&c._currentElement,f=t[s];if(null!=c&&a(l,f))o.receiveComponent(c,f,r,u),t[s]=c;else{c&&(n[s]=o.getNativeNode(c),o.unmountComponent(c,!1));var p=i(f);t[s]=p}}for(s in e)!e.hasOwnProperty(s)||t&&t.hasOwnProperty(s)||(c=e[s],n[s]=o.getNativeNode(c),o.unmountComponent(c,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];o.unmountComponent(r,t)}}});e.exports=s},function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);y(e,i,r),o.release(r)}function u(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function s(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,u=e.context,s=a.call(u,t,e.count++);Array.isArray(s)?c(s,o,n,m.thatReturnsArgument):null!=s&&(v.isValidElement(s)&&(s=v.cloneAndReplaceKey(s,i+(!s.key||t&&t.key===s.key?"":r(s.key)+"/")+n)),o.push(s))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=u.getPooled(t,a,o,i);y(e,s,c),u.release(c)}function l(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function f(e,t,n){return null}function p(e,t){return y(e,f,null)}function d(e){var t=[];return c(e,t,null,m.thatReturnsArgument),t}var h=n(16),v=n(17),m=n(9),y=n(88),g=h.twoArgumentPooler,b=h.fourArgumentPooler,_=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(o,g),u.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(u,b);var E={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:p,toArray:d};e.exports=E},function(e,t,n){"use strict";function r(e,t){var n=w.hasOwnProperty(t)?w[t]:null;C.hasOwnProperty(t)&&n!==_.OVERRIDE_BASE&&m(!1),e&&n!==_.DEFINE_MANY&&n!==_.DEFINE_MANY_MERGED&&m(!1)}function o(e,t){if(t){"function"==typeof t&&m(!1),d.isValidElement(t)&&m(!1);var n=e.prototype,o=n.__reactAutoBindPairs;t.hasOwnProperty(b)&&x.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==b){var a=t[i],c=n.hasOwnProperty(i);if(r(c,i),x.hasOwnProperty(i))x[i](e,a);else{var l=w.hasOwnProperty(i),f="function"==typeof a,p=f&&!l&&!c&&!1!==t.autobind;if(p)o.push(i,a),n[i]=a;else if(c){var h=w[i];(!l||h!==_.DEFINE_MANY_MERGED&&h!==_.DEFINE_MANY)&&m(!1),h===_.DEFINE_MANY_MERGED?n[i]=u(n[i],a):h===_.DEFINE_MANY&&(n[i]=s(n[i],a))}else n[i]=a}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in x;o&&m(!1);var i=n in e;i&&m(!1),e[n]=r}}}function a(e,t){e&&t&&"object"==typeof e&&"object"==typeof t||m(!1);for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]&&m(!1),e[n]=t[n]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function s(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function c(e,t){return t.bind(e)}function l(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=c(e,o)}}var f=n(3),p=n(308),d=n(17),h=(n(79),n(78),n(152)),v=n(24),m=n(1),y=n(32),g=n(14),b=(n(2),g({mixins:null})),_=y({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),E=[],w={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},x={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=f({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=f({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=f({},e.propTypes,t)},statics:function(e,t){i(e,t)},autobind:function(){}},C={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},S=function(){};f(S.prototype,p.prototype,C);var P={createClass:function(e){var t=function(e,t,n){this.__reactAutoBindPairs.length&&l(this),this.props=e,this.context=t,this.refs=v,this.updater=n||h,this.state=null;var r=this.getInitialState?this.getInitialState():null;("object"!=typeof r||Array.isArray(r))&&m(!1),this.state=r};t.prototype=new S,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],E.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render||m(!1);for(var n in w)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){E.push(e)}}};e.exports=P},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=i,this.updater=n||o}var o=n(152),i=(n(7),n(158),n(24)),a=n(1);n(2),r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&a(!1),this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")},e.exports=r},function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function o(e){}function i(e){return e.prototype&&e.prototype.isReactComponent}var a=n(3),u=n(75),s=n(20),c=n(17),l=n(76),f=n(77),p=(n(7),n(151)),d=n(79),h=(n(78),n(21)),v=n(154),m=n(24),y=n(1),g=n(87);n(2),o.prototype.render=function(){var e=f.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return t};var b=1,_={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._nativeParent=null,this._nativeContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1},mountComponent:function(e,t,n,r){this._context=r,this._mountOrder=b++,this._nativeParent=t,this._nativeContainerInfo=n;var a,u=this._processProps(this._currentElement.props),s=this._processContext(r),l=this._currentElement.type,p=this._constructComponent(u,s);i(l)||null!=p&&null!=p.render||(a=p,null===p||!1===p||c.isValidElement(p)||y(!1),p=new o(l)),p.props=u,p.context=s,p.refs=m,p.updater=v,this._instance=p,f.set(p,this);var d=p.state;void 0===d&&(p.state=d=null),("object"!=typeof d||Array.isArray(d))&&y(!1),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var h;return h=p.unstable_handleError?this.performInitialMountWithErrorHandling(a,t,n,e,r):this.performInitialMount(a,t,n,e,r),p.componentDidMount&&e.getReactMountReady().enqueue(p.componentDidMount,p),h},_constructComponent:function(e,t){return this._constructComponentWithoutOwner(e,t)},_constructComponentWithoutOwner:function(e,t){var n=this._currentElement.type;return i(n)?new n(e,t,v):n(e,t,v)},performInitialMountWithErrorHandling:function(e,t,n,r,o){var i,a=r.checkpoint();try{i=this.performInitialMount(e,t,n,r,o)}catch(u){r.rollback(a),this._instance.unstable_handleError(u),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),i=this.performInitialMount(e,t,n,r,o)}return i},performInitialMount:function(e,t,n,r,o){var i=this._instance;return i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===e&&(e=this._renderValidatedComponent()),this._renderedNodeType=p.getType(e),this._renderedComponent=this._instantiateReactComponent(e),h.mountComponent(this._renderedComponent,r,t,n,this._processChildContext(o))},getNativeNode:function(){return h.getNativeNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";l.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(h.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,this._renderedComponent=null,this._instance=null),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,f.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return m;var r={};for(var o in n)r[o]=e[o];return r},_processContext:function(e){return this._maskContext(e)},_processChildContext:function(e){var t=this._currentElement.type,n=this._instance,r=n.getChildContext&&n.getChildContext();if(r){"object"!=typeof t.childContextTypes&&y(!1);for(var o in r)o in t.childContextTypes||y(!1);return a({},e,r)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{"function"!=typeof e[i]&&y(!1),a=e[i](t,i,o,n)}catch(e){a=e}a instanceof Error&&(r(this),d.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement?h.receiveComponent(this,this._pendingElement,e,this._context):null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null},updateComponent:function(e,t,n,r,o){var i,a,u=this._instance,s=!1;this._context===o?i=u.context:(i=this._processContext(o),s=!0),t===n?a=n.props:(a=this._processProps(n.props),s=!0),s&&u.componentWillReceiveProps&&u.componentWillReceiveProps(a,i);var c=this._processPendingState(a,i),l=!0;!this._pendingForceUpdate&&u.shouldComponentUpdate&&(l=u.shouldComponentUpdate(a,c,i)),this._updateBatchNumber=null,l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,a,c,i,e,o)):(this._currentElement=n,this._context=o,u.props=a,u.state=c,u.context=i)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=a({},o?r[0]:n.state),u=o?1:0;u<r.length;u++){var s=r[u];a(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,u,s,c=this._instance,l=Boolean(c.componentDidUpdate);l&&(a=c.props,u=c.state,s=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(o,i),l&&o.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,u,s),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(g(r,o))h.receiveComponent(n,o,e,this._processChildContext(t));else{var i=h.getNativeNode(n);h.unmountComponent(n,!1),this._renderedNodeType=p.getType(o),this._renderedComponent=this._instantiateReactComponent(o);var a=h.mountComponent(this._renderedComponent,e,this._nativeParent,this._nativeContainerInfo,this._processChildContext(t));this._replaceNodeWithMarkup(i,a,n)}},_replaceNodeWithMarkup:function(e,t,n){u.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){return this._instance.render()},_renderValidatedComponent:function(){var e;s.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{s.current=null}return null===e||!1===e||c.isValidElement(e)||y(!1),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n&&y(!1);var r=t.getPublicInstance();(n.refs===m?n.refs={}:n.refs)[e]=r},detachRef:function(e){delete this.getPublicInstance().refs[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return e instanceof o?null:e},_instantiateReactComponent:null},E={Mixin:_};e.exports=E},function(e,t,n){"use strict";var r=n(4),o=n(143),i=n(148),a=n(21),u=n(10),s=n(155),c=n(352),l=n(161),f=n(358);n(2),o.inject();var p={findDOMNode:c,render:i.render,unmountComponentAtNode:i.unmountComponentAtNode,version:s,unstable_batchedUpdates:u.batchedUpdates,unstable_renderSubtreeIntoContainer:f};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:r.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=l(e)),e?r.getNodeFromInstance(e):null}},Mount:i,Reconciler:a}),e.exports=p},function(e,t,n){"use strict";var r=n(47),o={getNativeProps:r.getNativeProps};e.exports=o},function(e,t,n){"use strict";function r(e,t){t&&($[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&M(!1),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&M(!1),"object"==typeof t.dangerouslySetInnerHTML&&q in t.dangerouslySetInnerHTML||M(!1)),null!=t.style&&"object"!=typeof t.style&&M(!1))}function o(e,t,n,r){if(!(r instanceof I)){var o=e._nativeContainerInfo,a=o._node&&o._node.nodeType===z,u=a?o._node:o._ownerDocument;L(t,u),r.getReactMountReady().enqueue(i,{inst:e,registrationName:t,listener:n})}}function i(){var e=this;_.putListener(e.inst,e.registrationName,e.listener)}function a(){var e=this;T.postMountWrapper(e)}function u(){var e=this;e._rootNodeID||M(!1);var t=U(e);switch(t||M(!1),e._tag){case"iframe":case"object":e._wrapperState.listeners=[w.trapBubbledEvent(b.topLevelTypes.topLoad,"load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in Y)Y.hasOwnProperty(n)&&e._wrapperState.listeners.push(w.trapBubbledEvent(b.topLevelTypes[n],Y[n],t));break;case"img":e._wrapperState.listeners=[w.trapBubbledEvent(b.topLevelTypes.topError,"error",t),w.trapBubbledEvent(b.topLevelTypes.topLoad,"load",t)];break;case"form":e._wrapperState.listeners=[w.trapBubbledEvent(b.topLevelTypes.topReset,"reset",t),w.trapBubbledEvent(b.topLevelTypes.topSubmit,"submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[w.trapBubbledEvent(b.topLevelTypes.topInvalid,"invalid",t)]}}function s(){k.postUpdateWrapper(this)}function c(e){J.call(Q,e)||(X.test(e)||M(!1),Q[e]=!0)}function l(e,t){return e.indexOf("-")>=0||null!=t.is}function f(e){var t=e.type;c(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._nativeNode=null,this._nativeParent=null,this._rootNodeID=null,this._domID=null,this._nativeContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var p=n(3),d=n(296),h=n(298),v=n(23),m=n(137),y=n(19),g=n(71),b=n(12),_=n(28),E=n(48),w=n(49),x=n(138),C=n(311),S=n(139),P=n(4),O=n(317),T=n(319),k=n(141),A=n(323),R=(n(7),n(330)),I=n(153),N=(n(9),n(52)),M=n(1),j=(n(85),n(14)),F=(n(54),n(89),n(2),S),D=_.deleteListener,U=P.getNodeFromInstance,L=w.listenTo,V=E.registrationNameModules,B={string:!0,number:!0},W=j({style:null}),q=j({__html:null}),H={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},z=11,Y={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},K={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},G={listing:!0,pre:!0,textarea:!0},$=p({menuitem:!0},K),X=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Q={},J={}.hasOwnProperty,Z=1;f.displayName="ReactDOMComponent",f.Mixin={mountComponent:function(e,t,n,o){this._rootNodeID=Z++,this._domID=n._idCounter++,this._nativeParent=t,this._nativeContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"iframe":case"object":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(u,this);break;case"button":i=C.getNativeProps(this,i,t);break;case"input":O.mountWrapper(this,i,t),i=O.getNativeProps(this,i),e.getReactMountReady().enqueue(u,this);break;case"option":T.mountWrapper(this,i,t),i=T.getNativeProps(this,i);break;case"select":k.mountWrapper(this,i,t),i=k.getNativeProps(this,i),e.getReactMountReady().enqueue(u,this);break;case"textarea":A.mountWrapper(this,i,t),i=A.getNativeProps(this,i),e.getReactMountReady().enqueue(u,this)}r(this,i);var s,c;null!=t?(s=t._namespaceURI,c=t._tag):n._tag&&(s=n._namespaceURI,c=n._tag),(null==s||s===m.svg&&"foreignobject"===c)&&(s=m.html),s===m.html&&("svg"===this._tag?s=m.svg:"math"===this._tag&&(s=m.mathml)),this._namespaceURI=s;var l;if(e.useCreateElement){var f,p=n._ownerDocument;if(s===m.html)if("script"===this._tag){var h=p.createElement("div"),y=this._currentElement.type;h.innerHTML="<"+y+"></"+y+">",f=h.removeChild(h.firstChild)}else f=p.createElement(this._currentElement.type,i.is||null);else f=p.createElementNS(s,this._currentElement.type);P.precacheNode(this,f),this._flags|=F.hasCachedChildNodes,this._nativeParent||g.setAttributeForRoot(f),this._updateDOMProperties(null,i,e);var b=v(f);this._createInitialChildren(e,i,o,b),l=b}else{var _=this._createOpenTagMarkupAndPutListeners(e,i),E=this._createContentMarkup(e,i,o);l=!E&&K[this._tag]?_+"/>":_+">"+E+"</"+this._currentElement.type+">"}switch(this._tag){case"button":case"input":case"select":case"textarea":i.autoFocus&&e.getReactMountReady().enqueue(d.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(a,this)}return l},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(V.hasOwnProperty(r))i&&o(this,r,i,e);else{r===W&&(i&&(i=this._previousStyleCopy=p({},t.style)),i=h.createMarkupForStyles(i,this));var a=null;null!=this._tag&&l(this._tag,t)?H.hasOwnProperty(r)||(a=g.createMarkupForCustomAttribute(r,i)):a=g.createMarkupForProperty(r,i),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._nativeParent||(n+=" "+g.createMarkupForRoot()),n+=" "+g.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=B[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=N(i);else if(null!=a){var u=this.mountChildren(a,e,n);r=u.join("")}}return G[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&v.queueHTML(r,o.__html);else{var i=B[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)v.queueText(r,i);else if(null!=a)for(var u=this.mountChildren(a,e,n),s=0;s<u.length;s++)v.queueChild(r,u[s])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,o){var i=t.props,a=this._currentElement.props;switch(this._tag){case"button":i=C.getNativeProps(this,i),a=C.getNativeProps(this,a);break;case"input":O.updateWrapper(this),i=O.getNativeProps(this,i),a=O.getNativeProps(this,a);break;case"option":i=T.getNativeProps(this,i),a=T.getNativeProps(this,a);break;case"select":i=k.getNativeProps(this,i),a=k.getNativeProps(this,a);break;case"textarea":A.updateWrapper(this),i=A.getNativeProps(this,i),a=A.getNativeProps(this,a)}r(this,a),this._updateDOMProperties(i,a,e),this._updateDOMChildren(i,a,e,o),"select"===this._tag&&e.getReactMountReady().enqueue(s,this)},_updateDOMProperties:function(e,t,n){var r,i,a;for(r in e)if(!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&null!=e[r])if(r===W){var u=this._previousStyleCopy;for(i in u)u.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else V.hasOwnProperty(r)?e[r]&&D(this,r):(y.properties[r]||y.isCustomAttribute(r))&&g.deleteValueForProperty(U(this),r);for(r in t){var s=t[r],c=r===W?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&s!==c&&(null!=s||null!=c))if(r===W)if(s?s=this._previousStyleCopy=p({},s):this._previousStyleCopy=null,c){for(i in c)!c.hasOwnProperty(i)||s&&s.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in s)s.hasOwnProperty(i)&&c[i]!==s[i]&&(a=a||{},a[i]=s[i])}else a=s;else if(V.hasOwnProperty(r))s?o(this,r,s,n):c&&D(this,r);else if(l(this._tag,t))H.hasOwnProperty(r)||g.setValueForAttribute(U(this),r,s);else if(y.properties[r]||y.isCustomAttribute(r)){var f=U(this);null!=s?g.setValueForProperty(f,r,s):g.deleteValueForProperty(f,r)}}a&&h.setValueForStyles(U(this),a,this)},_updateDOMChildren:function(e,t,n,r){var o=B[typeof e.children]?e.children:null,i=B[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,c=null!=i?null:t.children,l=null!=o||null!=a,f=null!=i||null!=u;null!=s&&null==c?this.updateChildren(null,n,r):l&&!f&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=u?a!==u&&this.updateMarkup(""+u):null!=c&&this.updateChildren(c,n,r)},getNativeNode:function(){return U(this)},unmountComponent:function(e){switch(this._tag){case"iframe":case"object":case"img":case"form":case"video":case"audio":var t=this._wrapperState.listeners;if(t)for(var n=0;n<t.length;n++)t[n].remove();break;case"html":case"head":case"body":M(!1)}this.unmountChildren(e),P.uncacheNode(this),_.deleteAllListeners(this),x.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._domID=null,this._wrapperState=null},getPublicInstance:function(){return U(this)}},p(f.prototype,f.Mixin,R.Mixin),e.exports=f},function(e,t,n){"use strict";var r=n(325),o=(n(2),[]),i={addDevtool:function(e){o.push(e)},removeDevtool:function(e){for(var t=0;t<o.length;t++)o[t]===e&&(o.splice(t,1),t--)},onCreateMarkupForProperty:function(e,t){},onSetValueForProperty:function(e,t,n){},onDeleteValueForProperty:function(e,t){}};i.addDevtool(r),e.exports=i},function(e,t,n){"use strict";var r=n(3),o=n(23),i=n(4),a=function(e){this._currentElement=null,this._nativeNode=null,this._nativeParent=null,this._nativeContainerInfo=null,this._domID=null};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._nativeParent=t,this._nativeContainerInfo=n;var u=" react-empty: "+this._domID+" ";if(e.useCreateElement){var s=n._ownerDocument,c=s.createComment(u);return i.precacheNode(this,c),o(c)}return e.renderToStaticMarkup?"":"<!--"+u+"-->"},receiveComponent:function(){},getNativeNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),e.exports=a},function(e,t){"use strict";var n={useCreateElement:!0};e.exports=n},function(e,t,n){"use strict";var r=n(70),o=n(4),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};e.exports=i},function(e,t,n){"use strict";function r(){this._rootNodeID&&p.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);l.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var i=c.getNodeFromInstance(this),a=i;a.parentNode;)a=a.parentNode;for(var u=a.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),p=0;p<u.length;p++){var d=u[p];if(d!==i&&d.form===i.form){var h=c.getInstanceFromNode(d);h||f(!1),l.asap(r,h)}}}return n}var i=n(3),a=n(47),u=n(71),s=n(74),c=n(4),l=n(10),f=n(1),p=(n(2),{getNativeProps:function(e,t){var n=s.getValue(t),r=s.getChecked(t);return i({type:void 0},a.getNativeProps(e,t),{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:t.defaultChecked||!1,initialValue:null!=n?n:null,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&u.setValueForProperty(c.getNodeFromInstance(e),"checked",n||!1);var r=s.getValue(t);null!=r&&u.setValueForProperty(c.getNodeFromInstance(e),"value",""+r)}});e.exports=p},function(e,t,n){"use strict";var r=n(313);e.exports={debugTool:r}},function(e,t,n){"use strict";var r=n(3),o=n(306),i=n(4),a=n(141),u=(n(2),{mountWrapper:function(e,t,n){var r=null;if(null!=n){var o=n;"optgroup"===o._tag&&(o=o._nativeParent),null!=o&&"select"===o._tag&&(r=a.getSelectValueContext(o))}var i=null;if(null!=r)if(i=!1,Array.isArray(r)){for(var u=0;u<r.length;u++)if(""+r[u]==""+t.value){i=!0;break}}else i=""+r==""+t.value;e._wrapperState={selected:i}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){i.getNodeFromInstance(e).setAttribute("value",t.value)}},getNativeProps:function(e,t){var n=r({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var i="";return o.forEach(t.children,function(e){null!=e&&("string"!=typeof e&&"number"!=typeof e||(i+=e))}),i&&(n.children=i),n}});e.exports=u},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length;return{start:i,end:i+r}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,u=t.getRangeAt(0);try{u.startContainer.nodeType,u.endContainer.nodeType}catch(e){return null}var s=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=s?0:u.toString().length,l=u.cloneRange();l.selectNodeContents(e),l.setEnd(u.startContainer,u.startOffset);var f=r(l.startContainer,l.startOffset,l.endContainer,l.endOffset),p=f?0:l.toString().length,d=p+c,h=document.createRange();h.setStart(n,o),h.setEnd(i,a);var v=h.collapsed;return{start:v?d:p,end:v?p:d}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();void 0===t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,o=Math.min(t.start,r),i=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var u=c(e,o),s=c(e,i);if(u&&s){var f=document.createRange();f.setStart(u.node,u.offset),n.removeAllRanges(),o>i?(n.addRange(f),n.extend(s.node,s.offset)):(f.setEnd(s.node,s.offset),n.addRange(f))}}}var s=n(6),c=n(355),l=n(162),f=s.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:f?o:i,setOffsets:f?a:u};e.exports=p},function(e,t,n){"use strict";var r=n(143),o=n(336),i=n(155);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){"use strict";var r=n(3),o=n(70),i=n(23),a=n(4),u=(n(7),n(52)),s=n(1),c=(n(89),function(e){this._currentElement=e,this._stringText=""+e,this._nativeNode=null,this._nativeParent=null,this._domID=null,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});r(c.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,s=" react-text: "+o+" ",c=" /react-text ";if(this._domID=o,this._nativeParent=t,e.useCreateElement){var l=n._ownerDocument,f=l.createComment(s),p=l.createComment(c),d=i(l.createDocumentFragment());return i.queueChild(d,i(f)),this._stringText&&i.queueChild(d,i(l.createTextNode(this._stringText))),i.queueChild(d,i(p)),a.precacheNode(this,f),this._closingComment=p,d}var h=u(this._stringText);return e.renderToStaticMarkup?h:"<!--"+s+"-->"+h+"<!--"+c+"-->"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getNativeNode();o.replaceDelimitedText(r[0],r[1],n)}}},getNativeNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=a.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n&&s(!1),8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._nativeNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,a.uncacheNode(this)}}),e.exports=c},function(e,t,n){"use strict";function r(){this._rootNodeID&&p.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return l.asap(r,this),n}var i=n(3),a=n(47),u=n(71),s=n(74),c=n(4),l=n(10),f=n(1),p=(n(2),{getNativeProps:function(e,t){return null!=t.dangerouslySetInnerHTML&&f(!1),i({},a.getNativeProps(e,t),{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=t.defaultValue,r=t.children;null!=r&&(null!=n&&f(!1),Array.isArray(r)&&(r.length<=1||f(!1),r=r[0]),n=""+r),null==n&&(n="");var i=s.getValue(t);e._wrapperState={initialValue:""+(null!=i?i:n),listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=s.getValue(t);null!=n&&u.setValueForProperty(c.getNodeFromInstance(e),"value",""+n)}});e.exports=p},function(e,t,n){"use strict";function r(e,t){"_nativeNode"in e||s(!1),"_nativeNode"in t||s(!1);for(var n=0,r=e;r;r=r._nativeParent)n++;for(var o=0,i=t;i;i=i._nativeParent)o++;for(;n-o>0;)e=e._nativeParent,n--;for(;o-n>0;)t=t._nativeParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._nativeParent,t=t._nativeParent}return null}function o(e,t){"_nativeNode"in e||s(!1),"_nativeNode"in t||s(!1);for(;t;){if(t===e)return!0;t=t._nativeParent}return!1}function i(e){return"_nativeNode"in e||s(!1),e._nativeParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._nativeParent;var o;for(o=r.length;o-- >0;)t(r[o],!1,n);for(o=0;o<r.length;o++)t(r[o],!0,n)}function u(e,t,n,o,i){for(var a=e&&t?r(e,t):null,u=[];e&&e!==a;)u.push(e),e=e._nativeParent;for(var s=[];t&&t!==a;)s.push(t),t=t._nativeParent;var c;for(c=0;c<u.length;c++)n(u[c],!0,o);for(c=s.length;c-- >0;)n(s[c],!1,i)}var s=n(1);e.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:u}},function(e,t,n){"use strict";var r,o=(n(19),n(48),n(2),{onCreateMarkupForProperty:function(e,t){r(e)},onSetValueForProperty:function(e,t,n){r(t)},onDeleteValueForProperty:function(e,t){r(t)}});e.exports=o},function(e,t,n){"use strict";var r=(n(6),n(205),n(2),[]),o={addDevtool:function(e){r.push(e)},removeDevtool:function(e){for(var t=0;t<r.length;t++)r[t]===e&&(r.splice(t,1),t--)},beginProfiling:function(){},endProfiling:function(){},getFlushHistory:function(){},onBeginFlush:function(){},onEndFlush:function(){},onBeginLifeCycleTimer:function(e,t){},onEndLifeCycleTimer:function(e,t){},onBeginReconcilerTimer:function(e,t){},onEndReconcilerTimer:function(e,t){},onBeginProcessingChildContext:function(){},onEndProcessingChildContext:function(){},onNativeOperation:function(e,t,n){},onSetState:function(){},onSetDisplayName:function(e,t){},onSetChildren:function(e,t){},onSetOwner:function(e,t){},onSetText:function(e,t){},onMountRootComponent:function(e){},onMountComponent:function(e){},onUpdateComponent:function(e){},onUnmountComponent:function(e){}};e.exports=o},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(28),i={handleTopLevel:function(e,t,n,i){r(o.extractEvents(e,t,n,i))}};e.exports=i},function(e,t,n){"use strict";function r(e){for(;e._nativeParent;)e=e._nativeParent;var t=f.getNodeFromInstance(e),n=t.parentNode;return f.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=d(e.nativeEvent),n=f.getClosestInstanceFromNode(t),o=n;do{e.ancestors.push(o),o=o&&r(o)}while(o);for(var i=0;i<e.ancestors.length;i++)n=e.ancestors[i],v._handleTopLevel(e.topLevelType,n,e.nativeEvent,d(e.nativeEvent))}function a(e){e(h(window))}var u=n(3),s=n(94),c=n(6),l=n(16),f=n(4),p=n(10),d=n(83),h=n(198);u(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?s.listen(r,t,v.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?s.capture(r,t,v.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(v._enabled){var n=o.getPooled(e,t);try{p.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=v},function(e,t,n){"use strict";var r=n(19),o=n(28),i=n(72),a=n(75),u=n(307),s=n(144),c=n(49),l=n(150),f=n(10),p={Component:a.injection,Class:u.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:o.injection,EventPluginUtils:i.injection,EventEmitter:c.injection,NativeComponent:l.injection,Updates:f.injection};e.exports=p},function(e,t,n){"use strict";function r(e,t,n){return{type:f.INSERT_MARKUP,content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:f.MOVE_EXISTING,content:null,fromIndex:e._mountIndex,fromNode:p.getNativeNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:f.REMOVE_NODE,content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:f.SET_MARKUP,content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e){return{type:f.TEXT_CONTENT,content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function s(e,t){return t&&(e=e||[],e.push(t)),e}function c(e,t){l.processChildrenUpdates(e,t)}var l=n(75),f=(n(7),n(149)),p=(n(20),n(21)),d=n(305),h=(n(9),n(353)),v=n(1),m={Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return d.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o){var i;return i=h(t),d.updateChildren(e,i,n,r,o),i},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=p.mountComponent(u,t,this,this._nativeContainerInfo,n);u._mountIndex=i++,o.push(s)}return o},updateTextContent:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&v(!1);c(this,[u(e)])},updateMarkup:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&v(!1);c(this,[a(e)])},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=this._reconcilerUpdateChildren(r,e,o,t,n);if(i||r){var a,u=null,l=0,f=0,d=null;for(a in i)if(i.hasOwnProperty(a)){var h=r&&r[a],v=i[a];h===v?(u=s(u,this.moveChild(h,d,f,l)),l=Math.max(h._mountIndex,l),h._mountIndex=f):(h&&(l=Math.max(h._mountIndex,l)),u=s(u,this._mountChildAtIndex(v,d,f,t,n))),f++,d=p.getNativeNode(v)}for(a in o)o.hasOwnProperty(a)&&(u=s(u,this._unmountChild(r[a],o[a])));u&&c(this,u),this._renderedChildren=i}},unmountChildren:function(e){var t=this._renderedChildren;d.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){if(e._mountIndex<r)return o(e,t,n)},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return i(e,t)},_mountChildAtIndex:function(e,t,n,r,o){var i=p.mountComponent(e,r,this,this._nativeContainerInfo,o);return e._mountIndex=n,this.createChild(e,t,i)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}};e.exports=m},function(e,t,n){"use strict";var r=n(1),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){o.isValidOwner(n)||r(!1),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){o.isValidOwner(n)||r(!1);var i=n.getPublicInstance();i&&i.refs[t]===e.getPublicInstance()&&n.detachRef(t)}};e.exports=o},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e==1/t:e!==e&&t!==t}function o(e){function t(t,n,r,o,i,a){if(o=o||_,a=a||r,null==n[r]){var u=y[i];return t?new Error("Required "+u+" `"+a+"` was not specified in `"+o+"`."):null}return e(n,r,o,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function i(e){function t(t,n,r,o,i){var a=t[n];if(d(a)!==e){var u=y[o],s=h(a);return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` supplied to `"+r+"`, expected `"+e+"`.")}return null}return o(t)}function a(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var a=t[n];if(!Array.isArray(a)){var u=y[o],s=d(a);return new Error("Invalid "+u+" `"+i+"` of type `"+s+"` supplied to `"+r+"`, expected an array.")}for(var c=0;c<a.length;c++){var l=e(a,c,r,o,i+"["+c+"]");if(l instanceof Error)return l}return null}return o(t)}function u(e){function t(t,n,r,o,i){if(!(t[n]instanceof e)){var a=y[o],u=e.name||_,s=v(t[n]);return new Error("Invalid "+a+" `"+i+"` of type `"+s+"` supplied to `"+r+"`, expected instance of `"+u+"`.")}return null}return o(t)}function s(e){function t(t,n,o,i,a){for(var u=t[n],s=0;s<e.length;s++)if(r(u,e[s]))return null;var c=y[i],l=JSON.stringify(e);return new Error("Invalid "+c+" `"+a+"` of value `"+u+"` supplied to `"+o+"`, expected one of "+l+".")}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function c(e){function t(t,n,r,o,i){if("function"!=typeof e)return new Error("Property `"+i+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var a=t[n],u=d(a);if("object"!==u){var s=y[o];return new Error("Invalid "+s+" `"+i+"` of type `"+u+"` supplied to `"+r+"`, expected an object.")}for(var c in a)if(a.hasOwnProperty(c)){var l=e(a,c,r,o,i+"."+c);if(l instanceof Error)return l}return null}return o(t)}function l(e){function t(t,n,r,o,i){for(var a=0;a<e.length;a++){if(null==(0,e[a])(t,n,r,o,i))return null}var u=y[o];return new Error("Invalid "+u+" `"+i+"` supplied to `"+r+"`.")}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function f(e){function t(t,n,r,o,i){var a=t[n],u=d(a);if("object"!==u){var s=y[o];return new Error("Invalid "+s+" `"+i+"` of type `"+u+"` supplied to `"+r+"`, expected `object`.")}for(var c in e){var l=e[c];if(l){var f=l(a,c,r,o,i+"."+c);if(f)return f}}return null}return o(t)}function p(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(p);if(null===e||m.isValidElement(e))return!0;var t=b(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!p(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!p(o[1]))return!1}return!0;default:return!1}}function d(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function h(e){var t=d(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function v(e){return e.constructor&&e.constructor.name?e.constructor.name:_}var m=n(17),y=n(78),g=n(9),b=n(160),_="<<anonymous>>",E={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),any:function(){return o(g.thatReturns(null))}(),arrayOf:a,element:function(){function e(e,t,n,r,o){if(!m.isValidElement(e[t])){var i=y[r];return new Error("Invalid "+i+" `"+o+"` supplied to `"+n+"`, expected a single ReactElement.")}return null}return o(e)}(),instanceOf:u,node:function(){function e(e,t,n,r,o){if(!p(e[t])){var i=y[r];return new Error("Invalid "+i+" `"+o+"` supplied to `"+n+"`, expected a ReactNode.")}return null}return o(e)}(),objectOf:c,oneOf:s,oneOfType:l,shape:f};e.exports=E},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.useCreateElement=e}var o=n(3),i=n(136),a=n(16),u=n(49),s=n(146),c=n(51),l={initialize:s.getSelectionInformation,close:s.restoreSelection},f={initialize:function(){var e=u.isEnabled();return u.setEnabled(!1),e},close:function(e){u.setEnabled(e)}},p={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},d=[l,f,p],h={getTransactionWrappers:function(){return d},getReactMountReady:function(){return this.reactMountReady},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};o(r.prototype,c.Mixin,h),a.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(331),a={};a.attachRefs=function(e,t){if(null!==t&&!1!==t){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||!1===e,r=null===t||!1===t;return n||r||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&!1!==t){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t){"use strict";var n={isBatchingUpdates:!1,batchedUpdates:function(e){}};e.exports=n},function(e,t,n){"use strict";function r(e,t){var n;try{return d.injection.injectBatchingStrategy(f),n=p.getPooled(t),n.perform(function(){var r=v(e),o=l.mountComponent(r,n,null,a(),h);return t||(o=c.addChecksumToMarkup(o)),o},null)}finally{p.release(n),d.injection.injectBatchingStrategy(u)}}function o(e){return s.isValidElement(e)||m(!1),r(e,!1)}function i(e){return s.isValidElement(e)||m(!1),r(e,!0)}var a=n(140),u=n(142),s=n(17),c=(n(7),n(147)),l=n(21),f=n(335),p=n(153),d=n(10),h=n(24),v=n(84),m=n(1);e.exports={renderToString:o,renderToStaticMarkup:i}},function(e,t){"use strict";var n={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},r={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},o={Properties:{},DOMAttributeNamespaces:{xlinkActuate:n.xlink,xlinkArcrole:n.xlink,xlinkHref:n.xlink,xlinkRole:n.xlink,xlinkShow:n.xlink,xlinkTitle:n.xlink,xlinkType:n.xlink,xmlBase:n.xml,xmlLang:n.xml,xmlSpace:n.xml},DOMAttributeNames:{}};Object.keys(r).forEach(function(e){o.Properties[e]=0,r[e]&&(o.DOMAttributeNames[e]=r[e])}),e.exports=o},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&c.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(E||null==g||g!==f())return null;var n=r(g);if(!_||!h(_,n)){_=n;var o=l.getPooled(y.select,b,e,t);return o.type="select",o.target=g,a.accumulateTwoPhaseDispatches(o),o}return null}var i=n(12),a=n(29),u=n(6),s=n(4),c=n(146),l=n(13),f=n(96),p=n(163),d=n(14),h=n(54),v=i.topLevelTypes,m=u.canUseDOM&&"documentMode"in document&&document.documentMode<=11,y={select:{phasedRegistrationNames:{bubbled:d({onSelect:null}),captured:d({onSelectCapture:null})},dependencies:[v.topBlur,v.topContextMenu,v.topFocus,v.topKeyDown,v.topMouseDown,v.topMouseUp,v.topSelectionChange]}},g=null,b=null,_=null,E=!1,w=!1,x=d({onSelect:null}),C={eventTypes:y,extractEvents:function(e,t,n,r){if(!w)return null;var i=t?s.getNodeFromInstance(t):window;switch(e){case v.topFocus:(p(i)||"true"===i.contentEditable)&&(g=i,b=t,_=null);break;case v.topBlur:g=null,b=null,_=null;break;case v.topMouseDown:E=!0;break;case v.topContextMenu:case v.topMouseUp:return E=!1,o(n,r);case v.topSelectionChange:if(m)break;case v.topKeyDown:case v.topKeyUp:return o(n,r)}return null},didPutListener:function(e,t,n){t===x&&(w=!0)}};e.exports=C},function(e,t,n){"use strict";var r=n(12),o=n(94),i=n(29),a=n(4),u=n(340),s=n(341),c=n(13),l=n(344),f=n(346),p=n(50),d=n(343),h=n(347),v=n(348),m=n(30),y=n(349),g=n(9),b=n(81),_=n(1),E=n(14),w=r.topLevelTypes,x={abort:{phasedRegistrationNames:{bubbled:E({onAbort:!0}),captured:E({onAbortCapture:!0})}},animationEnd:{phasedRegistrationNames:{bubbled:E({onAnimationEnd:!0}),captured:E({onAnimationEndCapture:!0})}},animationIteration:{phasedRegistrationNames:{bubbled:E({onAnimationIteration:!0}),captured:E({onAnimationIterationCapture:!0})}},animationStart:{phasedRegistrationNames:{bubbled:E({onAnimationStart:!0}),captured:E({onAnimationStartCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:E({onBlur:!0}),captured:E({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:E({onCanPlay:!0}),captured:E({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:E({onCanPlayThrough:!0}),captured:E({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:E({onClick:!0}),captured:E({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:E({onContextMenu:!0}),captured:E({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:E({onCopy:!0}),captured:E({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:E({onCut:!0}),captured:E({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:E({onDoubleClick:!0}),captured:E({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:E({onDrag:!0}),captured:E({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:E({onDragEnd:!0}),captured:E({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:E({onDragEnter:!0}),captured:E({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:E({onDragExit:!0}),captured:E({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:E({onDragLeave:!0}),captured:E({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:E({onDragOver:!0}),captured:E({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:E({onDragStart:!0}),captured:E({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:E({onDrop:!0}),captured:E({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:E({onDurationChange:!0}),captured:E({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:E({onEmptied:!0}),captured:E({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:E({onEncrypted:!0}),captured:E({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:E({onEnded:!0}),captured:E({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:E({onError:!0}),captured:E({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:E({onFocus:!0}),captured:E({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:E({onInput:!0}),captured:E({onInputCapture:!0})}},invalid:{phasedRegistrationNames:{bubbled:E({onInvalid:!0}),captured:E({onInvalidCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:E({onKeyDown:!0}),captured:E({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:E({onKeyPress:!0}),captured:E({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:E({onKeyUp:!0}),captured:E({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:E({onLoad:!0}),captured:E({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:E({onLoadedData:!0}),captured:E({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:E({onLoadedMetadata:!0}),captured:E({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:E({onLoadStart:!0}),captured:E({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:E({onMouseDown:!0}),captured:E({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:E({onMouseMove:!0}),captured:E({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:E({onMouseOut:!0}),captured:E({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:E({onMouseOver:!0}),captured:E({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:E({onMouseUp:!0}),captured:E({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:E({onPaste:!0}),captured:E({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:E({onPause:!0}),captured:E({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:E({onPlay:!0}),captured:E({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:E({onPlaying:!0}),captured:E({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:E({onProgress:!0}),captured:E({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:E({onRateChange:!0}),captured:E({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:E({onReset:!0}),captured:E({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:E({onScroll:!0}),captured:E({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:E({onSeeked:!0}),captured:E({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:E({onSeeking:!0}),captured:E({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:E({onStalled:!0}),captured:E({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:E({onSubmit:!0}),captured:E({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:E({onSuspend:!0}),captured:E({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:E({onTimeUpdate:!0}),captured:E({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:E({onTouchCancel:!0}),captured:E({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:E({onTouchEnd:!0}),captured:E({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:E({onTouchMove:!0}),captured:E({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:E({onTouchStart:!0}),captured:E({onTouchStartCapture:!0})}},transitionEnd:{phasedRegistrationNames:{bubbled:E({onTransitionEnd:!0}),captured:E({onTransitionEndCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:E({onVolumeChange:!0}),captured:E({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:E({onWaiting:!0}),captured:E({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:E({onWheel:!0}),captured:E({onWheelCapture:!0})}}},C={topAbort:x.abort,topAnimationEnd:x.animationEnd,topAnimationIteration:x.animationIteration,topAnimationStart:x.animationStart,topBlur:x.blur,topCanPlay:x.canPlay,topCanPlayThrough:x.canPlayThrough,topClick:x.click,topContextMenu:x.contextMenu,topCopy:x.copy,topCut:x.cut,topDoubleClick:x.doubleClick,topDrag:x.drag,topDragEnd:x.dragEnd,topDragEnter:x.dragEnter,topDragExit:x.dragExit,topDragLeave:x.dragLeave,topDragOver:x.dragOver,topDragStart:x.dragStart,topDrop:x.drop,topDurationChange:x.durationChange,topEmptied:x.emptied,topEncrypted:x.encrypted,topEnded:x.ended,topError:x.error,topFocus:x.focus,topInput:x.input,topInvalid:x.invalid,topKeyDown:x.keyDown,topKeyPress:x.keyPress,topKeyUp:x.keyUp,topLoad:x.load,topLoadedData:x.loadedData,topLoadedMetadata:x.loadedMetadata,topLoadStart:x.loadStart,topMouseDown:x.mouseDown,topMouseMove:x.mouseMove,topMouseOut:x.mouseOut,topMouseOver:x.mouseOver,topMouseUp:x.mouseUp,topPaste:x.paste,topPause:x.pause,topPlay:x.play,topPlaying:x.playing,topProgress:x.progress,topRateChange:x.rateChange,topReset:x.reset,topScroll:x.scroll,topSeeked:x.seeked,topSeeking:x.seeking,topStalled:x.stalled,topSubmit:x.submit,topSuspend:x.suspend,topTimeUpdate:x.timeUpdate,topTouchCancel:x.touchCancel,topTouchEnd:x.touchEnd,topTouchMove:x.touchMove,topTouchStart:x.touchStart,topTransitionEnd:x.transitionEnd,topVolumeChange:x.volumeChange,topWaiting:x.waiting,topWheel:x.wheel};for(var S in C)C[S].dependencies=[S];var P=E({onClick:null}),O={},T={eventTypes:x,extractEvents:function(e,t,n,r){var o=C[e];if(!o)return null;var a;switch(e){case w.topAbort:case w.topCanPlay:case w.topCanPlayThrough:case w.topDurationChange:case w.topEmptied:case w.topEncrypted:case w.topEnded:case w.topError:case w.topInput:case w.topInvalid:case w.topLoad:case w.topLoadedData:case w.topLoadedMetadata:case w.topLoadStart:case w.topPause:case w.topPlay:case w.topPlaying:case w.topProgress:case w.topRateChange:case w.topReset:case w.topSeeked:case w.topSeeking:case w.topStalled:case w.topSubmit:case w.topSuspend:case w.topTimeUpdate:case w.topVolumeChange:case w.topWaiting:a=c;break;case w.topKeyPress:if(0===b(n))return null;case w.topKeyDown:case w.topKeyUp:a=f;break;case w.topBlur:case w.topFocus:a=l;break;case w.topClick:if(2===n.button)return null;case w.topContextMenu:case w.topDoubleClick:case w.topMouseDown:case w.topMouseMove:case w.topMouseOut:case w.topMouseOver:case w.topMouseUp:a=p;break;case w.topDrag:case w.topDragEnd:case w.topDragEnter:case w.topDragExit:case w.topDragLeave:case w.topDragOver:case w.topDragStart:case w.topDrop:a=d;break;case w.topTouchCancel:case w.topTouchEnd:case w.topTouchMove:case w.topTouchStart:a=h;break;case w.topAnimationEnd:case w.topAnimationIteration:case w.topAnimationStart:a=u;break;case w.topTransitionEnd:a=v;break;case w.topScroll:a=m;break;case w.topWheel:a=y;break;case w.topCopy:case w.topCut:case w.topPaste:a=s}a||_(!1);var g=a.getPooled(o,t,n,r);return i.accumulateTwoPhaseDispatches(g),g},didPutListener:function(e,t,n){if(t===P){var r=e._rootNodeID,i=a.getNodeFromInstance(e);O[r]||(O[r]=o.listen(i,"click",g))}},willDeleteListener:function(e,t){if(t===P){var n=e._rootNodeID;O[n].remove(),delete O[n]}}};e.exports=T},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i={animationName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(50),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(30),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(30),i=n(81),a=n(354),u=n(82),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(30),i=n(82),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(13),i={propertyName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(50),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0,i=e.length,a=-4&i;o<a;){for(var u=Math.min(o+4096,a);o<u;o+=4)n+=(t+=e.charCodeAt(o))+(t+=e.charCodeAt(o+1))+(t+=e.charCodeAt(o+2))+(t+=e.charCodeAt(o+3));t%=r,n%=r}for(;o<i;o++)n+=t+=e.charCodeAt(o);return t%=r,n%=r,t|n<<16}var r=65521;e.exports=n},function(e,t,n){"use strict";function r(e,t,n){return null==t||"boolean"==typeof t||""===t?"":isNaN(t)||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=n(135),i=(n(2),o.isUnitlessNumber);e.exports=r},function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=i.get(e);return t?(t=a(t),t?o.getNodeFromInstance(t):null):void u((e.render,!1))}var o=(n(20),n(4)),i=n(77),a=n(161),u=n(1);n(2),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){var r=e;void 0===r[n]&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}var i=(n(73),n(88));n(2),e.exports=o},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(81),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=r},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function r(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var o=n(e),i=0,a=0;o;){if(3===o.nodeType){if(a=i+o.textContent.length,i<=t&&a>=t)return{node:o,offset:t-i};i=a}o=n(r(o))}}e.exports=o},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(u[e])return u[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in s)return u[e]=t[n];return""}var i=n(6),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},u={},s={};i.canUseDOM&&(s=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(52);e.exports=r},function(e,t,n){"use strict";var r=n(148);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(54);e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(67),c=r(s),l=n(44),f=r(l),p=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),d=n(5),h=n(46),v=n(367),m=r(v),y=n(31),g=r(y),b=function(e,t,n){var r=e.asyncValidate,s=e.blur,l=e.change,v=e.focus,y=e.getFormState,b=e.initialValues,_=t.deepEqual,E=t.getIn,w=b&&E(b,n),x=function(e){function t(){return i(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return u(t,e),p(t,[{key:"shouldComponentUpdate",value:function(e){return!_(this.props,e)}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"render",value:function(){var e=this.props,t=e.component,i=e.defaultValue,a=e.withRef,u=o(e,["component","defaultValue","withRef"]),s=this.context._reduxForm.adapter,c=(0,m.default)(E,n,u,this.syncError,i,r);a&&(c.ref="renderedComponent");var l=void 0;return s&&(l=s(t,c)),l||(l=(0,d.createElement)(t,c)),l}},{key:"syncError",get:function(){var e=this.context._reduxForm.getSyncErrors,t=g.default.getIn(e(),n);return t&&t._error?t._error:t}},{key:"dirty",get:function(){return this.props.dirty}},{key:"pristine",get:function(){return this.props.pristine}},{key:"value",get:function(){return this.props.value}}]),t}(d.Component);x.propTypes={component:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]).isRequired,defaultValue:d.PropTypes.any},x.contextTypes={_reduxForm:d.PropTypes.object};var C=(0,c.default)({blur:s,change:l,focus:v},function(e){return(0,f.default)(e,n)});return(0,h.connect)(function(e,t){var r=E(y(e),"initial."+n)||w,o=E(y(e),"values."+n),i=o===r;return{asyncError:E(y(e),"asyncErrors."+n),asyncValidating:E(y(e),"asyncValidating")===n,dirty:!i,pristine:i,state:E(y(e),"fields."+n),submitError:E(y(e),"submitErrors."+n),value:o,_value:t.value}},C,void 0,{withRef:!0})(x)};t.default=b},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(67),c=r(s),l=n(44),f=r(l),p=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),d=n(5),h=n(46),v=n(366),m=r(v),y=n(31),g=r(y),b=n(69),_=r(b),E=function(e,t,n){var r=e.arrayInsert,s=e.arrayPop,l=e.arrayPush,v=e.arrayRemove,y=e.arrayShift,b=e.arraySplice,E=e.arraySwap,w=e.arrayUnshift,x=(e.asyncValidate,e.blur,e.change,e.focus,e.getFormState),C=e.initialValues,S=t.deepEqual,P=t.getIn,O=t.size,T=C&&P(C,n),k=function(e){function t(){return i(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return u(t,e),p(t,[{key:"shouldComponentUpdate",value:function(e){return(0,_.default)(this,e)}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"render",value:function(){var e=this.props,t=e.component,r=e.withRef,i=o(e,["component","withRef"]),a=(0,m.default)(P,O,n,i,this.syncError);return r&&(a.ref="renderedComponent"),(0,d.createElement)(t,a)}},{key:"syncError",get:function(){var e=this.context._reduxForm.getSyncErrors;return g.default.getIn(e(),n+"._error")}},{key:"dirty",get:function(){return this.props.dirty}},{key:"pristine",get:function(){return this.props.pristine}},{key:"value",get:function(){return this.props.value}}]),t}(d.Component);k.propTypes={component:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]).isRequired,defaultValue:d.PropTypes.any},k.contextTypes={_reduxForm:d.PropTypes.object};var A=(0,c.default)({arrayInsert:r,arrayPop:s,arrayPush:l,arrayRemove:v,arrayShift:y,arraySplice:b,arraySwap:E,arrayUnshift:w},function(e){return(0,f.default)(e,n)});return(0,h.connect)(function(e){var t=P(x(e),"initial."+n)||T,r=P(x(e),"values."+n),o=S(r,t);return{asyncError:P(x(e),"asyncErrors."+n+"._error"),dirty:!o,pristine:o,submitError:P(x(e),"submitErrors."+n+"._error"),value:r}},A,void 0,{withRef:!0})(k)};t.default=E},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(5),l=n(33),f=r(l),p=n(360),d=r(p),h=n(69),v=r(h),m=function(e){var t=e.deepEqual,n=e.getIn,r=function(e){function r(e,a){o(this,r);var u=i(this,Object.getPrototypeOf(r).call(this,e,a));if(!a._reduxForm)throw new Error("Field must be inside a component decorated with reduxForm()");return u.ConnectedField=(0,d.default)(a._reduxForm,{deepEqual:t,getIn:n},e.name),u}return a(r,e),s(r,[{key:"shouldComponentUpdate",value:function(e){return(0,v.default)(this,e)}},{key:"componentWillMount",value:function(){this.context._reduxForm.register(this.name,"Field")}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.ConnectedField=(0,d.default)(this.context._reduxForm,{deepEqual:t,getIn:n},e.name))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,f.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Field"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return(0,c.createElement)(this.ConnectedField,u({},this.props,{ref:"connected"}))}},{key:"name",get:function(){return this.props.name}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().dirty}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().pristine}},{key:"value",get:function(){return this.refs.connected.getWrappedInstance().value}}]),r}(c.Component);return r.propTypes={name:c.PropTypes.string.isRequired,component:c.PropTypes.oneOfType([c.PropTypes.func,c.PropTypes.string]).isRequired,defaultValue:c.PropTypes.any},r.contextTypes={_reduxForm:c.PropTypes.object},r};t.default=m},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(5),l=n(33),f=r(l),p=n(361),d=r(p),h=n(69),v=r(h),m=function(e){var t=e.deepEqual,n=e.getIn,r=e.size,l=function(e){function l(e,a){o(this,l);var u=i(this,Object.getPrototypeOf(l).call(this,e,a));if(!a._reduxForm)throw new Error("FieldArray must be inside a component decorated with reduxForm()");return u.ConnectedFieldArray=(0,d.default)(a._reduxForm,{deepEqual:t,getIn:n,size:r},e.name),u}return a(l,e),s(l,[{key:"shouldComponentUpdate",value:function(e){return(0,v.default)(this,e)}},{key:"componentWillMount",value:function(){this.context._reduxForm.register(this.name,"FieldArray")}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.ConnectedFieldArray=(0,d.default)(this.context._reduxForm,{deepEqual:t,getIn:n,size:r},e.name))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,f.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to FieldArray"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return(0,c.createElement)(this.ConnectedFieldArray,u({},this.props,{ref:"connected"}))}},{key:"name",get:function(){return this.props.name}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().dirty}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().pristine}},{key:"value",get:function(){return this.refs.connected.getWrappedInstance().value}}]),l}(c.Component);return l.propTypes={name:c.PropTypes.string.isRequired,component:c.PropTypes.func.isRequired},l.contextTypes={_reduxForm:c.PropTypes.object},l};t.default=m},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(55),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e,t,n,r){t(r);var i=e();if(!(0,o.default)(i))throw new Error("asyncValidate function passed to reduxForm must return a promise");var a=function(e){return function(t){if(t&&Object.keys(t).length)return n(t),Promise.reject();if(e)throw n(),new Error("Asynchronous validation promise was rejected without errors.");return n(),Promise.resolve()}};return i.then(a(!1),a(!0))};t.default=i},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(381),u=o(a),s=n(382),c=o(s),l=n(362),f=o(l),p=n(363),d=o(p),h=n(375),v=o(h),m=n(388),y=o(m),g=n(165),b=o(g),_=n(380),E=o(_),w=n(166),x=r(w),C=n(90),S=r(C),P=function(e){return i({actionTypes:S},x,{Field:(0,f.default)(e),FieldArray:(0,d.default)(e),formValueSelector:(0,v.default)(e),propTypes:E.default,reduxForm:(0,c.default)(e),reducer:(0,u.default)(e),SubmissionError:b.default,values:(0,y.default)(e)})};t.default=P},function(e,t){"use strict";function n(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=function(e,t,o,i,a){var u=i.arrayInsert,s=i.arrayPop,c=i.arrayPush,l=i.arrayRemove,f=i.arrayShift,p=(i.arraySplice,i.arraySwap),d=i.arrayUnshift,h=i.asyncError,v=i.dirty,m=i.pristine,y=(i.state,i.submitError),g=(i.submitFailed,i.value),b=n(i,["arrayInsert","arrayPop","arrayPush","arrayRemove","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncError","dirty","pristine","state","submitError","submitFailed","value"]),_=a||h||y,E=t(g);return r({dirty:v,error:_,forEach:function(e){return(g||[]).forEach(function(t,n){return e(o+"["+n+"]",n)})},insert:u,invalid:!!_,length:E,map:function(e){return(g||[]).map(function(t,n){return e(o+"["+n+"]",n)})},pop:function(){return s(),e(g,E-1)},pristine:m,push:c,remove:l,shift:function(){return f(),e(g,0)},swap:p,unshift:d,valid:!_},b)};t.default=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=n(130),a=r(i),u=n(44),s=r(u),c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(370),f=r(l),p=n(371),d=r(p),h=n(167),v=r(h),m=n(372),y=r(m),g=n(373),b=r(g),_=function(e,t){var n=e.type,r=e.value,i=o(e,["type","value"]);return"checkbox"===n?c({},i,{checked:!!r,type:n}):"radio"===n?c({},i,{checked:r===t,type:n,value:t}):"select-multiple"===n?c({},i,{type:n,value:r||[]}):e},E=function(e,t,n,r){var i=n.asyncError,u=n.blur,l=n.change,p=n.dirty,h=n.focus,m=n.pristine,g=n.state,E=n.submitError,w=n.value,x=n._value,C=o(n,["asyncError","blur","change","dirty","focus","pristine","state","submitError","value","_value"]),S=arguments.length<=4||void 0===arguments[4]?"":arguments[4],P=arguments.length<=5||void 0===arguments[5]?a.default:arguments[5],O=r||i||E,T=(0,d.default)(l);return _(c({active:g&&!!e(g,"active"),dirty:p,error:O,invalid:!!O,name:t,onBlur:(0,f.default)(u,(0,s.default)(P,t)),onChange:T,onDragStart:(0,v.default)(t,w),onDrop:(0,y.default)(t,l),onFocus:(0,b.default)(t,h),onUpdate:T,pristine:m,touched:!(!g||!e(g,"touched")),valid:!O,value:null==w?S:w,visited:g&&!!e(g,"visited")},C),x)};t.default=E},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){var t=e.initialized,n=e.trigger,r=e.pristine;if(!e.syncValidationPasses)return!1;switch(n){case"blur":return!0;case"submit":return!r||!t;default:return!1}};t.default=n},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(45),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e){var t=e.deepEqual,n=e.empty,r=e.getIn,i=e.deleteIn,a=e.setIn;return function e(u,s){if("]"===s[s.length-1]){var c=(0,o.default)(s);c.pop();return r(u,c.join("."))?a(u,s,void 0):u}var l=i(u,s),f=s.lastIndexOf(".");if(f>0){var p=s.substring(0,f);if("]"!==p[p.length-1]){var d=r(l,p);if(t(d,n))return e(l,p)}}return l}};t.default=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(168),i=r(o),a=n(171),u=r(a),s=function(e,t){return function(n){var r=(0,i.default)(n,u.default);e(r),t&&t(r)}};t.default=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(168),i=r(o),a=n(171),u=r(a),s=function(e){return function(t){return e((0,i.default)(t,u.default))}};t.default=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(167),o=function(e,t){return function(n){t(e,n.dataTransfer.getData(r.dataKey))}};t.default=o},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t){return function(){return t(e)}};t.default=n},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(170),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e){return function(t){for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return(0,o.default)(t)?e.apply(void 0,r):e.apply(void 0,[t].concat(r))}};t.default=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(33),i=r(o),a=n(31),u=r(a),s=function(e){var t=e.getIn;return function(e){var n=arguments.length<=1||void 0===arguments[1]?function(e){return t(e,"form")}:arguments[1];return(0,i.default)(e,"Form value must be specified"),function(r){for(var o=arguments.length,a=Array(o>1?o-1:0),s=1;s<o;s++)a[s-1]=arguments[s];return(0,i.default)(a.length,"No fields specified"),1===a.length?t(n(r),e+".values."+a[0]):a.reduce(function(o,i){var a=t(n(r),e+".values."+i);return void 0===a?o:u.default.setIn(o,i,a)},{})}}};t.default=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(55),a=r(i),u=n(165),s=r(u),c=function(e,t,n,r,i){var u=t.dispatch,c=t.startSubmit,l=t.stopSubmit,f=t.setSubmitFailed,p=t.syncErrors,d=t.returnRejectedSubmitPromise,h=t.values;if(n){var v=function(){var t=e(h,u);return(0,a.default)(t)?(c(),t.then(function(e){return l(),e}).catch(function(e){if(l(e instanceof s.default?e.errors:void 0),d)return Promise.reject(e)})):t},m=r&&r();return m?m.then(v,function(e){if(f.apply(void 0,o(i)),d)return Promise.reject(e)}):v()}if(f.apply(void 0,o(i)),d)return Promise.reject(p)};t.default=c},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(172),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e,t){switch(t){case"Field":return e;case"FieldArray":return e+"._error"}},a=function(e){var t=e.getIn;return function(e,n,r,a){var u=t(e,"name"),s=t(e,"type");if(!n&&!r&&!a)return!1;var c=i(u,s),l=(0,o.default)(n,c);if(l&&"string"==typeof l)return!0;var f=t(r,c);if(f&&"string"==typeof f)return!0;var p=t(a,c);return!(!p||"string"!=typeof p)}};t.default=a},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){var t=e.getIn;return function(e){return!!e&&(!!t(e,"_error")||"string"==typeof e&&!!e)}};t.default=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.values=t.untouch=t.touch=t.SubmissionError=t.stopSubmit=t.stopAsyncValidation=t.startSubmit=t.startAsyncValidation=t.setSubmitFailed=t.reset=t.propTypes=t.initialize=t.reduxForm=t.reducer=t.formValueSelector=t.focus=t.FieldArray=t.Field=t.destroy=t.change=t.blur=t.arrayUnshift=t.arraySwap=t.arraySplice=t.arrayShift=t.arrayRemove=t.arrayPush=t.arrayPop=t.arrayInsert=t.actionTypes=void 0;var o=n(365),i=r(o),a=n(31),u=r(a),s=(0,i.default)(u.default),c=s.actionTypes,l=s.arrayInsert,f=s.arrayPop,p=s.arrayPush,d=s.arrayRemove,h=s.arrayShift,v=s.arraySplice,m=s.arraySwap,y=s.arrayUnshift,g=s.blur,b=s.change,_=s.destroy,E=s.Field,w=s.FieldArray,x=s.focus,C=s.formValueSelector,S=s.reducer,P=s.reduxForm,O=s.initialize,T=s.propTypes,k=s.reset,A=s.setSubmitFailed,R=s.startAsyncValidation,I=s.startSubmit,N=s.stopAsyncValidation,M=s.stopSubmit,j=s.SubmissionError,F=s.touch,D=s.untouch,U=s.values;t.actionTypes=c,t.arrayInsert=l,t.arrayPop=f,t.arrayPush=p,t.arrayRemove=d,t.arrayShift=h,t.arraySplice=v,t.arraySwap=m,t.arrayUnshift=y,t.blur=g,t.change=b,t.destroy=_,t.Field=E,t.FieldArray=w,t.focus=x,t.formValueSelector=C,t.reducer=S,t.reduxForm=P,t.initialize=O,t.propTypes=T,t.reset=k,t.setSubmitFailed=A,t.startAsyncValidation=R,t.startSubmit=I,t.stopAsyncValidation=N,t.stopSubmit=M,t.SubmissionError=j,t.touch=F,t.untouch=D,t.values=U},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.propTypes=void 0;var r=n(5),o=r.PropTypes.any,i=r.PropTypes.bool,a=r.PropTypes.func;t.propTypes={asyncValidating:i.isRequired,autofilled:i,dirty:i.isRequired,error:o,invalid:i.isRequired,pristine:i.isRequired,submitting:i.isRequired,submitFailed:i.isRequired,valid:i.isRequired,asyncValidate:a.isRequired,destroy:a.isRequired,handleSubmit:a.isRequired,initialize:a.isRequired,reset:a.isRequired,touch:a.isRequired,untouch:a.isRequired}},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=n(90),a=n(369),u=function(e){return e&&e.__esModule?e:{default:e}}(a),s=function(e){var t,n=e.splice,a=e.empty,s=e.getIn,c=e.setIn,l=e.deleteIn,f=e.fromJS,p=e.size,d=e.some,h=(0,u.default)(e),v=function(e,t,r,o,i,a,u){var l=s(e,t+"."+r);return l||u?c(e,t+"."+r,n(l,o,i,a)):e},m=["values","fields","submitErrors","asyncErrors"],y=function(e,t,n,r,o){var i=e;return i=v(i,"values",t,n,r,o,!0),i=v(i,"fields",t,n,r,a),i=v(i,"submitErrors",t,n,r,a),i=v(i,"asyncErrors",t,n,r,a)},g=(t={},r(t,i.ARRAY_INSERT,function(e,t){var n=t.meta,r=n.field,o=n.index,i=t.payload;return y(e,r,o,0,i)}),r(t,i.ARRAY_POP,function(e,t){var n=t.meta.field,r=s(e,"values."+n),o=r?p(r):0;return o?y(e,n,o-1,1):e}),r(t,i.ARRAY_PUSH,function(e,t){var n=t.meta.field,r=t.payload,o=s(e,"values."+n),i=o?p(o):0;return y(e,n,i,0,r)}),r(t,i.ARRAY_REMOVE,function(e,t){var n=t.meta,r=n.field,o=n.index;return y(e,r,o,1)}),r(t,i.ARRAY_SHIFT,function(e,t){var n=t.meta.field;return y(e,n,0,1)}),r(t,i.ARRAY_SPLICE,function(e,t){var n=t.meta,r=n.field,o=n.index,i=n.removeNum,a=t.payload;return y(e,r,o,i,a)}),r(t,i.ARRAY_SWAP,function(e,t){var n=t.meta,r=n.field,o=n.indexA,i=n.indexB,a=e;return m.forEach(function(e){var t=s(a,e+"."+r+"["+o+"]"),n=s(a,e+"."+r+"["+i+"]");void 0===t&&void 0===n||(a=c(a,e+"."+r+"["+o+"]",n),a=c(a,e+"."+r+"["+i+"]",t))}),a}),r(t,i.ARRAY_UNSHIFT,function(e,t){var n=t.meta.field,r=t.payload;return y(e,n,0,0,r)}),r(t,i.BLUR,function(e,t){var n=t.meta,r=n.field,o=n.touch,i=t.payload,a=e;return void 0===s(a,"initial."+r)&&""===i?a=h(a,"values."+r):void 0!==i&&(a=c(a,"values."+r,i)),r===s(a,"active")&&(a=l(a,"active")),a=l(a,"fields."+r+".active"),o&&(a=c(a,"fields."+r+".touched",!0),a=c(a,"anyTouched",!0)),a}),r(t,i.CHANGE,function(e,t){var n=t.meta,r=n.field,o=n.touch,i=t.payload,a=e;return void 0===s(a,"initial."+r)&&""===i?a=h(a,"values."+r):void 0!==i&&(a=c(a,"values."+r,i)),a=h(a,"asyncErrors."+r),a=h(a,"submitErrors."+r),o&&(a=c(a,"fields."+r+".touched",!0),a=c(a,"anyTouched",!0)),a}),r(t,i.FOCUS,function(e,t){var n=t.meta.field,r=e,o=s(e,"active");return r=l(r,"fields."+o+".active"),r=c(r,"fields."+n+".visited",!0),r=c(r,"fields."+n+".active",!0),r=c(r,"active",n)}),r(t,i.INITIALIZE,function(e,t){var n=t.payload,r=f(n),o=a;return o=c(o,"values",r),o=c(o,"initial",r)}),r(t,i.REGISTER_FIELD,function(e,t){var r=t.payload,o=r.name,i=r.type,a=e,u=s(a,"registeredFields");if(d(u,function(e){return s(e,"name")===o}))return e;var l=f({name:o,type:i});return a=c(e,"registeredFields",n(u,p(u),0,l))}),r(t,i.RESET,function(e){var t=s(e,"initial"),n=a;return t?(n=c(n,"values",t),n=c(n,"initial",t)):n=h(n,"values"),n}),r(t,i.START_ASYNC_VALIDATION,function(e,t){var n=t.meta.field;return c(e,"asyncValidating",n||!0)}),r(t,i.START_SUBMIT,function(e){return c(e,"submitting",!0)}),r(t,i.STOP_ASYNC_VALIDATION,function(e,t){var n=t.payload,r=e;if(r=l(r,"asyncValidating"),n&&Object.keys(n).length){var i=n._error,a=o(n,["_error"]);i&&(r=c(r,"error",i)),r=Object.keys(a).length?c(r,"asyncErrors",f(a)):l(r,"asyncErrors")}else r=l(r,"error"),r=l(r,"asyncErrors");return r}),r(t,i.STOP_SUBMIT,function(e,t){var n=t.payload,r=e;if(r=l(r,"submitting"),r=l(r,"submitFailed"),n&&Object.keys(n).length){var i=n._error,a=o(n,["_error"]);i&&(r=c(r,"error",i)),r=Object.keys(a).length?c(r,"submitErrors",f(a)):l(r,"submitErrors"),r=c(r,"submitFailed",!0)}else r=l(r,"error"),r=l(r,"submitErrors");return r}),r(t,i.SET_SUBMIT_FAILED,function(e,t){var n=t.meta.fields,r=e;return r=c(r,"submitFailed",!0),r=l(r,"submitting"),n.forEach(function(e){return r=c(r,"fields."+e+".touched",!0)}),n.length&&(r=c(r,"anyTouched",!0)),r}),r(t,i.TOUCH,function(e,t){var n=t.meta.fields,r=e;return n.forEach(function(e){return r=c(r,"fields."+e+".touched",!0)}),r=c(r,"anyTouched",!0)}),r(t,i.UNREGISTER_FIELD,function(e,t){var r=t.payload.name,o=s(e,"registeredFields");if(!o)return e;var i=o.findIndex(function(e){return s(e,"name")===r});return p(o)<=1&&i>=0?h(e,"registeredFields"):c(e,"registeredFields",n(o,i,1))}),r(t,i.UNTOUCH,function(e,t){var n=t.meta.fields,r=e;return n.forEach(function(e){return r=l(r,"fields."+e+".touched")}),r}),t),b=function(){var e=arguments.length<=0||void 0===arguments[0]?a:arguments[0],t=arguments[1],n=g[t.type];return n?n(e,t):e};return function(e){return e}(function(e){return function(){var t=arguments.length<=0||void 0===arguments[0]?a:arguments[0],n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=n&&n.meta&&n.meta.form;if(!r)return t;if(n.type===i.DESTROY)return h(t,n.meta.form);var o=s(t,r),u=e(o,n);return u===o?t:c(t,r,u)}}(b))};t.default=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var s=n(283),c=r(s),l=n(44),f=r(l),p=n(67),d=r(p),h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},v=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y=n(5),g=n(98),b=r(g),_=n(46),E=n(175),w=n(55),x=r(w),C=n(387),S=r(C),P=n(166),O=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}(P),T=n(376),k=r(T),A=n(170),R=r(A),I=n(374),N=r(I),M=n(364),j=r(M),F=n(378),D=r(F),U=n(377),L=r(U),V=n(368),B=r(V),W=n(31),q=r(W),H=O.arrayInsert,z=O.arrayPop,Y=O.arrayPush,K=O.arrayRemove,G=O.arrayShift,$=O.arraySplice,X=O.arraySwap,Q=O.arrayUnshift,J=O.blur,Z=O.change,ee=O.focus,te=u(O,["arrayInsert","arrayPop","arrayPush","arrayRemove","arrayShift","arraySplice","arraySwap","arrayUnshift","blur","change","focus"]),ne={arrayInsert:H,arrayPop:z,arrayPush:Y,arrayRemove:K,arrayShift:G,arraySplice:$,arraySwap:X,arrayUnshift:Q},re=[].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(Object.keys(O)),["array","asyncErrors","initialized","initialValues","syncErrors","values","registeredFields"]),oe=function(e){if(!e||"function"!=typeof e)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return e},ie=function(e){var t=e.deepEqual,n=e.empty,r=e.getIn,s=e.setIn,l=e.fromJS,p=e.some,g=(0,D.default)(e),w=(0,L.default)(e),C=(0,D.default)(q.default);return function(e){var P=m({touchOnBlur:!0,touchOnChange:!1,destroyOnUnmount:!0,shouldAsyncValidate:B.default,getFormState:function(e){return r(e,"form")}},e);return function(e){var O=function(n){function c(e){o(this,c);var t=i(this,Object.getPrototypeOf(c).call(this,e));return t.submit=t.submit.bind(t),t.reset=t.reset.bind(t),t.asyncValidate=t.asyncValidate.bind(t),t.getSyncErrors=t.getSyncErrors.bind(t),t.register=t.register.bind(t),t.unregister=t.unregister.bind(t),t.submitCompleted=t.submitCompleted.bind(t),t}return a(c,n),v(c,[{key:"getChildContext",value:function(){var e=this;return{_reduxForm:m({},this.props,{getFormState:function(t){return r(e.props.getFormState(t),e.props.form)},asyncValidate:this.asyncValidate,getSyncErrors:this.getSyncErrors,register:this.register,unregister:this.unregister})}}},{key:"initIfNeeded",value:function(e){var t=e.initialize,n=e.initialized,r=e.initialValues;r&&!n&&t(r)}},{key:"componentWillMount",value:function(){this.initIfNeeded(this.props)}},{key:"componentWillReceiveProps",value:function(e){this.initIfNeeded(e)}},{key:"shouldComponentUpdate",value:function(e){var n=this;return Object.keys(e).some(function(r){return!~re.indexOf(r)&&!t(n.props[r],e[r])})}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.destroyOnUnmount,n=e.destroy;t&&(this.destroyed=!0,n())}},{key:"getSyncErrors",value:function(){return this.props.syncErrors}},{key:"register",value:function(e,t){this.props.registerField(e,t)}},{key:"unregister",value:function(e){this.destroyed||this.props.unregisterField(e)}},{key:"asyncValidate",value:function(e,t){var n=this,o=this.props,i=o.asyncBlurFields,a=o.asyncErrors,u=o.asyncValidate,c=o.dispatch,l=o.initialized,f=o.pristine,p=o.shouldAsyncValidate,d=o.startAsyncValidation,v=o.stopAsyncValidation,m=o.syncErrors,y=o.values,g=!e;if(u){var b=function(){var o=g?y:s(y,e,t),h=g||!r(m,e);if((!g&&(!i||~i.indexOf(e.replace(/\[[0-9]+\]/g,"[]")))||g)&&p({asyncErrors:a,initialized:l,trigger:g?"submit":"blur",blurredField:e,pristine:f,syncValidationPasses:h}))return{v:(0,j.default)(function(){return u(o,c,n.props)},d,v,e)}}();if("object"===(void 0===b?"undefined":h(b)))return b.v}}},{key:"submitCompleted",value:function(e){return delete this.submitPromise,e}},{key:"listenToSubmit",value:function(e){return(0,x.default)(e)?(this.submitPromise=e,e.then(this.submitCompleted,this.submitCompleted)):e}},{key:"submit",value:function(e){var t=this,n=this.props.onSubmit;return e&&!(0,R.default)(e)?(0,N.default)(function(){return!t.submitPromise&&t.listenToSubmit((0,k.default)(oe(e),t.props,t.valid,t.asyncValidate,t.fieldList))}):this.submitPromise?void 0:this.listenToSubmit((0,k.default)(oe(n),this.props,this.valid,this.asyncValidate,this.fieldList))}},{key:"reset",value:function(){this.props.reset()}},{key:"render",value:function(){var t=this.props,n=(t.arrayInsert,t.arrayPop,t.arrayPush,t.arrayRemove,t.arrayShift,t.arraySplice,t.arraySwap,t.arrayUnshift,t.asyncErrors,t.reduxMountPoint,t.destroyOnUnmount,t.getFormState,t.touchOnBlur,t.touchOnChange,t.syncErrors,t.values,t.registerField,t.unregisterField,u(t,["arrayInsert","arrayPop","arrayPush","arrayRemove","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncErrors","reduxMountPoint","destroyOnUnmount","getFormState","touchOnBlur","touchOnChange","syncErrors","values","registerField","unregisterField"]));return(0,y.createElement)(e,m({},n,{handleSubmit:this.submit}))}},{key:"values",get:function(){return this.props.values}},{key:"valid",get:function(){return this.props.valid}},{key:"invalid",get:function(){return!this.valid}},{key:"fieldList",get:function(){return this.props.registeredFields.map(function(e){return r(e,"name")})}}]),c}(y.Component);O.displayName="Form("+(0,S.default)(e)+")",O.WrappedComponent=e,O.childContextTypes={_reduxForm:y.PropTypes.object.isRequired},O.propTypes={adapter:y.PropTypes.func,destroyOnUnmount:y.PropTypes.bool,form:y.PropTypes.string.isRequired,initialValues:y.PropTypes.object,getFormState:y.PropTypes.func,validate:y.PropTypes.func,touchOnBlur:y.PropTypes.bool,touchOnChange:y.PropTypes.bool,registeredFields:y.PropTypes.any};var T=(0,_.connect)(function(e,o){var i=o.form,a=o.getFormState,u=o.initialValues,s=o.validate,c=r(a(e)||n,i)||n,l=r(c,"initial"),f=u||l||n,d=r(c,"values")||f,h=t(f,d),v=r(c,"asyncErrors"),m=r(c,"submitErrors"),y=s&&s(d,o)||{},b=C(y),_=g(v),E=g(m),x=!(b||_||E||p(r(c,"registeredFields"),function(e){return w(e,y,v,m)})),S=!!r(c,"anyTouched"),P=!!r(c,"submitting"),O=!!r(c,"submitFailed"),T=r(c,"error");return{anyTouched:S,asyncErrors:v,asyncValidating:r(c,"asyncValidating"),dirty:!h,error:T,initialized:!!l,invalid:!x,pristine:h,submitting:P,submitFailed:O,syncErrors:y,values:d,valid:x,registeredFields:r(c,"registeredFields")}},function(e,t){var n=function(e){return(0,f.default)(e,t.form)},r=(0,d.default)(te,n),o=(0,d.default)(ne,n),i=(0,c.default)(n(J),!!t.touchOnBlur),a=(0,c.default)(n(Z),!!t.touchOnChange),u=n(ee),s=(0,E.bindActionCreators)(r,e),l={insert:(0,E.bindActionCreators)(o.arrayInsert,e),pop:(0,E.bindActionCreators)(o.arrayPop,e),push:(0,E.bindActionCreators)(o.arrayPush,e),remove:(0,E.bindActionCreators)(o.arrayRemove,e),shift:(0,E.bindActionCreators)(o.arrayShift,e),splice:(0,E.bindActionCreators)(o.arraySplice,e),swap:(0,E.bindActionCreators)(o.arraySwap,e),unshift:(0,E.bindActionCreators)(o.arrayUnshift,e)},p=m({},s,o,{blur:i,change:a,array:l,focus:u,dispatch:e});return function(){return p}},void 0,{withRef:!0}),A=(0,b.default)(T(O),e);return A.defaultProps=P,function(e){function t(){return o(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),v(t,[{key:"submit",value:function(){return this.refs.wrapped.getWrappedInstance().submit()}},{key:"reset",value:function(){return this.refs.wrapped.getWrappedInstance().reset()}},{key:"render",value:function(){var e=this.props,t=e.initialValues,n=u(e,["initialValues"]);return(0,y.createElement)(A,m({},n,{ref:"wrapped",initialValues:l(t)}))}},{key:"valid",get:function(){return this.refs.wrapped.getWrappedInstance().valid}},{key:"invalid",get:function(){return this.refs.wrapped.getWrappedInstance().invalid}},{key:"values",get:function(){return this.refs.wrapped.getWrappedInstance().values}},{key:"fieldList",get:function(){return this.refs.wrapped.getWrappedInstance().fieldList}}]),t}(y.Component)}}};t.default=ie},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(279),o=function(e){return e&&e.__esModule?e:{default:e}}(r),i=function(e,t){return e==t||null==e&&""===t||""===e&&null==t||void 0},a=function(e,t){return(0,o.default)(e,t,i)};t.default=a},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(45),a=function(e){return e&&e.__esModule?e:{default:e}}(i),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function e(t,n){for(var i=arguments.length,a=Array(i>2?i-2:0),s=2;s<i;s++)a[s-2]=arguments[s];if(void 0===t||void 0===n)return t;if(a.length){if(Array.isArray(t)){if(n<t.length){var c=e.apply(void 0,[t&&t[n]].concat(a));if(c!==t[n]){var l=[].concat(o(t));return l[n]=c,l}}return t}if(n in t){var f=e.apply(void 0,[t&&t[n]].concat(a));return t[n]===f?t:u({},t,r({},n,f))}return t}if(Array.isArray(t)){if(isNaN(n))throw new Error("Cannot delete non-numerical index from an array");if(n<t.length){var p=[].concat(o(t));return p.splice(n,1),p}return t}if(n in t){var d=u({},t);return delete d[n],d}return t},c=function(e,t){return s.apply(void 0,[e].concat(o((0,a.default)(t))))};t.default=c},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(45),a=function(e){return e&&e.__esModule?e:{default:e}}(i),u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function e(t,n,i){for(var a=arguments.length,s=Array(a>3?a-3:0),c=3;c<a;c++)s[c-3]=arguments[c];if(void 0===i)return n;var l=e.apply(void 0,[t&&t[i],n].concat(s));if(!t){var f=isNaN(i)?{}:[];return f[i]=l,f}if(Array.isArray(t)){var p=[].concat(o(t));return p[i]=l,p}return u({},t,r({},i,l))},c=function(e,t,n){return s.apply(void 0,[e,n].concat(o((0,a.default)(t))))};t.default=c},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var r=function(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=arguments[1],r=arguments[2],o=arguments[3],i=[].concat(n(e));return r?i.splice(t,r):i.splice(t,0,o),i};t.default=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){return e.displayName||e.name||"Component"};t.default=n},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(46),a=function(e){var t=e.getIn;return function(e){var n=o({prop:"values",getFormState:function(e){return t(e,"form")}},e),a=n.form,u=n.prop,s=n.getFormState;return(0,i.connect)(function(e){return r({},u,t(s(e),a+".values"))},function(){return{}})}};t.default=a},function(e,t,n){"use strict";function r(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){return function(n,r,i){var u=e(n,r,i),s=u.dispatch,c=[],l={getState:u.getState,dispatch:function(e){return s(e)}};return c=t.map(function(e){return e(l)}),s=a.default.apply(void 0,c)(u.dispatch),o({},u,{dispatch:s})}}}t.__esModule=!0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.default=r;var i=n(173),a=function(e){return e&&e.__esModule?e:{default:e}}(i)},function(e,t){"use strict";function n(e,t){return function(){return t(e.apply(void 0,arguments))}}function r(e,t){if("function"==typeof e)return n(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var r=Object.keys(e),o={},i=0;i<r.length;i++){var a=r[i],u=e[a];"function"==typeof u&&(o[a]=n(u,t))}return o}t.__esModule=!0,t.default=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n=t&&t.type;return"Given action "+(n&&'"'+n.toString()+'"'||"an action")+', reducer "'+e+'" returned undefined. To ignore an action, you must explicitly return the previous state.'}function i(e){Object.keys(e).forEach(function(t){var n=e[t];if(void 0===n(void 0,{type:u.ActionTypes.INIT}))throw new Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');if(void 0===n(void 0,{type:"@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".")}))throw new Error('Reducer "'+t+"\" returned undefined when probed with a random type. Don't try to handle "+u.ActionTypes.INIT+' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.')})}function a(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++){var a=t[r];"function"==typeof e[a]&&(n[a]=e[a])}var u,s=Object.keys(n);try{i(n)}catch(e){u=e}return function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments[1];if(u)throw u;for(var r=!1,i={},a=0;a<s.length;a++){var c=s[a],l=n[c],f=e[c],p=l(f,t);if(void 0===p){var d=o(c,t);throw new Error(d)}i[c]=p,r=r||p!==f}return r?i:e}}t.__esModule=!0,t.default=a;var u=n(174);r((r(n(65)),n(176)))},function(e,t,n){(function(t){"use strict";e.exports=n(393)(t||window||this)}).call(t,function(){return this}())},function(e,t){"use strict";e.exports=function(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}}])})},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(15),s=(n.n(u),n(68)),c=n(261),l=n(263),f=n(695),p=n(42),d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),v=["_reduxForm"],m=function(e){var t=e.deepEqual,m=e.getIn,y=e.toJS,g=function(e,t){var n=p.a.getIn(e,t);return n&&n._error?n._error:n},b=function(e,t){var n=m(e,t);return n&&n._warning?n._warning:n},_=function(e){function s(e){o(this,s);var t=i(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,e));return t.handleChange=t.handleChange.bind(t),t.handleFocus=t.handleFocus.bind(t),t.handleBlur=t.handleBlur.bind(t),t.handleDragStart=t.handleDragStart.bind(t),t.handleDrop=t.handleDrop.bind(t),t}return a(s,e),h(s,[{key:"shouldComponentUpdate",value:function(e){var n=this,r=Object.keys(e),o=Object.keys(this.props);return r.length!==o.length||r.some(function(r){return!~v.indexOf(r)&&!t(n.props[r],e[r])})}},{key:"isPristine",value:function(){return this.props.pristine}},{key:"getValue",value:function(){return this.props.value}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"handleChange",value:function(e){var t=this.props,r=t.name,o=t.dispatch,i=t.parse,a=t.normalize,u=t.onChange,s=t._reduxForm,c=t.value,f=n.i(l.a)(e,{name:r,parse:i,normalize:a}),p=!1;u&&u(d({},e,{preventDefault:function(){return p=!0,e.preventDefault()}}),f,c),p||o(s.change(r,f))}},{key:"handleFocus",value:function(e){var t=this.props,n=t.name,r=t.dispatch,o=t.onFocus,i=t._reduxForm,a=!1;o&&o(d({},e,{preventDefault:function(){return a=!0,e.preventDefault()}})),a||r(i.focus(n))}},{key:"handleBlur",value:function(e){var t=this.props,r=t.name,o=t.dispatch,i=t.parse,a=t.normalize,u=t.onBlur,s=t._reduxForm,c=t._value,f=t.value,p=n.i(l.a)(e,{name:r,parse:i,normalize:a});p===c&&void 0!==c&&(p=f);var h=!1;u&&u(d({},e,{preventDefault:function(){return h=!0,e.preventDefault()}}),p,f),h||(o(s.blur(r,p)),s.asyncValidate&&s.asyncValidate(r,p))}},{key:"handleDragStart",value:function(e){var t=this.props,n=t.onDragStart,r=t.value;e.dataTransfer.setData(f.a,null==r?"":r),n&&n(e)}},{key:"handleDrop",value:function(e){var t=this.props,n=t.name,r=t.dispatch,o=t.onDrop,i=t._reduxForm,a=t.value,u=e.dataTransfer.getData(f.a),s=!1;o&&o(d({},e,{preventDefault:function(){return s=!0,e.preventDefault()}}),u,a),s||(r(i.change(n,u)),e.preventDefault())}},{key:"render",value:function(){var e=this.props,t=e.component,o=e.withRef,i=e.name,a=e._reduxForm,s=(e.normalize,e.onBlur,e.onChange,e.onFocus,e.onDragStart,e.onDrop,r(e,["component","withRef","name","_reduxForm","normalize","onBlur","onChange","onFocus","onDragStart","onDrop"])),l=n.i(c.a)({getIn:m,toJS:y},i,d({},s,{form:a.form,onBlur:this.handleBlur,onChange:this.handleChange,onDrop:this.handleDrop,onDragStart:this.handleDragStart,onFocus:this.handleFocus})),f=l.custom,p=r(l,["custom"]);if(o&&(f.ref="renderedComponent"),"string"==typeof t){var h=p.input;p.meta;return n.i(u.createElement)(t,d({},h,f))}return n.i(u.createElement)(t,d({},p,f))}}]),s}(u.Component);return _.propTypes={component:u.PropTypes.oneOfType([u.PropTypes.func,u.PropTypes.string]).isRequired,props:u.PropTypes.object},n.i(s.connect)(function(e,n){var r=n.name,o=n._reduxForm,i=o.initialValues,a=o.getFormState,u=a(e),s=m(u,"initial."+r),c=void 0!==s?s:i&&m(i,r),l=m(u,"values."+r),f=m(u,"submitting"),p=g(m(u,"syncErrors"),r),d=b(m(u,"syncWarnings"),r),h=t(l,c);return{asyncError:m(u,"asyncErrors."+r),asyncValidating:m(u,"asyncValidating")===r,dirty:!h,pristine:h,state:m(u,"fields."+r),submitError:m(u,"submitErrors."+r),submitFailed:m(u,"submitFailed"),submitting:f,syncError:p,syncWarning:d,value:l,_value:n.value}},void 0,void 0,{withRef:!0})(_)};t.a=m},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(228),s=n(15),c=(n.n(s),n(68)),l=n(110),f=n(663),p=n(42),d=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),h=["_reduxForm","value"],v=function(e){var t=e.deepEqual,v=e.getIn,m=e.size,y=function(e,t){return p.a.getIn(e,t+"._error")},g=function(e,t){return v(e,t+"._warning")},b=function(e){function u(){o(this,u);var e=i(this,(u.__proto__||Object.getPrototypeOf(u)).call(this));return e.getValue=e.getValue.bind(e),e}return a(u,e),d(u,[{key:"shouldComponentUpdate",value:function(e){var n=this,r=this.props.value,o=e.value;if(r&&o&&(r.length!==o.length||r.every(function(e){return o.some(function(n){return t(e,n)})})))return!0;var i=Object.keys(e),a=Object.keys(this.props);return i.length!==a.length||i.some(function(r){return!~h.indexOf(r)&&!t(n.props[r],e[r])})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"getValue",value:function(e){return this.props.value&&v(this.props.value,e)}},{key:"render",value:function(){var e=this.props,t=e.component,o=e.withRef,i=e.name,a=e._reduxForm,u=(e.validate,e.warn,r(e,["component","withRef","name","_reduxForm","validate","warn"])),c=n.i(f.a)(v,i,a.form,a.sectionPrefix,this.getValue,u);return o&&(c.ref="renderedComponent"),n.i(s.createElement)(t,c)}},{key:"dirty",get:function(){return this.props.dirty}},{key:"pristine",get:function(){return this.props.pristine}},{key:"value",get:function(){return this.props.value}}]),u}(s.Component);return b.propTypes={component:s.PropTypes.oneOfType([s.PropTypes.func,s.PropTypes.string]).isRequired,props:s.PropTypes.object},b.contextTypes={_reduxForm:s.PropTypes.object},n.i(c.connect)(function(e,n){var r=n.name,o=n._reduxForm,i=o.initialValues,a=o.getFormState,u=a(e),s=v(u,"initial."+r)||i&&v(i,r),c=v(u,"values."+r),l=v(u,"submitting"),f=y(v(u,"syncErrors"),r),p=g(v(u,"syncWarnings"),r),d=t(c,s);return{asyncError:v(u,"asyncErrors."+r+"._error"),dirty:!d,pristine:d,state:v(u,"fields."+r),submitError:v(u,"submitErrors."+r+"._error"),submitFailed:v(u,"submitFailed"),submitting:l,syncError:f,syncWarning:p,value:c,length:m(c)}},function(e,t){var r=t.name,o=t._reduxForm,i=o.arrayInsert,a=o.arrayMove,s=o.arrayPop,c=o.arrayPush,f=o.arrayRemove,p=o.arrayRemoveAll,d=o.arrayShift,h=o.arraySplice,v=o.arraySwap,m=o.arrayUnshift;return n.i(u.a)({arrayInsert:i,arrayMove:a,arrayPop:s,arrayPush:c,arrayRemove:f,arrayRemoveAll:p,arrayShift:d,arraySplice:h,arraySwap:v,arrayUnshift:m},function(t){return n.i(l.bindActionCreators)(t.bind(null,r),e)})},void 0,{withRef:!0})(b)};t.a=v},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(15),s=(n.n(u),n(68)),c=n(261),l=n(42),f=n(263),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),h=["_reduxForm"],v=function(e){var t=e.deepEqual,v=e.getIn,m=e.toJS,y=e.size,g=function(e,t){return l.a.getIn(e,t+"._error")||l.a.getIn(e,t)},b=function(e,t){var n=v(e,t);return n&&n._warning?n._warning:n},_=function(e){function s(e){o(this,s);var t=i(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,e));return t.handleChange=t.handleChange.bind(t),t.handleFocus=t.handleFocus.bind(t),t.handleBlur=t.handleBlur.bind(t),t.onChangeFns=e.names.reduce(function(e,n){return e[n]=function(e){return t.handleChange(n,e)},e},{}),t.onFocusFns=e.names.reduce(function(e,n){return e[n]=function(){return t.handleFocus(n)},e},{}),t.onBlurFns=e.names.reduce(function(e,n){return e[n]=function(e){return t.handleBlur(n,e)},e},{}),t}return a(s,e),d(s,[{key:"componentWillReceiveProps",value:function(e){var t=this;this.props.names===e.names||y(this.props.names)===y(e.names)&&!e.names.some(function(e){return!t.props._fields[e]})||(this.onChangeFns=e.names.reduce(function(e,n){return e[n]=function(e){return t.handleChange(n,e)},e},{}),this.onFocusFns=e.names.reduce(function(e,n){return e[n]=function(){return t.handleFocus(n)},e},{}),this.onBlurFns=e.names.reduce(function(e,n){return e[n]=function(e){return t.handleBlur(n,e)},e},{}))}},{key:"shouldComponentUpdate",value:function(e){var n=this,r=Object.keys(e),o=Object.keys(this.props);return r.length!==o.length||r.some(function(r){return!~h.indexOf(r)&&!t(n.props[r],e[r])})}},{key:"isDirty",value:function(){var e=this.props._fields;return Object.keys(e).some(function(t){return e[t].dirty})}},{key:"getValues",value:function(){var e=this.props._fields;return Object.keys(e).reduce(function(t,n){return l.a.setIn(t,n,e[n].value)},{})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"handleChange",value:function(e,t){var r=this.props,o=r.dispatch,i=r.parse,a=r.normalize,u=r._reduxForm,s=n.i(f.a)(t,{name:e,parse:i,normalize:a});o(u.change(e,s))}},{key:"handleFocus",value:function(e){var t=this.props;(0,t.dispatch)(t._reduxForm.focus(e))}},{key:"handleBlur",value:function(e,t){var r=this.props,o=r.dispatch,i=r.parse,a=r.normalize,u=r._reduxForm,s=n.i(f.a)(t,{name:e,parse:i,normalize:a});o(u.blur(e,s)),u.asyncValidate&&u.asyncValidate(e,s)}},{key:"render",value:function(){var e=this,t=this.props,o=t.component,i=t.withRef,a=t._fields,s=t._reduxForm,f=r(t,["component","withRef","_fields","_reduxForm"]),d=s.sectionPrefix,h=Object.keys(a).reduce(function(t,o){var i=a[o],u=n.i(c.a)({getIn:v,toJS:m},o,p({},i,f,{onBlur:e.onBlurFns[o],onChange:e.onChangeFns[o],onFocus:e.onFocusFns[o]})),s=u.custom,h=r(u,["custom"]);t.custom=s;var y=d?o.replace(d+".",""):o;return l.a.setIn(t,y,h)},{}),y=h.custom,g=r(h,["custom"]);return i&&(g.ref="renderedComponent"),n.i(u.createElement)(o,p({},g,y))}}]),s}(u.Component);return _.propTypes={component:u.PropTypes.oneOfType([u.PropTypes.func,u.PropTypes.string]).isRequired,_fields:u.PropTypes.object.isRequired,props:u.PropTypes.object},n.i(s.connect)(function(e,t){var n=t.names,r=t._reduxForm,o=r.initialValues,i=r.getFormState,a=i(e);return{_fields:n.reduce(function(e,n){var r=v(a,"initial."+n),i=void 0!==r?r:o&&v(o,n),u=v(a,"values."+n),s=g(v(a,"syncErrors"),n),c=b(v(a,"syncWarnings"),n),l=v(a,"submitting"),f=u===i;return e[n]={asyncError:v(a,"asyncErrors."+n),asyncValidating:v(a,"asyncValidating")===n,dirty:!f,pristine:f,state:v(a,"fields."+n),submitError:v(a,"submitErrors."+n),submitFailed:v(a,"submitFailed"),submitting:l,syncError:s,syncWarning:c,value:u,_value:t.value},e},{})}},void 0,void 0,{withRef:!0})(_)};t.a=v},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(15),u=(n.n(a),n(76)),s=n.n(u),c=n(653),l=n(267),f=n(109),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),h=function(e){var t=e.deepEqual,u=e.getIn,h=e.setIn,v=e.toJS,m=n.i(c.a)({deepEqual:t,getIn:u,toJS:v}),y=function(e){function t(e,n){r(this,t);var i=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));if(!n._reduxForm)throw new Error("Field must be inside a component decorated with reduxForm()");return i.normalize=i.normalize.bind(i),i}return i(t,e),d(t,[{key:"shouldComponentUpdate",value:function(e,t){return n.i(l.a)(this,e,t)}},{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"Field",function(){return e.props.validate},function(){return e.props.warn})}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register(n.i(f.a)(this.context,e.name),"Field"))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return s()(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Field"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"normalize",value:function(e,t){var n=this.props.normalize;if(!n)return t;var r=this.context._reduxForm.getValues();return n(t,this.value,h(r,e,t),r)}},{key:"render",value:function(){return n.i(a.createElement)(m,p({},this.props,{name:this.name,normalize:this.normalize,_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"name",get:function(){return n.i(f.a)(this.context,this.props.name)}},{key:"dirty",get:function(){return!this.pristine}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().isPristine()}},{key:"value",get:function(){return this.refs.connected&&this.refs.connected.getWrappedInstance().getValue()}}]),t}(a.Component);return y.propTypes={name:a.PropTypes.string.isRequired,component:a.PropTypes.oneOfType([a.PropTypes.func,a.PropTypes.string]).isRequired,format:a.PropTypes.func,normalize:a.PropTypes.func,onBlur:a.PropTypes.func,onChange:a.PropTypes.func,onFocus:a.PropTypes.func,onDragStart:a.PropTypes.func,onDrop:a.PropTypes.func,parse:a.PropTypes.func,props:a.PropTypes.object,validate:a.PropTypes.oneOfType([a.PropTypes.func,a.PropTypes.arrayOf(a.PropTypes.func)]),warn:a.PropTypes.oneOfType([a.PropTypes.func,a.PropTypes.arrayOf(a.PropTypes.func)]),withRef:a.PropTypes.bool},y.contextTypes={_reduxForm:a.PropTypes.object},y};t.a=h},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var u=n(15),s=(n.n(u),n(76)),c=n.n(s),l=n(654),f=n(109),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),h=function(e){return Array.isArray(e)?e:[e]},v=function(e,t){return e&&function(){for(var n=h(e),r=0;r<n.length;r++){var o=n[r].apply(n,arguments);if(o)return a({},t,o)}}},m=function(e){var t=e.deepEqual,a=e.getIn,s=e.size,h=n.i(l.a)({deepEqual:t,getIn:a,size:s}),m=function(e){function t(e,n){r(this,t);var i=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));if(!n._reduxForm)throw new Error("FieldArray must be inside a component decorated with reduxForm()");return i}return i(t,e),d(t,[{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"FieldArray",function(){return v(e.props.validate,"_error")},function(){return v(e.props.warn,"_warning")})}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register(n.i(f.a)(this.context,e.name),"FieldArray"))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return c()(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to FieldArray"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return n.i(u.createElement)(h,p({},this.props,{name:this.name,syncError:this.syncError,syncWarning:this.syncWarning,_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"name",get:function(){return n.i(f.a)(this.context,this.props.name)}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().dirty}},{key:"pristine",get:function(){return this.refs.connected.getWrappedInstance().pristine}},{key:"value",get:function(){return this.refs.connected.getWrappedInstance().value}}]),t}(u.Component);return m.propTypes={name:u.PropTypes.string.isRequired,component:u.PropTypes.func.isRequired,props:u.PropTypes.object,validate:u.PropTypes.oneOfType([u.PropTypes.func,u.PropTypes.arrayOf(u.PropTypes.func)]),warn:u.PropTypes.oneOfType([u.PropTypes.func,u.PropTypes.arrayOf(u.PropTypes.func)]),withRef:u.PropTypes.bool},m.contextTypes={_reduxForm:u.PropTypes.object},m};t.a=m},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(15),u=(n.n(a),n(76)),s=n.n(u),c=n(655),l=n(267),f=n(42),p=n(109),d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),v=function(e){return e?Array.isArray(e)||e._isFieldArray?void 0:new Error('Invalid prop "names" supplied to <Fields/>. Must be either an array of strings or the fields array generated by FieldArray.'):new Error('No "names" prop was specified <Fields/>')},m=function(e){var t=e.deepEqual,u=e.getIn,m=e.toJS,y=e.size,g=n.i(c.a)({deepEqual:t,getIn:u,toJS:m,size:y}),b=function(e){function t(e,n){r(this,t);var i=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));if(!n._reduxForm)throw new Error("Fields must be inside a component decorated with reduxForm()");return i}return i(t,e),h(t,[{key:"shouldComponentUpdate",value:function(e,t){return n.i(l.a)(this,e,t)}},{key:"componentWillMount",value:function(){var e=v(this.props.names);if(e)throw e;var t=this.context,n=t._reduxForm.register;this.names.forEach(function(e){return n(e,"Field")})}},{key:"componentWillReceiveProps",value:function(e){if(!f.a.deepEqual(this.props.names,e.names)){var t=this.context,r=t._reduxForm,o=r.register,i=r.unregister;this.props.names.forEach(function(e){return i(n.i(p.a)(t,e))}),e.names.forEach(function(e){return o(n.i(p.a)(t,e),"Field")})}}},{key:"componentWillUnmount",value:function(){var e=this.context,t=e._reduxForm.unregister;this.props.names.forEach(function(r){return t(n.i(p.a)(e,r))})}},{key:"getRenderedComponent",value:function(){return s()(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Fields"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){var e=this.context;return n.i(a.createElement)(g,d({},this.props,{names:this.props.names.map(function(t){return n.i(p.a)(e,t)}),_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"names",get:function(){var e=this.context;return this.props.names.map(function(t){return n.i(p.a)(e,t)})}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().isDirty()}},{key:"pristine",get:function(){return!this.dirty}},{key:"values",get:function(){return this.refs.connected&&this.refs.connected.getWrappedInstance().getValues()}}]),t}(a.Component);return b.propTypes={names:function(e,t){return v(e[t])},component:a.PropTypes.oneOfType([a.PropTypes.func,a.PropTypes.string]).isRequired,format:a.PropTypes.func,parse:a.PropTypes.func,props:a.PropTypes.object,withRef:a.PropTypes.bool},b.contextTypes={_reduxForm:a.PropTypes.object},b};t.a=m},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(15),u=n.n(a),s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=function(e){function t(e,n){r(this,t);var i=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));if(!n._reduxForm)throw new Error("Form must be inside a component decorated with reduxForm()");return i}return i(t,e),s(t,[{key:"componentWillMount",value:function(){this.context._reduxForm.registerInnerOnSubmit(this.props.onSubmit)}},{key:"render",value:function(){return u.a.createElement("form",this.props)}}]),t}(a.Component);c.propTypes={onSubmit:a.PropTypes.func.isRequired},c.contextTypes={_reduxForm:a.PropTypes.object},t.a=c},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(15),s=n.n(u),c=n(109),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),p=function(e){function t(e,n){o(this,t);var r=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));if(!n._reduxForm)throw new Error("FormSection must be inside a component decorated with reduxForm()");return r}return a(t,e),f(t,[{key:"getChildContext",value:function(){var e=this.context,t=this.props.name;return{_reduxForm:l({},e._reduxForm,{sectionPrefix:n.i(c.a)(e,t)})}}},{key:"render",value:function(){var e=this.props,t=e.children,o=(e.name,e.component),i=r(e,["children","name","component"]);return s.a.isValidElement(t)?t:n.i(u.createElement)(o,l({},i,{children:t}))}}]),t}(u.Component);p.propTypes={name:u.PropTypes.string.isRequired,component:u.PropTypes.oneOfType([u.PropTypes.func,u.PropTypes.string])},p.defaultProps={component:"div"},p.childContextTypes={_reduxForm:u.PropTypes.object.isRequired},p.contextTypes={_reduxForm:u.PropTypes.object},t.a=p},function(e,t,n){"use strict";var r=n(139),o=n.n(r),i=function(e,t,n,r){t(r);var i=e();if(!o()(i))throw new Error("asyncValidate function passed to reduxForm must return a promise");var a=function(e){return function(t){if(t&&Object.keys(t).length)return n(t),t;if(e)throw n(),new Error("Asynchronous validation promise was rejected without errors.");return n(),Promise.resolve()}};return i.then(a(!1),a(!0))};t.a=i},function(e,t,n){"use strict";var r=n(675),o=n(676),i=n(656),a=n(658),u=n(657),s=n(669),c=n(697),l=n(679),f=n(683),p=n(678),d=n(681),h=n(677),v=n(682),m=n(680),y=n(686),g=n(687),b=n(266),_=n(175),E=n(688),w=n(685),x=n(684),C=n(659),S=n(660),P=n(259),O=n(674),T=n(260),k=n(174),A=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},R=function(e){return A({actionTypes:k},T,{Field:n.i(i.a)(e),Fields:n.i(a.a)(e),FieldArray:n.i(u.a)(e),Form:C.a,FormSection:S.a,formValueSelector:n.i(s.a)(e),getFormNames:n.i(l.a)(e),getFormValues:n.i(f.a)(e),getFormInitialValues:n.i(p.a)(e),getFormSyncErrors:n.i(d.a)(e),getFormAsyncErrors:n.i(h.a)(e),getFormSyncWarnings:n.i(v.a)(e),getFormSubmitErrors:n.i(m.a)(e),isDirty:n.i(y.a)(e),isInvalid:n.i(g.a)(e),isPristine:n.i(b.a)(e),isValid:n.i(_.a)(e),isSubmitting:n.i(E.a)(e),hasSubmitSucceeded:n.i(w.a)(e),hasSubmitFailed:n.i(x.a)(e),propTypes:O.a,reduxForm:n.i(o.a)(e),reducer:n.i(r.a)(e),SubmissionError:P.a,values:n.i(c.a)(e)})};t.a=R},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=function(e,t,n,i,a,u){var s=u.arrayInsert,c=u.arrayMove,l=u.arrayPop,f=u.arrayPush,p=u.arrayRemove,d=u.arrayRemoveAll,h=u.arrayShift,v=(u.arraySplice,u.arraySwap),m=u.arrayUnshift,y=u.asyncError,g=u.dirty,b=u.length,_=u.pristine,E=u.submitError,w=u.state,x=u.submitFailed,C=u.submitting,S=u.syncError,P=u.syncWarning,O=u.value,T=u.props,k=r(u,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncError","dirty","length","pristine","submitError","state","submitFailed","submitting","syncError","syncWarning","value","props"]),A=S||y||E,R=P,I=i?t.replace(i+".",""):t,N=o({fields:{_isFieldArray:!0,forEach:function(e){return(O||[]).forEach(function(t,n){return e(I+"["+n+"]",n,N.fields)})},get:a,getAll:function(){return O},insert:s,length:b,map:function(e){return(O||[]).map(function(t,n){return e(I+"["+n+"]",n,N.fields)})},move:c,name:t,pop:function(){return l(),e(O,b-1)},push:f,reduce:function(e,t){return(O||[]).reduce(function(t,n,r){return e(t,I+"["+r+"]",r,N.fields)},t)},remove:p,removeAll:d,shift:function(){return h(),e(O,0)},swap:v,unshift:m},meta:{dirty:g,error:A,form:n,warning:R,invalid:!!A,pristine:_,submitting:C,submitFailed:x,touched:!(!w||!e(w,"touched")),valid:!A}},T,k);return N};t.a=i},function(e,t,n){"use strict";var r=function(e){var t=e.initialized,n=e.trigger,r=e.pristine;if(!e.syncValidationPasses)return!1;switch(n){case"blur":return!0;case"submit":return!r||!t;default:return!1}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.values,n=e.nextProps,r=e.initialRender,o=e.lastFieldValidatorKeys,i=e.fieldValidatorKeys,a=e.structure;return!!r||(!a.deepEqual(t,n.values)||!a.deepEqual(o,i))};t.a=r},function(e,t,n){"use strict";var r=n(103),o=function(e){var t=e.deepEqual,o=e.empty,i=e.getIn,a=e.deleteIn,u=e.setIn;return function e(s,c){if("]"===c[c.length-1]){var l=n.i(r.a)(c);l.pop();return i(s,l.join("."))?u(s,c,void 0):s}var f=a(s,c),p=c.lastIndexOf(".");if(p>0){var d=c.substring(0,p);if("]"!==d[d.length-1]){var h=i(f,d);if(t(h,o))return e(f,d)}}return f}};t.a=o},function(e,t,n){"use strict";var r=n(262),o=function(e){var t=[];if(e)for(var n=0;n<e.length;n++){var r=e[n];r.selected&&t.push(r.value)}return t},i=function(e,t){if(n.i(r.a)(e)){if(!t&&e.nativeEvent&&void 0!==e.nativeEvent.text)return e.nativeEvent.text;if(t&&void 0!==e.nativeEvent)return e.nativeEvent.text;var i=e.target,a=i.type,u=i.value,s=i.checked,c=i.files,l=e.dataTransfer;return"checkbox"===a?s:"file"===a?c||l&&l.files:"select-multiple"===a?o(e.target.options):u}return e};t.a=i},function(e,t,n){"use strict";var r=n(264),o=function(e){return function(t){for(var o=arguments.length,i=Array(o>1?o-1:0),a=1;a<o;a++)i[a-1]=arguments[a];return n.i(r.a)(t)?e.apply(void 0,i):e.apply(void 0,[t].concat(i))}};t.a=o},function(e,t,n){"use strict";var r=n(76),o=n.n(r),i=n(42),a=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return o()(e,"Form value must be specified"),function(r){for(var a=arguments.length,u=Array(a>1?a-1:0),s=1;s<a;s++)u[s-1]=arguments[s];return o()(u.length,"No fields specified"),1===u.length?t(n(r),e+".values."+u[0]):u.reduce(function(o,a){var u=t(n(r),e+".values."+a);return void 0===u?o:i.a.setIn(o,a,u)},{})}}};t.a=a},function(e,t,n){"use strict";var r=n(42),o=function(e){return Array.isArray(e)?e:[e]},i=function(e,t,n,r){for(var i=o(r),a=0;a<i.length;a++){var u=i[a](e,t,n);if(u)return u}},a=function(e,t){var n=t.getIn;return function(t,o){var a={};return Object.keys(e).forEach(function(u){var s=n(t,u),c=i(s,t,o,e[u]);c&&(a=r.a.setIn(a,u,c))}),a}};t.a=a},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var o=n(139),i=n.n(o),a=n(259),u=function(e,t,n,o,u){var s=t.dispatch,c=t.onSubmitFail,l=t.onSubmitSuccess,f=t.startSubmit,p=t.stopSubmit,d=t.setSubmitFailed,h=t.setSubmitSucceeded,v=t.syncErrors,m=t.touch,y=t.values,g=t.persistentSubmitErrors;if(m.apply(void 0,r(u)),n||g){var b=function(){var n=void 0;try{n=e(y,s,t)}catch(e){var o=e instanceof a.a?e.errors:void 0;if(p(o),d.apply(void 0,r(u)),c&&c(o,s,e,t),o||c)return o;throw e}return i()(n)?(f(),n.then(function(e){return p(),h(),l&&l(e,s,t),e},function(e){var n=e instanceof a.a?e.errors:void 0;if(p(n),d.apply(void 0,r(u)),c&&c(n,s,e,t),n||c)return n;throw e})):(h(),l&&l(n,s,t),n)},_=o&&o();return _?_.then(function(e){if(e)throw e;return b()}).catch(function(e){return d.apply(void 0,r(u)),c&&c(e,s,null,t),Promise.reject(e)}):b()}return d.apply(void 0,r(u)),c&&c(v,s,null,t),v};t.a=u},function(e,t,n){"use strict";var r=function(e,t){switch(t){case"Field":return[e,e+"._error"];case"FieldArray":return[e+"._error"];default:throw new Error("Unknown field type")}},o=function(e){var t=e.getIn;return function(e,n,o,i){if(!n&&!o&&!i)return!1;var a=t(e,"name"),u=t(e,"type");return r(a,u).some(function(e){return t(n,e)||t(o,e)||t(i,e)})}};t.a=o},function(e,t,n){"use strict";var r="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product;t.a=r},function(e,t,n){"use strict";var r=n(15),o=(n.n(r),r.PropTypes.any),i=r.PropTypes.bool,a=r.PropTypes.func,u=r.PropTypes.shape,s=r.PropTypes.string,c=r.PropTypes.oneOfType,l=r.PropTypes.object,f={anyTouched:i.isRequired,asyncValidating:c([i,s]).isRequired,dirty:i.isRequired,error:o,form:s.isRequired,invalid:i.isRequired,initialized:i.isRequired,initialValues:l,pristine:i.isRequired,pure:i.isRequired,submitting:i.isRequired,submitFailed:i.isRequired,submitSucceeded:i.isRequired,valid:i.isRequired,warning:o,array:u({insert:a.isRequired,move:a.isRequired,pop:a.isRequired,push:a.isRequired,remove:a.isRequired,removeAll:a.isRequired,shift:a.isRequired,splice:a.isRequired,swap:a.isRequired,unshift:a.isRequired}),asyncValidate:a.isRequired,autofill:a.isRequired,blur:a.isRequired,change:a.isRequired,clearAsyncError:a.isRequired,destroy:a.isRequired,dispatch:a.isRequired,handleSubmit:a.isRequired,initialize:a.isRequired,reset:a.isRequired,touch:a.isRequired,submit:a.isRequired,untouch:a.isRequired,triggerSubmit:i,clearSubmit:a.isRequired};t.a=f},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var i=n(174),a=n(666),u=n(42),s=function(e){function t(e){return e.plugin=function(e){var n=this;return t(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(e).reduce(function(n,o){var i=f(n,o),a=e[o](i,r,f(t,o));return a===i?n:p(n,o,a)},n(t,r))})},e}var s,c=e.deepEqual,l=e.empty,f=e.getIn,p=e.setIn,d=e.deleteIn,h=e.fromJS,v=e.keys,m=e.size,y=e.splice,g=n.i(a.a)(e),b=function(e,t,n,r,o,i,a){var u=f(e,t+"."+n);return u||a?p(e,t+"."+n,y(u,r,o,i)):e},_=function(e,t,n,r,o,i,a){var s=f(e,t),c=u.a.getIn(s,n);return c||a?p(e,t,u.a.setIn(s,n,u.a.splice(c,r,o,i))):e},E=["values","fields","submitErrors","asyncErrors"],w=function(e,t,n,r,o){var i=e,a=null!=o?l:void 0;return i=b(i,"values",t,n,r,o,!0),i=b(i,"fields",t,n,r,a),i=_(i,"syncErrors",t,n,r,void 0),i=_(i,"syncWarnings",t,n,r,void 0),i=b(i,"submitErrors",t,n,r,void 0),i=b(i,"asyncErrors",t,n,r,void 0)},x=(s={},r(s,i.ARRAY_INSERT,function(e,t){var n=t.meta,r=n.field,o=n.index,i=t.payload;return w(e,r,o,0,i)}),r(s,i.ARRAY_MOVE,function(e,t){var n=t.meta,r=n.field,o=n.from,i=n.to,a=f(e,"values."+r),u=a?m(a):0,s=e;return u&&E.forEach(function(e){var t=e+"."+r;if(f(s,t)){var n=f(s,t+"["+o+"]");s=p(s,t,y(f(s,t),o,1)),s=p(s,t,y(f(s,t),i,0,n))}}),s}),r(s,i.ARRAY_POP,function(e,t){var n=t.meta.field,r=f(e,"values."+n),o=r?m(r):0;return o?w(e,n,o-1,1):e}),r(s,i.ARRAY_PUSH,function(e,t){var n=t.meta.field,r=t.payload,o=f(e,"values."+n),i=o?m(o):0;return w(e,n,i,0,r)}),r(s,i.ARRAY_REMOVE,function(e,t){var n=t.meta,r=n.field,o=n.index;return w(e,r,o,1)}),r(s,i.ARRAY_REMOVE_ALL,function(e,t){var n=t.meta.field,r=f(e,"values."+n),o=r?m(r):0;return o?w(e,n,0,o):e}),r(s,i.ARRAY_SHIFT,function(e,t){var n=t.meta.field;return w(e,n,0,1)}),r(s,i.ARRAY_SPLICE,function(e,t){var n=t.meta,r=n.field,o=n.index,i=n.removeNum,a=t.payload;return w(e,r,o,i,a)}),r(s,i.ARRAY_SWAP,function(e,t){var n=t.meta,r=n.field,o=n.indexA,i=n.indexB,a=e;return E.forEach(function(e){var t=f(a,e+"."+r+"["+o+"]"),n=f(a,e+"."+r+"["+i+"]");void 0===t&&void 0===n||(a=p(a,e+"."+r+"["+o+"]",n),a=p(a,e+"."+r+"["+i+"]",t))}),a}),r(s,i.ARRAY_UNSHIFT,function(e,t){var n=t.meta.field,r=t.payload;return w(e,n,0,0,r)}),r(s,i.AUTOFILL,function(e,t){var n=t.meta.field,r=t.payload,o=e;return o=g(o,"asyncErrors."+n),o=g(o,"submitErrors."+n),o=p(o,"fields."+n+".autofilled",!0),o=p(o,"values."+n,r)}),r(s,i.BLUR,function(e,t){var n=t.meta,r=n.field,o=n.touch,i=t.payload,a=e;return void 0===f(a,"initial."+r)&&""===i?a=g(a,"values."+r):void 0!==i&&(a=p(a,"values."+r,i)),r===f(a,"active")&&(a=d(a,"active")),a=d(a,"fields."+r+".active"),o&&(a=p(a,"fields."+r+".touched",!0),a=p(a,"anyTouched",!0)),a}),r(s,i.CHANGE,function(e,t){var n=t.meta,r=n.field,o=n.touch,i=n.persistentSubmitErrors,a=t.payload,u=e;return void 0===f(u,"initial."+r)&&""===a?u=g(u,"values."+r):void 0!==a&&(u=p(u,"values."+r,a)),u=g(u,"asyncErrors."+r),i||(u=g(u,"submitErrors."+r)),u=g(u,"fields."+r+".autofilled"),o&&(u=p(u,"fields."+r+".touched",!0),u=p(u,"anyTouched",!0)),u}),r(s,i.CLEAR_SUBMIT,function(e){return d(e,"triggerSubmit")}),r(s,i.CLEAR_SUBMIT_ERRORS,function(e){return g(e,"submitErrors")}),r(s,i.CLEAR_ASYNC_ERROR,function(e,t){var n=t.meta.field;return d(e,"asyncErrors."+n)}),r(s,i.FOCUS,function(e,t){var n=t.meta.field,r=e,o=f(e,"active");return r=d(r,"fields."+o+".active"),r=p(r,"fields."+n+".visited",!0),r=p(r,"fields."+n+".active",!0),r=p(r,"active",n)}),r(s,i.INITIALIZE,function(e,t){var n=t.payload,r=t.meta,o=r.keepDirty,i=r.keepSubmitSucceeded,a=h(n),u=l,s=f(e,"warning");s&&(u=p(u,"warning",s));var d=f(e,"syncWarnings");d&&(u=p(u,"syncWarnings",d));var m=f(e,"error");m&&(u=p(u,"error",m));var y=f(e,"syncErrors");y&&(u=p(u,"syncErrors",y));var g=f(e,"registeredFields");g&&(u=p(u,"registeredFields",g));var b=a;if(o&&g){var _=f(e,"values"),E=f(e,"initial");v(g).forEach(function(e){var t=f(E,e),n=f(_,e);c(n,t)||(b=p(b,e,n))})}return i&&f(e,"submitSucceeded")&&(u=p(u,"submitSucceeded",!0)),u=p(u,"values",b),u=p(u,"initial",a)}),r(s,i.REGISTER_FIELD,function(e,t){var n=t.payload,r=n.name,o=n.type,i="registeredFields['"+r+"']",a=f(e,i);if(a){var u=f(a,"count")+1;a=p(a,"count",u)}else a=h({name:r,type:o,count:1});return p(e,i,a)}),r(s,i.RESET,function(e){var t=l,n=f(e,"registeredFields");n&&(t=p(t,"registeredFields",n));var r=f(e,"initial");return r&&(t=p(t,"values",r),t=p(t,"initial",r)),t}),r(s,i.SUBMIT,function(e){return p(e,"triggerSubmit",!0)}),r(s,i.START_ASYNC_VALIDATION,function(e,t){var n=t.meta.field;return p(e,"asyncValidating",n||!0)}),r(s,i.START_SUBMIT,function(e){return p(e,"submitting",!0)}),r(s,i.STOP_ASYNC_VALIDATION,function(e,t){var n=t.payload,r=e;if(r=d(r,"asyncValidating"),n&&Object.keys(n).length){var i=n._error,a=o(n,["_error"]);i&&(r=p(r,"error",i)),r=Object.keys(a).length?p(r,"asyncErrors",h(a)):d(r,"asyncErrors")}else r=d(r,"error"),r=d(r,"asyncErrors");return r}),r(s,i.STOP_SUBMIT,function(e,t){var n=t.payload,r=e;if(r=d(r,"submitting"),r=d(r,"submitFailed"),r=d(r,"submitSucceeded"),n&&Object.keys(n).length){var i=n._error,a=o(n,["_error"]);r=i?p(r,"error",i):d(r,"error"),r=Object.keys(a).length?p(r,"submitErrors",h(a)):d(r,"submitErrors"),r=p(r,"submitFailed",!0)}else r=p(r,"submitSucceeded",!0),r=d(r,"error"),r=d(r,"submitErrors");return r}),r(s,i.SET_SUBMIT_FAILED,function(e,t){var n=t.meta.fields,r=e;return r=p(r,"submitFailed",!0),r=d(r,"submitSucceeded"),r=d(r,"submitting"),n.forEach(function(e){return r=p(r,"fields."+e+".touched",!0)}),n.length&&(r=p(r,"anyTouched",!0)),r}),r(s,i.SET_SUBMIT_SUCCEEDED,function(e){var t=e;return t=d(t,"submitFailed"),t=p(t,"submitSucceeded",!0)}),r(s,i.TOUCH,function(e,t){var n=t.meta.fields,r=e;return n.forEach(function(e){return r=p(r,"fields."+e+".touched",!0)}),r=p(r,"anyTouched",!0)}),r(s,i.UNREGISTER_FIELD,function(e,t){var n=t.payload,r=n.name,o=n.destroyOnUnmount,i=e,a="registeredFields['"+r+"']",u=f(i,a);if(!u)return i;var s=f(u,"count")-1;return s<=0&&o?(i=d(i,a),c(f(i,"registeredFields"),l)&&(i=d(i,"registeredFields"))):(u=p(u,"count",s),i=p(i,a,u)),i}),r(s,i.UNTOUCH,function(e,t){var n=t.meta.fields,r=e;n.forEach(function(e){return r=d(r,"fields."+e+".touched")});var o=v(f(r,"registeredFields")).some(function(e){return f(r,"fields."+e+".touched")});return r=o?p(r,"anyTouched",!0):d(r,"anyTouched")}),r(s,i.UPDATE_SYNC_ERRORS,function(e,t){var n=t.payload,r=n.syncErrors,o=n.error,i=e;return o?(i=p(i,"error",o),i=p(i,"syncError",!0)):(i=d(i,"error"),i=d(i,"syncError")),i=Object.keys(r).length?p(i,"syncErrors",r):d(i,"syncErrors")}),r(s,i.UPDATE_SYNC_WARNINGS,function(e,t){var n=t.payload,r=n.syncWarnings,o=n.warning,i=e;return i=o?p(i,"warning",o):d(i,"warning"),i=Object.keys(r).length?p(i,"syncWarnings",r):d(i,"syncWarnings")}),s),C=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,t=arguments[1],n=x[t.type];return n?n(e,t):e};return t(function(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n&&n.meta&&n.meta.form;if(!r)return t;if(n.type===i.DESTROY)return n.meta.form.reduce(function(e,t){return g(e,t)},t);var o=f(t,r),a=e(o,n);return a===o?t:p(t,r,a)}}(C))};t.a=s},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}var s=n(561),c=n(228),l=n(15),f=(n.n(l),n(208)),p=n.n(f),d=n(68),h=n(110),v=n(139),m=n.n(v),y=n(696),g=n(260),b=n(671),_=n(264),E=n(668),w=n(661),x=n(664),C=n(665),S=n(42),P=n(670),O=n(175),T=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),k=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},R=function(e){return Boolean(e&&e.prototype&&"object"===A(e.prototype.isReactComponent))},I=g.arrayInsert,N=g.arrayMove,M=g.arrayPop,j=g.arrayPush,F=g.arrayRemove,D=g.arrayRemoveAll,U=g.arrayShift,L=g.arraySplice,V=g.arraySwap,B=g.arrayUnshift,W=g.blur,q=g.change,H=g.focus,z=u(g,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","blur","change","focus"]),Y={arrayInsert:I,arrayMove:N,arrayPop:M,arrayPush:j,arrayRemove:F,arrayRemoveAll:D,arrayShift:U,arraySplice:L,arraySwap:V,arrayUnshift:B},K=[].concat(function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}(Object.keys(g)),["array","asyncErrors","initialized","initialValues","syncErrors","syncWarnings","values","registeredFields"]),G=function(e){if(!e||"function"!=typeof e)throw new Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return e},$=function(e){var t=e.deepEqual,f=e.empty,v=e.getIn,g=e.setIn,A=e.keys,I=e.fromJS,N=n.i(O.a)(e);return function(O){var M=k({touchOnBlur:!0,touchOnChange:!1,persistentSubmitErrors:!1,destroyOnUnmount:!0,shouldAsyncValidate:x.a,shouldValidate:C.a,enableReinitialize:!1,keepDirtyOnReinitialize:!1,getFormState:function(e){return v(e,"form")},pure:!0,forceUnregisterOnUnmount:!1},O);return function(x){var C=function(c){function f(e){o(this,f);var t=i(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,e));return t.submit=t.submit.bind(t),t.reset=t.reset.bind(t),t.asyncValidate=t.asyncValidate.bind(t),t.getValues=t.getValues.bind(t),t.register=t.register.bind(t),t.unregister=t.unregister.bind(t),t.submitCompleted=t.submitCompleted.bind(t),t.submitFailed=t.submitFailed.bind(t),t.fieldValidators={},t.lastFieldValidatorKeys=[],t.fieldWarners={},t.lastFieldWarnerKeys=[],t}return a(f,c),T(f,[{key:"getChildContext",value:function(){var e=this;return{_reduxForm:k({},this.props,{getFormState:function(t){return v(e.props.getFormState(t),e.props.form)},asyncValidate:this.asyncValidate,getValues:this.getValues,sectionPrefix:void 0,register:this.register,unregister:this.unregister,registerInnerOnSubmit:function(t){return e.innerOnSubmit=t}})}}},{key:"initIfNeeded",value:function(e){var n=this.props.enableReinitialize;if(e){if((n||!e.initialized)&&!t(this.props.initialValues,e.initialValues)){var r=e.initialized&&this.props.keepDirtyOnReinitialize;this.props.initialize(e.initialValues,r)}}else!this.props.initialValues||this.props.initialized&&!n||this.props.initialize(this.props.initialValues,this.props.keepDirtyOnReinitialize)}},{key:"updateSyncErrorsIfNeeded",value:function(e,t){var n=this.props,r=n.error,o=n.syncErrors,i=n.updateSyncErrors,a=!(o&&Object.keys(o).length||r),u=!(e&&Object.keys(e).length||t);a&&u||S.a.deepEqual(o,e)&&S.a.deepEqual(r,t)||i(e,t)}},{key:"clearSubmitPromiseIfNeeded",value:function(e){var t=this.props.submitting;this.submitPromise&&t&&!e.submitting&&delete this.submitPromise}},{key:"submitIfNeeded",value:function(e){var t=this.props,n=t.clearSubmit;!t.triggerSubmit&&e.triggerSubmit&&(n(),this.submit())}},{key:"validateIfNeeded",value:function(t){var r=this.props,o=r.shouldValidate,i=r.validate,a=r.values,c=this.generateValidator();if(i||c){var l=void 0===t,f=Object.keys(this.getValidators());if(o({values:a,nextProps:t,props:this.props,initialRender:l,lastFieldValidatorKeys:this.lastFieldValidatorKeys,fieldValidatorKeys:f,structure:e})){var p=l?this.props:t,d=n.i(s.a)(i?i(p.values,p)||{}:{},c?c(p.values,p)||{}:{}),h=d._error,v=u(d,["_error"]);this.lastFieldValidatorKeys=f,this.updateSyncErrorsIfNeeded(v,h)}}}},{key:"updateSyncWarningsIfNeeded",value:function(e,t){var n=this.props,r=n.warning,o=n.syncWarnings,i=n.updateSyncWarnings,a=!(o&&Object.keys(o).length||r),u=!(e&&Object.keys(e).length||t);a&&u||S.a.deepEqual(o,e)&&S.a.deepEqual(r,t)||i(e,t)}},{key:"warnIfNeeded",value:function(t){var r=this.props,o=r.shouldValidate,i=r.warn,a=r.values,c=this.generateWarner();if(i||c){var l=void 0===t,f=Object.keys(this.getWarners());if(o({values:a,nextProps:t,props:this.props,initialRender:l,lastFieldValidatorKeys:this.lastFieldWarnerKeys,fieldValidatorKeys:f,structure:e})){var p=l?this.props:t,d=n.i(s.a)(i?i(p.values,p):{},c?c(p.values,p):{}),h=d._warning,v=u(d,["_warning"]);this.lastFieldWarnerKeys=f,this.updateSyncWarningsIfNeeded(v,h)}}}},{key:"componentWillMount",value:function(){this.initIfNeeded(),this.validateIfNeeded(),this.warnIfNeeded()}},{key:"componentWillReceiveProps",value:function(e){this.initIfNeeded(e),this.validateIfNeeded(e),this.warnIfNeeded(e),this.clearSubmitPromiseIfNeeded(e),this.submitIfNeeded(e),e.onChange&&(t(e.values,this.props.values)||e.onChange(e.values,e.dispatch,e))}},{key:"shouldComponentUpdate",value:function(e){var n=this;return!this.props.pure||Object.keys(e).some(function(r){return!~K.indexOf(r)&&!t(n.props[r],e[r])})}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.destroyOnUnmount,n=e.destroy;t&&(this.destroyed=!0,n())}},{key:"getValues",value:function(){return this.props.values}},{key:"isValid",value:function(){return this.props.valid}},{key:"isPristine",value:function(){return this.props.pristine}},{key:"register",value:function(e,t,n,r){this.props.registerField(e,t),n&&(this.fieldValidators[e]=n),r&&(this.fieldWarners[e]=r)}},{key:"unregister",value:function(e){this.destroyed||(this.props.destroyOnUnmount||this.props.forceUnregisterOnUnmount?(this.props.unregisterField(e),delete this.fieldValidators[e],delete this.fieldWarners[e]):this.props.unregisterField(e,!1))}},{key:"getFieldList",value:function(e){var t=this.props.registeredFields,n=[];if(!t)return n;var r=A(t);return e&&e.excludeFieldArray&&(r=r.filter(function(e){return"FieldArray"!==v(t,"['"+e+"'].type")})),I(r.reduce(function(e,t){return e.push(t),e},n))}},{key:"getValidators",value:function(){var e=this,t={};return Object.keys(this.fieldValidators).forEach(function(n){var r=e.fieldValidators[n]();r&&(t[n]=r)}),t}},{key:"generateValidator",value:function(){var t=this.getValidators();return Object.keys(t).length?n.i(P.a)(t,e):void 0}},{key:"getWarners",value:function(){var e=this,t={};return Object.keys(this.fieldWarners).forEach(function(n){var r=e.fieldWarners[n]();r&&(t[n]=r)}),t}},{key:"generateWarner",value:function(){var t=this.getWarners();return Object.keys(t).length?n.i(P.a)(t,e):void 0}},{key:"asyncValidate",value:function(e,t){var r=this,o=this.props,i=o.asyncBlurFields,a=o.asyncErrors,u=o.asyncValidate,s=o.dispatch,c=o.initialized,l=o.pristine,f=o.shouldAsyncValidate,p=o.startAsyncValidation,d=o.stopAsyncValidation,h=o.syncErrors,m=o.values,y=!e;if(u){var b=y?m:g(m,e,t),_=y||!v(h,e);if((!y&&(!i||~i.indexOf(e.replace(/\[[0-9]+\]/g,"[]")))||y)&&f({asyncErrors:a,initialized:c,trigger:y?"submit":"blur",blurredField:e,pristine:l,syncValidationPasses:_}))return n.i(w.a)(function(){return u(b,s,r.props,e)},p,d,e)}}},{key:"submitCompleted",value:function(e){return delete this.submitPromise,e}},{key:"submitFailed",value:function(e){throw delete this.submitPromise,e}},{key:"listenToSubmit",value:function(e){return m()(e)?(this.submitPromise=e,e.then(this.submitCompleted,this.submitFailed)):e}},{key:"submit",value:function(e){var t=this,r=this.props,o=r.onSubmit,i=r.blur,a=r.change,u=r.dispatch,s=r.validExceptSubmit;return e&&!n.i(_.a)(e)?n.i(E.a)(function(){return!t.submitPromise&&t.listenToSubmit(n.i(b.a)(G(e),k({},t.props,n.i(h.bindActionCreators)({blur:i,change:a},u)),s,t.asyncValidate,t.getFieldList({excludeFieldArray:!0})))}):this.submitPromise?void 0:this.innerOnSubmit?this.innerOnSubmit():this.listenToSubmit(n.i(b.a)(G(o),k({},this.props,n.i(h.bindActionCreators)({blur:i,change:a},u)),s,this.asyncValidate,this.getFieldList({excludeFieldArray:!0})))}},{key:"reset",value:function(){this.props.reset()}},{key:"render",value:function(){var e=this.props,t=e.anyTouched,o=(e.arrayInsert,e.arrayMove,e.arrayPop,e.arrayPush,e.arrayRemove,e.arrayRemoveAll,e.arrayShift,e.arraySplice,e.arraySwap,e.arrayUnshift,e.asyncErrors,e.asyncValidate,e.asyncValidating),i=e.blur,a=e.change,s=e.destroy,c=(e.destroyOnUnmount,e.forceUnregisterOnUnmount,e.dirty),f=e.dispatch,p=(e.enableReinitialize,e.error),d=(e.focus,e.form),v=(e.getFormState,e.initialize),m=e.initialized,y=e.initialValues,g=e.invalid,b=(e.keepDirtyOnReinitialize,e.pristine),_=e.propNamespace,E=(e.registeredFields,e.registerField,e.reset),w=(e.setSubmitFailed,e.setSubmitSucceeded,e.shouldAsyncValidate,e.shouldValidate,e.startAsyncValidation,e.startSubmit,e.stopAsyncValidation,e.stopSubmit,e.submitting),C=e.submitFailed,S=e.submitSucceeded,P=e.touch,O=(e.touchOnBlur,e.touchOnChange,e.persistentSubmitErrors,e.syncErrors,e.syncWarnings,e.unregisterField,e.untouch),T=(e.updateSyncErrors,e.updateSyncWarnings,e.valid),A=(e.validExceptSubmit,e.values,e.warning),I=u(e,["anyTouched","arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncErrors","asyncValidate","asyncValidating","blur","change","destroy","destroyOnUnmount","forceUnregisterOnUnmount","dirty","dispatch","enableReinitialize","error","focus","form","getFormState","initialize","initialized","initialValues","invalid","keepDirtyOnReinitialize","pristine","propNamespace","registeredFields","registerField","reset","setSubmitFailed","setSubmitSucceeded","shouldAsyncValidate","shouldValidate","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitting","submitFailed","submitSucceeded","touch","touchOnBlur","touchOnChange","persistentSubmitErrors","syncErrors","syncWarnings","unregisterField","untouch","updateSyncErrors","updateSyncWarnings","valid","validExceptSubmit","values","warning"]),N=k({anyTouched:t,asyncValidate:this.asyncValidate,asyncValidating:o},n.i(h.bindActionCreators)({blur:i,change:a},f),{destroy:s,dirty:c,dispatch:f,error:p,form:d,handleSubmit:this.submit,initialize:v,initialized:m,initialValues:y,invalid:g,pristine:b,reset:E,submitting:w,submitFailed:C,submitSucceeded:S,touch:P,untouch:O,valid:T,warning:A}),M=k({},_?r({},_,N):N,I);return R(x)&&(M.ref="wrapped"),n.i(l.createElement)(x,M)}}]),f}(l.Component);C.displayName="Form("+n.i(y.a)(x)+")",C.WrappedComponent=x,C.childContextTypes={_reduxForm:l.PropTypes.object.isRequired},C.propTypes={destroyOnUnmount:l.PropTypes.bool,forceUnregisterOnUnmount:l.PropTypes.bool,form:l.PropTypes.string.isRequired,initialValues:l.PropTypes.object,getFormState:l.PropTypes.func,onSubmitFail:l.PropTypes.func,onSubmitSuccess:l.PropTypes.func,propNameSpace:l.PropTypes.string,validate:l.PropTypes.func,warn:l.PropTypes.func,touchOnBlur:l.PropTypes.bool,touchOnChange:l.PropTypes.bool,triggerSubmit:l.PropTypes.bool,persistentSubmitErrors:l.PropTypes.bool,registeredFields:l.PropTypes.any};var O=n.i(d.connect)(function(e,n){var r=n.form,o=n.getFormState,i=n.initialValues,a=n.enableReinitialize,u=n.keepDirtyOnReinitialize,s=v(o(e)||f,r)||f,c=v(s,"initial"),l=!!c,p=a&&l&&!t(i,c),d=p&&!u,h=i||c||f;p&&(h=c||f);var m=v(s,"values")||h;d&&(m=h);var y=d||t(h,m),g=v(s,"asyncErrors"),b=v(s,"syncErrors")||{},_=v(s,"syncWarnings")||{},E=v(s,"registeredFields"),w=N(r,o,!1)(e),x=N(r,o,!0)(e),C=!!v(s,"anyTouched"),S=!!v(s,"submitting"),P=!!v(s,"submitFailed"),O=!!v(s,"submitSucceeded"),T=v(s,"error"),k=v(s,"warning"),A=v(s,"triggerSubmit");return{anyTouched:C,asyncErrors:g,asyncValidating:v(s,"asyncValidating")||!1,dirty:!y,error:T,initialized:l,invalid:!w,pristine:y,registeredFields:E,submitting:S,submitFailed:P,submitSucceeded:O,syncErrors:b,syncWarnings:_,triggerSubmit:A,values:m,valid:w,validExceptSubmit:x,warning:k}},function(e,t){var r=function(e){return e.bind(null,t.form)},o=n.i(c.a)(z,r),i=n.i(c.a)(Y,r),a=function(e,n){return W(t.form,e,n,!!t.touchOnBlur)},u=function(e,n){return q(t.form,e,n,!!t.touchOnChange,!!t.persistentSubmitErrors)},s=r(H),l=n.i(h.bindActionCreators)(o,e),f={insert:n.i(h.bindActionCreators)(i.arrayInsert,e),move:n.i(h.bindActionCreators)(i.arrayMove,e),pop:n.i(h.bindActionCreators)(i.arrayPop,e),push:n.i(h.bindActionCreators)(i.arrayPush,e),remove:n.i(h.bindActionCreators)(i.arrayRemove,e),removeAll:n.i(h.bindActionCreators)(i.arrayRemoveAll,e),shift:n.i(h.bindActionCreators)(i.arrayShift,e),splice:n.i(h.bindActionCreators)(i.arraySplice,e),swap:n.i(h.bindActionCreators)(i.arraySwap,e),unshift:n.i(h.bindActionCreators)(i.arrayUnshift,e)},p=k({},l,i,{blur:a,change:u,array:f,focus:s,dispatch:e});return function(){return p}},void 0,{withRef:!0}),j=p()(O(C),x);return j.defaultProps=M,function(e){function t(){return o(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),T(t,[{key:"submit",value:function(){return this.refs.wrapped.getWrappedInstance().submit()}},{key:"reset",value:function(){return this.refs.wrapped.getWrappedInstance().reset()}},{key:"render",value:function(){var e=this.props,t=e.initialValues,r=u(e,["initialValues"]);return n.i(l.createElement)(j,k({},r,{ref:"wrapped",initialValues:I(t)}))}},{key:"valid",get:function(){return this.refs.wrapped.getWrappedInstance().isValid()}},{key:"invalid",get:function(){return!this.valid}},{key:"pristine",get:function(){return this.refs.wrapped.getWrappedInstance().isPristine()}},{key:"dirty",get:function(){return!this.pristine}},{key:"values",get:function(){return this.refs.wrapped.getWrappedInstance().getValues()}},{key:"fieldList",get:function(){return this.refs.wrapped.getWrappedInstance().getFieldList()}},{key:"wrappedInstance",get:function(){return this.refs.wrapped.getWrappedInstance().refs.wrapped}}]),t}(l.Component)}}};t.a=$},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".asyncErrors")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".initial")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn,n=e.keys;return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(e){return t(e,"form")};return function(t){return n(e(t))}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".submitErrors")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".syncErrors")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".syncWarnings")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){return t(n(r),e+".values")}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){var o=n(r);return t(o,e+".submitFailed")||!1}}};t.a=r},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){var o=n(r);return t(o,e+".submitSucceeded")||!1}}};t.a=r},function(e,t,n){"use strict";var r=n(266),o=function(e){return function(t,o){var i=n.i(r.a)(e)(t,o);return function(e){return!i(e)}}};t.a=o},function(e,t,n){"use strict";var r=n(175),o=function(e){return function(t,o){var i=n.i(r.a)(e)(t,o);return function(e){return!i(e)}}};t.a=o},function(e,t,n){"use strict";var r=function(e){var t=e.getIn;return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e){return t(e,"form")};return function(r){var o=n(r);return t(o,e+".submitting")||!1}}};t.a=r},function(e,t,n){"use strict";var r=n(226),o=function(e,t){return e===t||(!(null!=e&&""!==e&&!1!==e||null!=t&&""!==t&&!1!==t)||(!e||!t||e._error===t._error)&&((!e||!t||e._warning===t._warning)&&void 0))},i=function(e,t){return n.i(r.a)(e,t,o)};t.a=i},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var i=n(103),a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function e(t,n){for(var i=arguments.length,u=Array(i>2?i-2:0),s=2;s<i;s++)u[s-2]=arguments[s];if(void 0===t||void 0===n)return t;if(u.length){if(Array.isArray(t)){if(n<t.length){var c=e.apply(void 0,[t&&t[n]].concat(u));if(c!==t[n]){var l=[].concat(o(t));return l[n]=c,l}}return t}if(n in t){var f=e.apply(void 0,[t&&t[n]].concat(u));return t[n]===f?t:a({},t,r({},n,f))}return t}if(Array.isArray(t)){if(isNaN(n))throw new Error("Cannot delete non-numerical index from an array");if(n<t.length){var p=[].concat(o(t));return p.splice(n,1),p}return t}if(n in t){var d=a({},t);return delete d[n],d}return t},s=function(e,t){return u.apply(void 0,[e].concat(o(n.i(i.a)(t))))};t.a=s},function(e,t,n){"use strict";var r=n(103),o=function(e,t){if(!e)return e;var o=n.i(r.a)(t),i=o.length;if(i){for(var a=e,u=0;u<i&&a;++u)a=a[o[u]];return a}};t.a=o},function(e,t,n){"use strict";var r=function(e){return e?Object.keys(e):[]};t.a=r},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o=n(103),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function e(t,n,o,a){if(a>=o.length)return n;var u=o[a],s=e(t&&t[u],n,o,a+1);if(!t){var c=isNaN(u)?{}:[];return c[u]=s,c}if(Array.isArray(t)){var l=[].concat(t);return l[u]=s,l}return i({},t,r({},u,s))},u=function(e,t,r){return a(e,r,n.i(o.a)(t),0)};t.a=u},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}var o=function(e,t,n,o){if(e=e||[],t<e.length){if(void 0===o&&!n){var i=[].concat(r(e));return i.splice(t,0,null),i[t]=void 0,i}if(null!=o){var a=[].concat(r(e));return a.splice(t,n,o),a}var u=[].concat(r(e));return u.splice(t,n),u}if(n)return e;var s=[].concat(r(e));return s[t]=o,s};t.a=o},function(e,t,n){"use strict";n.d(t,"a",function(){return r});var r="text"},function(e,t,n){"use strict";var r=function(e){return e.displayName||e.name||"Component"};t.a=r},function(e,t,n){"use strict";function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var o=n(68),i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(e){var t=e.getIn;return function(e){var a=i({prop:"values",getFormState:function(e){return t(e,"form")}},e),u=a.form,s=a.prop,c=a.getFormState;return n.i(o.connect)(function(e){return r({},s,t(c(e),u+".values"))},function(){return{}})}};t.a=a},function(e,t,n){"use strict";function r(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){return function(n,r,a){var u=e(n,r,a),s=u.dispatch,c=[],l={getState:u.getState,dispatch:function(e){return s(e)}};return c=t.map(function(e){return e(l)}),s=o.a.apply(void 0,c)(u.dispatch),i({},u,{dispatch:s})}}}var o=n(268);t.a=r;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){"use strict";function r(e,t){return function(){return t(e.apply(void 0,arguments))}}function o(e,t){if("function"==typeof e)return r(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var n=Object.keys(e),o={},i=0;i<n.length;i++){var a=n[i],u=e[a];"function"==typeof u&&(o[a]=r(u,t))}return o}t.a=o},function(e,t,n){"use strict";function r(e,t){var n=t&&t.type;return"Given action "+(n&&'"'+n.toString()+'"'||"an action")+', reducer "'+e+'" returned undefined. To ignore an action, you must explicitly return the previous state.'}function o(e){Object.keys(e).forEach(function(t){var n=e[t];if(void 0===n(void 0,{type:a.b.INIT}))throw new Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');if(void 0===n(void 0,{type:"@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".")}))throw new Error('Reducer "'+t+"\" returned undefined when probed with a random type. Don't try to handle "+a.b.INIT+' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.')})}function i(e){for(var t=Object.keys(e),n={},i=0;i<t.length;i++){var a=t[i];"function"==typeof e[a]&&(n[a]=e[a])}var u,s=Object.keys(n);try{o(n)}catch(e){u=e}return function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments[1];if(u)throw u;for(var o=!1,i={},a=0;a<s.length;a++){var c=s[a],l=n[c],f=e[c],p=l(f,t);if(void 0===p){var d=r(c,t);throw new Error(d)}i[c]=p,o=o||p!==f}return o?i:e}}var a=n(269);n(101),n(270);t.a=i},function(e,t,n){(function(t,n){!function(t){"use strict";function r(e,t,n,r){var o=t&&t.prototype instanceof i?t:i,a=Object.create(o.prototype),u=new h(r||[]);return a._invoke=l(e,n,u),a}function o(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}function i(){}function a(){}function u(){}function s(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function c(e){function t(n,r,i,a){var u=o(e[n],e,r);if("throw"!==u.type){var s=u.arg,c=s.value;return c&&"object"==typeof c&&b.call(c,"__await")?Promise.resolve(c.__await).then(function(e){t("next",e,i,a)},function(e){t("throw",e,i,a)}):Promise.resolve(c).then(function(e){s.value=e,i(s)},a)}a(u.arg)}function r(e,n){function r(){return new Promise(function(r,o){t(e,n,r,o)})}return i=i?i.then(r,r):r()}"object"==typeof n&&n.domain&&(t=n.domain.bind(t));var i;this._invoke=r}function l(e,t,n){var r=S;return function(i,a){if(r===O)throw new Error("Generator is already running");if(r===T){if("throw"===i)throw a;return m()}for(n.method=i,n.arg=a;;){var u=n.delegate;if(u){var s=f(u,n);if(s){if(s===k)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===S)throw r=T,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=O;var c=o(e,t,n);if("normal"===c.type){if(r=n.done?T:P,c.arg===k)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r=T,n.method="throw",n.arg=c.arg)}}}function f(e,t){var n=e.iterator[t.method];if(n===y){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=y,f(e,t),"throw"===t.method))return k;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return k}var r=o(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,k;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=y),t.delegate=null,k):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,k)}function p(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function d(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function h(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(p,this),this.reset(!0)}function v(e){if(e){var t=e[E];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n<e.length;)if(b.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=y,t.done=!0,t};return r.next=r}}return{next:m}}function m(){return{value:y,done:!0}}var y,g=Object.prototype,b=g.hasOwnProperty,_="function"==typeof Symbol?Symbol:{},E=_.iterator||"@@iterator",w=_.toStringTag||"@@toStringTag",x="object"==typeof e,C=t.regeneratorRuntime;if(C)return void(x&&(e.exports=C));C=t.regeneratorRuntime=x?e.exports:{},C.wrap=r;var S="suspendedStart",P="suspendedYield",O="executing",T="completed",k={},A={};A[E]=function(){return this};var R=Object.getPrototypeOf,I=R&&R(R(v([])));I&&I!==g&&b.call(I,E)&&(A=I);var N=u.prototype=i.prototype=Object.create(A);a.prototype=N.constructor=u,u.constructor=a,u[w]=a.displayName="GeneratorFunction",C.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===a||"GeneratorFunction"===(t.displayName||t.name))},C.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,w in e||(e[w]="GeneratorFunction")),e.prototype=Object.create(N),e},C.awrap=function(e){return{__await:e}},s(c.prototype),C.AsyncIterator=c,C.async=function(e,t,n,o){var i=new c(r(e,t,n,o));return C.isGeneratorFunction(t)?i:i.next().then(function(e){return e.done?e.value:i.next()})},s(N),N[w]="Generator",N.toString=function(){return"[object Generator]"},C.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},C.values=v,h.prototype={constructor:h,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=y,this.done=!1,this.delegate=null,this.method="next",this.arg=y,this.tryEntries.forEach(d),!e)for(var t in this)"t"===t.charAt(0)&&b.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=y)},stop:function(){this.done=!0;var e=this.tryEntries[0],t=e.completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){function t(t,r){return i.type="throw",i.arg=e,n.next=t,r&&(n.method="next",n.arg=y),!!r}if(this.done)throw e;for(var n=this,r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r],i=o.completion;if("root"===o.tryLoc)return t("end");if(o.tryLoc<=this.prev){var a=b.call(o,"catchLoc"),u=b.call(o,"finallyLoc");if(a&&u){if(this.prev<o.catchLoc)return t(o.catchLoc,!0);if(this.prev<o.finallyLoc)return t(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return t(o.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return t(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&b.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=e,i.arg=t,o?(this.method="next",this.next=o.finallyLoc,k):this.complete(i)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),k},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),d(n),k}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;d(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:v(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=y),k}}}("object"==typeof t?t:"object"==typeof window?window:"object"==typeof self?self:this)}).call(t,n(111),n(154))},function(e,t,n){e.exports=n(703)},function(e,t,n){"use strict";(function(e,r){Object.defineProperty(t,"__esModule",{value:!0});var o,i=n(704),a=function(e){return e&&e.__esModule?e:{default:e}}(i);o="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:r;var u=(0,a.default)(o);t.default=u}).call(t,n(111),n(705)(e))},function(e,t,n){"use strict";function r(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){n(272),e.exports=n(271)}]); |
ajax/libs/onsen/1.3.9/js/onsenui.js | holtkamp/cdnjs | /*! onsenui - v1.3.9 - 2015-09-07 */
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// JavaScript Dynamic Content shim for Windows Store apps
(function () {
if (window.MSApp && MSApp.execUnsafeLocalFunction) {
// Some nodes will have an "attributes" property which shadows the Node.prototype.attributes property
// and means we don't actually see the attributes of the Node (interestingly the VS debug console
// appears to suffer from the same issue).
//
var Element_setAttribute = Object.getOwnPropertyDescriptor(Element.prototype, "setAttribute").value;
var Element_removeAttribute = Object.getOwnPropertyDescriptor(Element.prototype, "removeAttribute").value;
var HTMLElement_insertAdjacentHTMLPropertyDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "insertAdjacentHTML");
var Node_get_attributes = Object.getOwnPropertyDescriptor(Node.prototype, "attributes").get;
var Node_get_childNodes = Object.getOwnPropertyDescriptor(Node.prototype, "childNodes").get;
var detectionDiv = document.createElement("div");
function getAttributes(element) {
return Node_get_attributes.call(element);
}
function setAttribute(element, attribute, value) {
try {
Element_setAttribute.call(element, attribute, value);
} catch (e) {
// ignore
}
}
function removeAttribute(element, attribute) {
Element_removeAttribute.call(element, attribute);
}
function childNodes(element) {
return Node_get_childNodes.call(element);
}
function empty(element) {
while (element.childNodes.length) {
element.removeChild(element.lastChild);
}
}
function insertAdjacentHTML(element, position, html) {
HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element, position, html);
}
function inUnsafeMode() {
var isUnsafe = true;
try {
detectionDiv.innerHTML = "<test/>";
}
catch (ex) {
isUnsafe = false;
}
return isUnsafe;
}
function cleanse(html, targetElement) {
var cleaner = document.implementation.createHTMLDocument("cleaner");
empty(cleaner.documentElement);
MSApp.execUnsafeLocalFunction(function () {
insertAdjacentHTML(cleaner.documentElement, "afterbegin", html);
});
var scripts = cleaner.documentElement.querySelectorAll("script");
Array.prototype.forEach.call(scripts, function (script) {
switch (script.type.toLowerCase()) {
case "":
script.type = "text/inert";
break;
case "text/javascript":
case "text/ecmascript":
case "text/x-javascript":
case "text/jscript":
case "text/livescript":
case "text/javascript1.1":
case "text/javascript1.2":
case "text/javascript1.3":
script.type = "text/inert-" + script.type.slice("text/".length);
break;
case "application/javascript":
case "application/ecmascript":
case "application/x-javascript":
script.type = "application/inert-" + script.type.slice("application/".length);
break;
default:
break;
}
});
function cleanseAttributes(element) {
var attributes = getAttributes(element);
if (attributes && attributes.length) {
// because the attributes collection is live it is simpler to queue up the renames
var events;
for (var i = 0, len = attributes.length; i < len; i++) {
var attribute = attributes[i];
var name = attribute.name;
if ((name[0] === "o" || name[0] === "O") &&
(name[1] === "n" || name[1] === "N")) {
events = events || [];
events.push({ name: attribute.name, value: attribute.value });
}
}
if (events) {
for (var i = 0, len = events.length; i < len; i++) {
var attribute = events[i];
removeAttribute(element, attribute.name);
setAttribute(element, "x-" + attribute.name, attribute.value);
}
}
}
var children = childNodes(element);
for (var i = 0, len = children.length; i < len; i++) {
cleanseAttributes(children[i]);
}
}
cleanseAttributes(cleaner.documentElement);
var cleanedNodes = [];
if (targetElement.tagName === 'HTML') {
cleanedNodes = Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes);
} else {
if (cleaner.head) {
cleanedNodes = cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes));
}
if (cleaner.body) {
cleanedNodes = cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes));
}
}
return cleanedNodes;
}
function cleansePropertySetter(property, setter) {
var propertyDescriptor = Object.getOwnPropertyDescriptor(HTMLElement.prototype, property);
var originalSetter = propertyDescriptor.set;
Object.defineProperty(HTMLElement.prototype, property, {
get: propertyDescriptor.get,
set: function (value) {
if(window.WinJS && window.WinJS._execUnsafe && inUnsafeMode()) {
originalSetter.call(this, value);
} else {
var that = this;
var nodes = cleanse(value, that);
MSApp.execUnsafeLocalFunction(function () {
setter(propertyDescriptor, that, nodes);
});
}
},
enumerable: propertyDescriptor.enumerable,
configurable: propertyDescriptor.configurable,
});
}
cleansePropertySetter("innerHTML", function (propertyDescriptor, target, elements) {
empty(target);
for (var i = 0, len = elements.length; i < len; i++) {
target.appendChild(elements[i]);
}
});
cleansePropertySetter("outerHTML", function (propertyDescriptor, target, elements) {
for (var i = 0, len = elements.length; i < len; i++) {
target.insertAdjacentElement("afterend", elements[i]);
}
target.parentNode.removeChild(target);
});
}
}());
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
;(function () {
'use strict';
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults
*/
function FastClick(layer, options) {
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
/**
* The maximum time for a tap
*
* @type number
*/
this.tapTimeout = options.tapTimeout || 700;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
*
* @type boolean
*/
var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0-7.* requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);
/**
* BlackBerry requires exceptions.
*
* @type boolean
*/
var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
// random integers, it's safe to to continue if the identifier is 0 here.
if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay && (event.timeStamp - this.lastClickTime) > -1) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay && (event.timeStamp - this.lastClickTime) > -1) {
this.cancelNextClick = true;
return true;
}
if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
var metaViewport;
var chromeVersion;
var blackberryVersion;
var firefoxVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
if (deviceIsBlackBerry10) {
blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
// BlackBerry 10.3+ does not require Fastclick library.
// https://github.com/ftlabs/fastclick/issues/251
if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// user-scalable=no eliminates click delay.
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// width=device-width (or less than device-width) eliminates click delay.
if (document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
}
}
// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
return true;
}
// Firefox version - zero for other browsers
firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (firefoxVersion >= 27) {
// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
return true;
}
}
// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults
*/
FastClick.attach = function(layer, options) {
return new FastClick(layer, options);
};
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
}());
/*! Hammer.JS - v1.1.3 - 2014-05-20
* http://eightmedia.github.io/hammer.js
*
* Copyright (c) 2014 Jorik Tangelder <[email protected]>;
* Licensed under the MIT license */
(function(window, undefined) {
'use strict';
/**
* @main
* @module hammer
*
* @class Hammer
* @static
*/
/**
* Hammer, use this to create instances
* ````
* var hammertime = new Hammer(myElement);
* ````
*
* @method Hammer
* @param {HTMLElement} element
* @param {Object} [options={}]
* @return {Hammer.Instance}
*/
var Hammer = function Hammer(element, options) {
return new Hammer.Instance(element, options || {});
};
/**
* version, as defined in package.json
* the value will be set at each build
* @property VERSION
* @final
* @type {String}
*/
Hammer.VERSION = '1.1.3';
/**
* default settings.
* more settings are defined per gesture at `/gestures`. Each gesture can be disabled/enabled
* by setting it's name (like `swipe`) to false.
* You can set the defaults for all instances by changing this object before creating an instance.
* @example
* ````
* Hammer.defaults.drag = false;
* Hammer.defaults.behavior.touchAction = 'pan-y';
* delete Hammer.defaults.behavior.userSelect;
* ````
* @property defaults
* @type {Object}
*/
Hammer.defaults = {
/**
* this setting object adds styles and attributes to the element to prevent the browser from doing
* its native behavior. The css properties are auto prefixed for the browsers when needed.
* @property defaults.behavior
* @type {Object}
*/
behavior: {
/**
* Disables text selection to improve the dragging gesture. When the value is `none` it also sets
* `onselectstart=false` for IE on the element. Mainly for desktop browsers.
* @property defaults.behavior.userSelect
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Specifies whether and how a given region can be manipulated by the user (for instance, by panning or zooming).
* Used by Chrome 35> and IE10>. By default this makes the element blocking any touch event.
* @property defaults.behavior.touchAction
* @type {String}
* @default: 'pan-y'
*/
touchAction: 'pan-y',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @property defaults.behavior.touchCallout
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @property defaults.behavior.contentZooming
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its contents.
* Mainly for desktop browsers.
* @property defaults.behavior.userDrag
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in Safari on iPhone. This property obeys the alpha value, if specified.
*
* If you don't specify an alpha value, Safari on iPhone applies a default alpha value
* to the color. To disable tap highlighting, set the alpha value to 0 (invisible).
* If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
* @property defaults.behavior.tapHighlightColor
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
/**
* hammer document where the base events are added at
* @property DOCUMENT
* @type {HTMLElement}
* @default window.document
*/
Hammer.DOCUMENT = document;
/**
* detect support for pointer events
* @property HAS_POINTEREVENTS
* @type {Boolean}
*/
Hammer.HAS_POINTEREVENTS = navigator.pointerEnabled || navigator.msPointerEnabled;
/**
* detect support for touch events
* @property HAS_TOUCHEVENTS
* @type {Boolean}
*/
Hammer.HAS_TOUCHEVENTS = ('ontouchstart' in window);
/**
* detect mobile browsers
* @property IS_MOBILE
* @type {Boolean}
*/
Hammer.IS_MOBILE = /mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent);
/**
* detect if we want to support mouseevents at all
* @property NO_MOUSEEVENTS
* @type {Boolean}
*/
Hammer.NO_MOUSEEVENTS = (Hammer.HAS_TOUCHEVENTS && Hammer.IS_MOBILE) || Hammer.HAS_POINTEREVENTS;
/**
* interval in which Hammer recalculates current velocity/direction/angle in ms
* @property CALCULATE_INTERVAL
* @type {Number}
* @default 25
*/
Hammer.CALCULATE_INTERVAL = 25;
/**
* eventtypes per touchevent (start, move, end) are filled by `Event.determineEventTypes` on `setup`
* the object contains the DOM event names per type (`EVENT_START`, `EVENT_MOVE`, `EVENT_END`)
* @property EVENT_TYPES
* @private
* @writeOnce
* @type {Object}
*/
var EVENT_TYPES = {};
/**
* direction strings, for safe comparisons
* @property DIRECTION_DOWN|LEFT|UP|RIGHT
* @final
* @type {String}
* @default 'down' 'left' 'up' 'right'
*/
var DIRECTION_DOWN = Hammer.DIRECTION_DOWN = 'down';
var DIRECTION_LEFT = Hammer.DIRECTION_LEFT = 'left';
var DIRECTION_UP = Hammer.DIRECTION_UP = 'up';
var DIRECTION_RIGHT = Hammer.DIRECTION_RIGHT = 'right';
/**
* pointertype strings, for safe comparisons
* @property POINTER_MOUSE|TOUCH|PEN
* @final
* @type {String}
* @default 'mouse' 'touch' 'pen'
*/
var POINTER_MOUSE = Hammer.POINTER_MOUSE = 'mouse';
var POINTER_TOUCH = Hammer.POINTER_TOUCH = 'touch';
var POINTER_PEN = Hammer.POINTER_PEN = 'pen';
/**
* eventtypes
* @property EVENT_START|MOVE|END|RELEASE|TOUCH
* @final
* @type {String}
* @default 'start' 'change' 'move' 'end' 'release' 'touch'
*/
var EVENT_START = Hammer.EVENT_START = 'start';
var EVENT_MOVE = Hammer.EVENT_MOVE = 'move';
var EVENT_END = Hammer.EVENT_END = 'end';
var EVENT_RELEASE = Hammer.EVENT_RELEASE = 'release';
var EVENT_TOUCH = Hammer.EVENT_TOUCH = 'touch';
/**
* if the window events are set...
* @property READY
* @writeOnce
* @type {Boolean}
* @default false
*/
Hammer.READY = false;
/**
* plugins namespace
* @property plugins
* @type {Object}
*/
Hammer.plugins = Hammer.plugins || {};
/**
* gestures namespace
* see `/gestures` for the definitions
* @property gestures
* @type {Object}
*/
Hammer.gestures = Hammer.gestures || {};
/**
* setup events to detect gestures on the document
* this function is called when creating an new instance
* @private
*/
function setup() {
if(Hammer.READY) {
return;
}
// find what eventtypes we add listeners to
Event.determineEventTypes();
// Register all gestures inside Hammer.gestures
Utils.each(Hammer.gestures, function(gesture) {
Detection.register(gesture);
});
// Add touch events on the document
Event.onTouch(Hammer.DOCUMENT, EVENT_MOVE, Detection.detect);
Event.onTouch(Hammer.DOCUMENT, EVENT_END, Detection.detect);
// Hammer is ready...!
Hammer.READY = true;
}
/**
* @module hammer
*
* @class Utils
* @static
*/
var Utils = Hammer.utils = {
/**
* extend method, could also be used for cloning when `dest` is an empty object.
* changes the dest object
* @method extend
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge=false] do a merge
* @return {Object} dest
*/
extend: function extend(dest, src, merge) {
for(var key in src) {
if(!src.hasOwnProperty(key) || (dest[key] !== undefined && merge)) {
continue;
}
dest[key] = src[key];
}
return dest;
},
/**
* simple addEventListener wrapper
* @method on
* @param {HTMLElement} element
* @param {String} type
* @param {Function} handler
*/
on: function on(element, type, handler) {
element.addEventListener(type, handler, false);
},
/**
* simple removeEventListener wrapper
* @method off
* @param {HTMLElement} element
* @param {String} type
* @param {Function} handler
*/
off: function off(element, type, handler) {
element.removeEventListener(type, handler, false);
},
/**
* forEach over arrays and objects
* @method each
* @param {Object|Array} obj
* @param {Function} iterator
* @param {any} iterator.item
* @param {Number} iterator.index
* @param {Object|Array} iterator.obj the source object
* @param {Object} context value to use as `this` in the iterator
*/
each: function each(obj, iterator, context) {
var i, len;
// native forEach on arrays
if('forEach' in obj) {
obj.forEach(iterator, context);
// arrays
} else if(obj.length !== undefined) {
for(i = 0, len = obj.length; i < len; i++) {
if(iterator.call(context, obj[i], i, obj) === false) {
return;
}
}
// objects
} else {
for(i in obj) {
if(obj.hasOwnProperty(i) &&
iterator.call(context, obj[i], i, obj) === false) {
return;
}
}
}
},
/**
* find if a string contains the string using indexOf
* @method inStr
* @param {String} src
* @param {String} find
* @return {Boolean} found
*/
inStr: function inStr(src, find) {
return src.indexOf(find) > -1;
},
/**
* find if a array contains the object using indexOf or a simple polyfill
* @method inArray
* @param {String} src
* @param {String} find
* @return {Boolean|Number} false when not found, or the index
*/
inArray: function inArray(src, find) {
if(src.indexOf) {
var index = src.indexOf(find);
return (index === -1) ? false : index;
} else {
for(var i = 0, len = src.length; i < len; i++) {
if(src[i] === find) {
return i;
}
}
return false;
}
},
/**
* convert an array-like object (`arguments`, `touchlist`) to an array
* @method toArray
* @param {Object} obj
* @return {Array}
*/
toArray: function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
},
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
hasParent: function hasParent(node, parent) {
while(node) {
if(node == parent) {
return true;
}
node = node.parentNode;
}
return false;
},
/**
* get the center of all the touches
* @method getCenter
* @param {Array} touches
* @return {Object} center contains `pageX`, `pageY`, `clientX` and `clientY` properties
*/
getCenter: function getCenter(touches) {
var pageX = [],
pageY = [],
clientX = [],
clientY = [],
min = Math.min,
max = Math.max;
// no need to loop when only one touch
if(touches.length === 1) {
return {
pageX: touches[0].pageX,
pageY: touches[0].pageY,
clientX: touches[0].clientX,
clientY: touches[0].clientY
};
}
Utils.each(touches, function(touch) {
pageX.push(touch.pageX);
pageY.push(touch.pageY);
clientX.push(touch.clientX);
clientY.push(touch.clientY);
});
return {
pageX: (min.apply(Math, pageX) + max.apply(Math, pageX)) / 2,
pageY: (min.apply(Math, pageY) + max.apply(Math, pageY)) / 2,
clientX: (min.apply(Math, clientX) + max.apply(Math, clientX)) / 2,
clientY: (min.apply(Math, clientY) + max.apply(Math, clientY)) / 2
};
},
/**
* calculate the velocity between two points. unit is in px per ms.
* @method getVelocity
* @param {Number} deltaTime
* @param {Number} deltaX
* @param {Number} deltaY
* @return {Object} velocity `x` and `y`
*/
getVelocity: function getVelocity(deltaTime, deltaX, deltaY) {
return {
x: Math.abs(deltaX / deltaTime) || 0,
y: Math.abs(deltaY / deltaTime) || 0
};
},
/**
* calculate the angle between two coordinates
* @method getAngle
* @param {Touch} touch1
* @param {Touch} touch2
* @return {Number} angle
*/
getAngle: function getAngle(touch1, touch2) {
var x = touch2.clientX - touch1.clientX,
y = touch2.clientY - touch1.clientY;
return Math.atan2(y, x) * 180 / Math.PI;
},
/**
* do a small comparision to get the direction between two touches.
* @method getDirection
* @param {Touch} touch1
* @param {Touch} touch2
* @return {String} direction matches `DIRECTION_LEFT|RIGHT|UP|DOWN`
*/
getDirection: function getDirection(touch1, touch2) {
var x = Math.abs(touch1.clientX - touch2.clientX),
y = Math.abs(touch1.clientY - touch2.clientY);
if(x >= y) {
return touch1.clientX - touch2.clientX > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return touch1.clientY - touch2.clientY > 0 ? DIRECTION_UP : DIRECTION_DOWN;
},
/**
* calculate the distance between two touches
* @method getDistance
* @param {Touch}touch1
* @param {Touch} touch2
* @return {Number} distance
*/
getDistance: function getDistance(touch1, touch2) {
var x = touch2.clientX - touch1.clientX,
y = touch2.clientY - touch1.clientY;
return Math.sqrt((x * x) + (y * y));
},
/**
* calculate the scale factor between two touchLists
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @method getScale
* @param {Array} start array of touches
* @param {Array} end array of touches
* @return {Number} scale
*/
getScale: function getScale(start, end) {
// need two fingers...
if(start.length >= 2 && end.length >= 2) {
return this.getDistance(end[0], end[1]) / this.getDistance(start[0], start[1]);
}
return 1;
},
/**
* calculate the rotation degrees between two touchLists
* @method getRotation
* @param {Array} start array of touches
* @param {Array} end array of touches
* @return {Number} rotation
*/
getRotation: function getRotation(start, end) {
// need two fingers
if(start.length >= 2 && end.length >= 2) {
return this.getAngle(end[1], end[0]) - this.getAngle(start[1], start[0]);
}
return 0;
},
/**
* find out if the direction is vertical *
* @method isVertical
* @param {String} direction matches `DIRECTION_UP|DOWN`
* @return {Boolean} is_vertical
*/
isVertical: function isVertical(direction) {
return direction == DIRECTION_UP || direction == DIRECTION_DOWN;
},
/**
* set css properties with their prefixes
* @param {HTMLElement} element
* @param {String} prop
* @param {String} value
* @param {Boolean} [toggle=true]
* @return {Boolean}
*/
setPrefixedCss: function setPrefixedCss(element, prop, value, toggle) {
var prefixes = ['', 'Webkit', 'Moz', 'O', 'ms'];
prop = Utils.toCamelCase(prop);
for(var i = 0; i < prefixes.length; i++) {
var p = prop;
// prefixes
if(prefixes[i]) {
p = prefixes[i] + p.slice(0, 1).toUpperCase() + p.slice(1);
}
// test the style
if(p in element.style) {
element.style[p] = (toggle == null || toggle) && value || '';
break;
}
}
},
/**
* toggle browser default behavior by setting css properties.
* `userSelect='none'` also sets `element.onselectstart` to false
* `userDrag='none'` also sets `element.ondragstart` to false
*
* @method toggleBehavior
* @param {HtmlElement} element
* @param {Object} props
* @param {Boolean} [toggle=true]
*/
toggleBehavior: function toggleBehavior(element, props, toggle) {
if(!props || !element || !element.style) {
return;
}
// set the css properties
Utils.each(props, function(value, prop) {
Utils.setPrefixedCss(element, prop, value, toggle);
});
var falseFn = toggle && function() {
return false;
};
// also the disable onselectstart
if(props.userSelect == 'none') {
element.onselectstart = falseFn;
}
// and disable ondragstart
if(props.userDrag == 'none') {
element.ondragstart = falseFn;
}
},
/**
* convert a string with underscores to camelCase
* so prevent_default becomes preventDefault
* @param {String} str
* @return {String} camelCaseStr
*/
toCamelCase: function toCamelCase(str) {
return str.replace(/[_-]([a-z])/g, function(s) {
return s[1].toUpperCase();
});
}
};
/**
* @module hammer
*/
/**
* @class Event
* @static
*/
var Event = Hammer.event = {
/**
* when touch events have been fired, this is true
* this is used to stop mouse events
* @property prevent_mouseevents
* @private
* @type {Boolean}
*/
preventMouseEvents: false,
/**
* if EVENT_START has been fired
* @property started
* @private
* @type {Boolean}
*/
started: false,
/**
* when the mouse is hold down, this is true
* @property should_detect
* @private
* @type {Boolean}
*/
shouldDetect: false,
/**
* simple event binder with a hook and support for multiple types
* @method on
* @param {HTMLElement} element
* @param {String} type
* @param {Function} handler
* @param {Function} [hook]
* @param {Object} hook.type
*/
on: function on(element, type, handler, hook) {
var types = type.split(' ');
Utils.each(types, function(type) {
Utils.on(element, type, handler);
hook && hook(type);
});
},
/**
* simple event unbinder with a hook and support for multiple types
* @method off
* @param {HTMLElement} element
* @param {String} type
* @param {Function} handler
* @param {Function} [hook]
* @param {Object} hook.type
*/
off: function off(element, type, handler, hook) {
var types = type.split(' ');
Utils.each(types, function(type) {
Utils.off(element, type, handler);
hook && hook(type);
});
},
/**
* the core touch event handler.
* this finds out if we should to detect gestures
* @method onTouch
* @param {HTMLElement} element
* @param {String} eventType matches `EVENT_START|MOVE|END`
* @param {Function} handler
* @return onTouchHandler {Function} the core event handler
*/
onTouch: function onTouch(element, eventType, handler) {
var self = this;
var onTouchHandler = function onTouchHandler(ev) {
var srcType = ev.type.toLowerCase(),
isPointer = Hammer.HAS_POINTEREVENTS,
isMouse = Utils.inStr(srcType, 'mouse'),
triggerType;
// if we are in a mouseevent, but there has been a touchevent triggered in this session
// we want to do nothing. simply break out of the event.
if(isMouse && self.preventMouseEvents) {
return;
// mousebutton must be down
} else if(isMouse && eventType == EVENT_START && ev.button === 0) {
self.preventMouseEvents = false;
self.shouldDetect = true;
} else if(isPointer && eventType == EVENT_START) {
self.shouldDetect = (ev.buttons === 1 || PointerEvent.matchType(POINTER_TOUCH, ev));
// just a valid start event, but no mouse
} else if(!isMouse && eventType == EVENT_START) {
self.preventMouseEvents = true;
self.shouldDetect = true;
}
// update the pointer event before entering the detection
if(isPointer && eventType != EVENT_END) {
PointerEvent.updatePointer(eventType, ev);
}
// we are in a touch/down state, so allowed detection of gestures
if(self.shouldDetect) {
triggerType = self.doDetect.call(self, ev, eventType, element, handler);
}
// ...and we are done with the detection
// so reset everything to start each detection totally fresh
if(triggerType == EVENT_END) {
self.preventMouseEvents = false;
self.shouldDetect = false;
PointerEvent.reset();
// update the pointerevent object after the detection
}
if(isPointer && eventType == EVENT_END) {
PointerEvent.updatePointer(eventType, ev);
}
};
this.on(element, EVENT_TYPES[eventType], onTouchHandler);
return onTouchHandler;
},
/**
* the core detection method
* this finds out what hammer-touch-events to trigger
* @method doDetect
* @param {Object} ev
* @param {String} eventType matches `EVENT_START|MOVE|END`
* @param {HTMLElement} element
* @param {Function} handler
* @return {String} triggerType matches `EVENT_START|MOVE|END`
*/
doDetect: function doDetect(ev, eventType, element, handler) {
var touchList = this.getTouchList(ev, eventType);
var touchListLength = touchList.length;
var triggerType = eventType;
var triggerChange = touchList.trigger; // used by fakeMultitouch plugin
var changedLength = touchListLength;
// at each touchstart-like event we want also want to trigger a TOUCH event...
if(eventType == EVENT_START) {
triggerChange = EVENT_TOUCH;
// ...the same for a touchend-like event
} else if(eventType == EVENT_END) {
triggerChange = EVENT_RELEASE;
// keep track of how many touches have been removed
changedLength = touchList.length - ((ev.changedTouches) ? ev.changedTouches.length : 1);
}
// after there are still touches on the screen,
// we just want to trigger a MOVE event. so change the START or END to a MOVE
// but only after detection has been started, the first time we actualy want a START
if(changedLength > 0 && this.started) {
triggerType = EVENT_MOVE;
}
// detection has been started, we keep track of this, see above
this.started = true;
// generate some event data, some basic information
var evData = this.collectEventData(element, triggerType, touchList, ev);
// trigger the triggerType event before the change (TOUCH, RELEASE) events
// but the END event should be at last
if(eventType != EVENT_END) {
handler.call(Detection, evData);
}
// trigger a change (TOUCH, RELEASE) event, this means the length of the touches changed
if(triggerChange) {
evData.changedLength = changedLength;
evData.eventType = triggerChange;
handler.call(Detection, evData);
evData.eventType = triggerType;
delete evData.changedLength;
}
// trigger the END event
if(triggerType == EVENT_END) {
handler.call(Detection, evData);
// ...and we are done with the detection
// so reset everything to start each detection totally fresh
this.started = false;
}
return triggerType;
},
/**
* we have different events for each device/browser
* determine what we need and set them in the EVENT_TYPES constant
* the `onTouch` method is bind to these properties.
* @method determineEventTypes
* @return {Object} events
*/
determineEventTypes: function determineEventTypes() {
var types;
if(Hammer.HAS_POINTEREVENTS) {
if(window.PointerEvent) {
types = [
'pointerdown',
'pointermove',
'pointerup pointercancel lostpointercapture'
];
} else {
types = [
'MSPointerDown',
'MSPointerMove',
'MSPointerUp MSPointerCancel MSLostPointerCapture'
];
}
} else if(Hammer.NO_MOUSEEVENTS) {
types = [
'touchstart',
'touchmove',
'touchend touchcancel'
];
} else {
types = [
'touchstart mousedown',
'touchmove mousemove',
'touchend touchcancel mouseup'
];
}
EVENT_TYPES[EVENT_START] = types[0];
EVENT_TYPES[EVENT_MOVE] = types[1];
EVENT_TYPES[EVENT_END] = types[2];
return EVENT_TYPES;
},
/**
* create touchList depending on the event
* @method getTouchList
* @param {Object} ev
* @param {String} eventType
* @return {Array} touches
*/
getTouchList: function getTouchList(ev, eventType) {
// get the fake pointerEvent touchlist
if(Hammer.HAS_POINTEREVENTS) {
return PointerEvent.getTouchList();
}
// get the touchlist
if(ev.touches) {
if(eventType == EVENT_MOVE) {
return ev.touches;
}
var identifiers = [];
var concat = [].concat(Utils.toArray(ev.touches), Utils.toArray(ev.changedTouches));
var touchList = [];
Utils.each(concat, function(touch) {
if(Utils.inArray(identifiers, touch.identifier) === false) {
touchList.push(touch);
}
identifiers.push(touch.identifier);
});
return touchList;
}
// make fake touchList from mouse position
ev.identifier = 1;
return [ev];
},
/**
* collect basic event data
* @method collectEventData
* @param {HTMLElement} element
* @param {String} eventType matches `EVENT_START|MOVE|END`
* @param {Array} touches
* @param {Object} ev
* @return {Object} ev
*/
collectEventData: function collectEventData(element, eventType, touches, ev) {
// find out pointerType
var pointerType = POINTER_TOUCH;
if(Utils.inStr(ev.type, 'mouse') || PointerEvent.matchType(POINTER_MOUSE, ev)) {
pointerType = POINTER_MOUSE;
} else if(PointerEvent.matchType(POINTER_PEN, ev)) {
pointerType = POINTER_PEN;
}
return {
center: Utils.getCenter(touches),
timeStamp: Date.now(),
target: ev.target,
touches: touches,
eventType: eventType,
pointerType: pointerType,
srcEvent: ev,
/**
* prevent the browser default actions
* mostly used to disable scrolling of the browser
*/
preventDefault: function() {
var srcEvent = this.srcEvent;
srcEvent.preventManipulation && srcEvent.preventManipulation();
srcEvent.preventDefault && srcEvent.preventDefault();
},
/**
* stop bubbling the event up to its parents
*/
stopPropagation: function() {
this.srcEvent.stopPropagation();
},
/**
* immediately stop gesture detection
* might be useful after a swipe was detected
* @return {*}
*/
stopDetect: function() {
return Detection.stopDetect();
}
};
}
};
/**
* @module hammer
*
* @class PointerEvent
* @static
*/
var PointerEvent = Hammer.PointerEvent = {
/**
* holds all pointers, by `identifier`
* @property pointers
* @type {Object}
*/
pointers: {},
/**
* get the pointers as an array
* @method getTouchList
* @return {Array} touchlist
*/
getTouchList: function getTouchList() {
var touchlist = [];
// we can use forEach since pointerEvents only is in IE10
Utils.each(this.pointers, function(pointer) {
touchlist.push(pointer);
});
return touchlist;
},
/**
* update the position of a pointer
* @method updatePointer
* @param {String} eventType matches `EVENT_START|MOVE|END`
* @param {Object} pointerEvent
*/
updatePointer: function updatePointer(eventType, pointerEvent) {
if(eventType == EVENT_END || (eventType != EVENT_END && pointerEvent.buttons !== 1)) {
delete this.pointers[pointerEvent.pointerId];
} else {
pointerEvent.identifier = pointerEvent.pointerId;
this.pointers[pointerEvent.pointerId] = pointerEvent;
}
},
/**
* check if ev matches pointertype
* @method matchType
* @param {String} pointerType matches `POINTER_MOUSE|TOUCH|PEN`
* @param {PointerEvent} ev
*/
matchType: function matchType(pointerType, ev) {
if(!ev.pointerType) {
return false;
}
var pt = ev.pointerType,
types = {};
types[POINTER_MOUSE] = (pt === (ev.MSPOINTER_TYPE_MOUSE || POINTER_MOUSE));
types[POINTER_TOUCH] = (pt === (ev.MSPOINTER_TYPE_TOUCH || POINTER_TOUCH));
types[POINTER_PEN] = (pt === (ev.MSPOINTER_TYPE_PEN || POINTER_PEN));
return types[pointerType];
},
/**
* reset the stored pointers
* @method reset
*/
reset: function resetList() {
this.pointers = {};
}
};
/**
* @module hammer
*
* @class Detection
* @static
*/
var Detection = Hammer.detection = {
// contains all registred Hammer.gestures in the correct order
gestures: [],
// data of the current Hammer.gesture detection session
current: null,
// the previous Hammer.gesture session data
// is a full clone of the previous gesture.current object
previous: null,
// when this becomes true, no gestures are fired
stopped: false,
/**
* start Hammer.gesture detection
* @method startDetect
* @param {Hammer.Instance} inst
* @param {Object} eventData
*/
startDetect: function startDetect(inst, eventData) {
// already busy with a Hammer.gesture detection on an element
if(this.current) {
return;
}
this.stopped = false;
// holds current session
this.current = {
inst: inst, // reference to HammerInstance we're working for
startEvent: Utils.extend({}, eventData), // start eventData for distances, timing etc
lastEvent: false, // last eventData
lastCalcEvent: false, // last eventData for calculations.
futureCalcEvent: false, // last eventData for calculations.
lastCalcData: {}, // last lastCalcData
name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
};
this.detect(eventData);
},
/**
* Hammer.gesture detection
* @method detect
* @param {Object} eventData
* @return {any}
*/
detect: function detect(eventData) {
if(!this.current || this.stopped) {
return;
}
// extend event data with calculations about scale, distance etc
eventData = this.extendEventData(eventData);
// hammer instance and instance options
var inst = this.current.inst,
instOptions = inst.options;
// call Hammer.gesture handlers
Utils.each(this.gestures, function triggerGesture(gesture) {
// only when the instance options have enabled this gesture
if(!this.stopped && inst.enabled && instOptions[gesture.name]) {
gesture.handler.call(gesture, eventData, inst);
}
}, this);
// store as previous event event
if(this.current) {
this.current.lastEvent = eventData;
}
if(eventData.eventType == EVENT_END) {
this.stopDetect();
}
return eventData;
},
/**
* clear the Hammer.gesture vars
* this is called on endDetect, but can also be used when a final Hammer.gesture has been detected
* to stop other Hammer.gestures from being fired
* @method stopDetect
*/
stopDetect: function stopDetect() {
// clone current data to the store as the previous gesture
// used for the double tap gesture, since this is an other gesture detect session
this.previous = Utils.extend({}, this.current);
// reset the current
this.current = null;
this.stopped = true;
},
/**
* calculate velocity, angle and direction
* @method getVelocityData
* @param {Object} ev
* @param {Object} center
* @param {Number} deltaTime
* @param {Number} deltaX
* @param {Number} deltaY
*/
getCalculatedData: function getCalculatedData(ev, center, deltaTime, deltaX, deltaY) {
var cur = this.current,
recalc = false,
calcEv = cur.lastCalcEvent,
calcData = cur.lastCalcData;
if(calcEv && ev.timeStamp - calcEv.timeStamp > Hammer.CALCULATE_INTERVAL) {
center = calcEv.center;
deltaTime = ev.timeStamp - calcEv.timeStamp;
deltaX = ev.center.clientX - calcEv.center.clientX;
deltaY = ev.center.clientY - calcEv.center.clientY;
recalc = true;
}
if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
cur.futureCalcEvent = ev;
}
if(!cur.lastCalcEvent || recalc) {
calcData.velocity = Utils.getVelocity(deltaTime, deltaX, deltaY);
calcData.angle = Utils.getAngle(center, ev.center);
calcData.direction = Utils.getDirection(center, ev.center);
cur.lastCalcEvent = cur.futureCalcEvent || ev;
cur.futureCalcEvent = ev;
}
ev.velocityX = calcData.velocity.x;
ev.velocityY = calcData.velocity.y;
ev.interimAngle = calcData.angle;
ev.interimDirection = calcData.direction;
},
/**
* extend eventData for Hammer.gestures
* @method extendEventData
* @param {Object} ev
* @return {Object} ev
*/
extendEventData: function extendEventData(ev) {
var cur = this.current,
startEv = cur.startEvent,
lastEv = cur.lastEvent || startEv;
// update the start touchlist to calculate the scale/rotation
if(ev.eventType == EVENT_TOUCH || ev.eventType == EVENT_RELEASE) {
startEv.touches = [];
Utils.each(ev.touches, function(touch) {
startEv.touches.push({
clientX: touch.clientX,
clientY: touch.clientY
});
});
}
var deltaTime = ev.timeStamp - startEv.timeStamp,
deltaX = ev.center.clientX - startEv.center.clientX,
deltaY = ev.center.clientY - startEv.center.clientY;
this.getCalculatedData(ev, lastEv.center, deltaTime, deltaX, deltaY);
Utils.extend(ev, {
startEvent: startEv,
deltaTime: deltaTime,
deltaX: deltaX,
deltaY: deltaY,
distance: Utils.getDistance(startEv.center, ev.center),
angle: Utils.getAngle(startEv.center, ev.center),
direction: Utils.getDirection(startEv.center, ev.center),
scale: Utils.getScale(startEv.touches, ev.touches),
rotation: Utils.getRotation(startEv.touches, ev.touches)
});
return ev;
},
/**
* register new gesture
* @method register
* @param {Object} gesture object, see `gestures/` for documentation
* @return {Array} gestures
*/
register: function register(gesture) {
// add an enable gesture options if there is no given
var options = gesture.defaults || {};
if(options[gesture.name] === undefined) {
options[gesture.name] = true;
}
// extend Hammer default options with the Hammer.gesture options
Utils.extend(Hammer.defaults, options, true);
// set its index
gesture.index = gesture.index || 1000;
// add Hammer.gesture to the list
this.gestures.push(gesture);
// sort the list by index
this.gestures.sort(function(a, b) {
if(a.index < b.index) {
return -1;
}
if(a.index > b.index) {
return 1;
}
return 0;
});
return this.gestures;
}
};
/**
* @module hammer
*/
/**
* create new hammer instance
* all methods should return the instance itself, so it is chainable.
*
* @class Instance
* @constructor
* @param {HTMLElement} element
* @param {Object} [options={}] options are merged with `Hammer.defaults`
* @return {Hammer.Instance}
*/
Hammer.Instance = function(element, options) {
var self = this;
// setup HammerJS window events and register all gestures
// this also sets up the default options
setup();
/**
* @property element
* @type {HTMLElement}
*/
this.element = element;
/**
* @property enabled
* @type {Boolean}
* @protected
*/
this.enabled = true;
/**
* options, merged with the defaults
* options with an _ are converted to camelCase
* @property options
* @type {Object}
*/
Utils.each(options, function(value, name) {
delete options[name];
options[Utils.toCamelCase(name)] = value;
});
this.options = Utils.extend(Utils.extend({}, Hammer.defaults), options || {});
// add some css to the element to prevent the browser from doing its native behavoir
if(this.options.behavior) {
Utils.toggleBehavior(this.element, this.options.behavior, true);
}
/**
* event start handler on the element to start the detection
* @property eventStartHandler
* @type {Object}
*/
this.eventStartHandler = Event.onTouch(element, EVENT_START, function(ev) {
if(self.enabled && ev.eventType == EVENT_START) {
Detection.startDetect(self, ev);
} else if(ev.eventType == EVENT_TOUCH) {
Detection.detect(ev);
}
});
/**
* keep a list of user event handlers which needs to be removed when calling 'dispose'
* @property eventHandlers
* @type {Array}
*/
this.eventHandlers = [];
};
Hammer.Instance.prototype = {
/**
* bind events to the instance
* @method on
* @chainable
* @param {String} gestures multiple gestures by splitting with a space
* @param {Function} handler
* @param {Object} handler.ev event object
*/
on: function onEvent(gestures, handler) {
var self = this;
Event.on(self.element, gestures, handler, function(type) {
self.eventHandlers.push({ gesture: type, handler: handler });
});
return self;
},
/**
* unbind events to the instance
* @method off
* @chainable
* @param {String} gestures
* @param {Function} handler
*/
off: function offEvent(gestures, handler) {
var self = this;
Event.off(self.element, gestures, handler, function(type) {
var index = Utils.inArray({ gesture: type, handler: handler });
if(index !== false) {
self.eventHandlers.splice(index, 1);
}
});
return self;
},
/**
* trigger gesture event
* @method trigger
* @chainable
* @param {String} gesture
* @param {Object} [eventData]
*/
trigger: function triggerEvent(gesture, eventData) {
// optional
if(!eventData) {
eventData = {};
}
// create DOM event
var event = Hammer.DOCUMENT.createEvent('Event');
event.initEvent(gesture, true, true);
event.gesture = eventData;
// trigger on the target if it is in the instance element,
// this is for event delegation tricks
var element = this.element;
if(Utils.hasParent(eventData.target, element)) {
element = eventData.target;
}
element.dispatchEvent(event);
return this;
},
/**
* enable of disable hammer.js detection
* @method enable
* @chainable
* @param {Boolean} state
*/
enable: function enable(state) {
this.enabled = state;
return this;
},
/**
* dispose this hammer instance
* @method dispose
* @return {Null}
*/
dispose: function dispose() {
var i, eh;
// undo all changes made by stop_browser_behavior
Utils.toggleBehavior(this.element, this.options.behavior, false);
// unbind all custom event handlers
for(i = -1; (eh = this.eventHandlers[++i]);) {
Utils.off(this.element, eh.gesture, eh.handler);
}
this.eventHandlers = [];
// unbind the start event listener
Event.off(this.element, EVENT_TYPES[EVENT_START], this.eventStartHandler);
return null;
}
};
/**
* @module gestures
*/
/**
* Move with x fingers (default 1) around on the page.
* Preventing the default browser behavior is a good way to improve feel and working.
* ````
* hammertime.on("drag", function(ev) {
* console.log(ev);
* ev.gesture.preventDefault();
* });
* ````
*
* @class Drag
* @static
*/
/**
* @event drag
* @param {Object} ev
*/
/**
* @event dragstart
* @param {Object} ev
*/
/**
* @event dragend
* @param {Object} ev
*/
/**
* @event drapleft
* @param {Object} ev
*/
/**
* @event dragright
* @param {Object} ev
*/
/**
* @event dragup
* @param {Object} ev
*/
/**
* @event dragdown
* @param {Object} ev
*/
/**
* @param {String} name
*/
(function(name) {
var triggered = false;
function dragGesture(ev, inst) {
var cur = Detection.current;
// max touches
if(inst.options.dragMaxTouches > 0 &&
ev.touches.length > inst.options.dragMaxTouches) {
return;
}
switch(ev.eventType) {
case EVENT_START:
triggered = false;
break;
case EVENT_MOVE:
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(ev.distance < inst.options.dragMinDistance &&
cur.name != name) {
return;
}
var startCenter = cur.startEvent.center;
// we are dragging!
if(cur.name != name) {
cur.name = name;
if(inst.options.dragDistanceCorrection && ev.distance > 0) {
// When a drag is triggered, set the event center to dragMinDistance pixels from the original event center.
// Without this correction, the dragged distance would jumpstart at dragMinDistance pixels instead of at 0.
// It might be useful to save the original start point somewhere
var factor = Math.abs(inst.options.dragMinDistance / ev.distance);
startCenter.pageX += ev.deltaX * factor;
startCenter.pageY += ev.deltaY * factor;
startCenter.clientX += ev.deltaX * factor;
startCenter.clientY += ev.deltaY * factor;
// recalculate event data using new start point
ev = Detection.extendEventData(ev);
}
}
// lock drag to axis?
if(cur.lastEvent.dragLockToAxis ||
( inst.options.dragLockToAxis &&
inst.options.dragLockMinDistance <= ev.distance
)) {
ev.dragLockToAxis = true;
}
// keep direction on the axis that the drag gesture started on
var lastDirection = cur.lastEvent.direction;
if(ev.dragLockToAxis && lastDirection !== ev.direction) {
if(Utils.isVertical(lastDirection)) {
ev.direction = (ev.deltaY < 0) ? DIRECTION_UP : DIRECTION_DOWN;
} else {
ev.direction = (ev.deltaX < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
}
// first time, trigger dragstart event
if(!triggered) {
inst.trigger(name + 'start', ev);
triggered = true;
}
// trigger events
inst.trigger(name, ev);
inst.trigger(name + ev.direction, ev);
var isVertical = Utils.isVertical(ev.direction);
// block the browser events
if((inst.options.dragBlockVertical && isVertical) ||
(inst.options.dragBlockHorizontal && !isVertical)) {
ev.preventDefault();
}
break;
case EVENT_RELEASE:
if(triggered && ev.changedLength <= inst.options.dragMaxTouches) {
inst.trigger(name + 'end', ev);
triggered = false;
}
break;
case EVENT_END:
triggered = false;
break;
}
}
Hammer.gestures.Drag = {
name: name,
index: 50,
handler: dragGesture,
defaults: {
/**
* minimal movement that have to be made before the drag event gets triggered
* @property dragMinDistance
* @type {Number}
* @default 10
*/
dragMinDistance: 10,
/**
* Set dragDistanceCorrection to true to make the starting point of the drag
* be calculated from where the drag was triggered, not from where the touch started.
* Useful to avoid a jerk-starting drag, which can make fine-adjustments
* through dragging difficult, and be visually unappealing.
* @property dragDistanceCorrection
* @type {Boolean}
* @default true
*/
dragDistanceCorrection: true,
/**
* set 0 for unlimited, but this can conflict with transform
* @property dragMaxTouches
* @type {Number}
* @default 1
*/
dragMaxTouches: 1,
/**
* prevent default browser behavior when dragging occurs
* be careful with it, it makes the element a blocking element
* when you are using the drag gesture, it is a good practice to set this true
* @property dragBlockHorizontal
* @type {Boolean}
* @default false
*/
dragBlockHorizontal: false,
/**
* same as `dragBlockHorizontal`, but for vertical movement
* @property dragBlockVertical
* @type {Boolean}
* @default false
*/
dragBlockVertical: false,
/**
* dragLockToAxis keeps the drag gesture on the axis that it started on,
* It disallows vertical directions if the initial direction was horizontal, and vice versa.
* @property dragLockToAxis
* @type {Boolean}
* @default false
*/
dragLockToAxis: false,
/**
* drag lock only kicks in when distance > dragLockMinDistance
* This way, locking occurs only when the distance has become large enough to reliably determine the direction
* @property dragLockMinDistance
* @type {Number}
* @default 25
*/
dragLockMinDistance: 25
}
};
})('drag');
/**
* @module gestures
*/
/**
* trigger a simple gesture event, so you can do anything in your handler.
* only usable if you know what your doing...
*
* @class Gesture
* @static
*/
/**
* @event gesture
* @param {Object} ev
*/
Hammer.gestures.Gesture = {
name: 'gesture',
index: 1337,
handler: function releaseGesture(ev, inst) {
inst.trigger(this.name, ev);
}
};
/**
* @module gestures
*/
/**
* Touch stays at the same place for x time
*
* @class Hold
* @static
*/
/**
* @event hold
* @param {Object} ev
*/
/**
* @param {String} name
*/
(function(name) {
var timer;
function holdGesture(ev, inst) {
var options = inst.options,
current = Detection.current;
switch(ev.eventType) {
case EVENT_START:
clearTimeout(timer);
// set the gesture so we can check in the timeout if it still is
current.name = name;
// set timer and if after the timeout it still is hold,
// we trigger the hold event
timer = setTimeout(function() {
if(current && current.name == name) {
inst.trigger(name, ev);
}
}, options.holdTimeout);
break;
case EVENT_MOVE:
if(ev.distance > options.holdThreshold) {
clearTimeout(timer);
}
break;
case EVENT_RELEASE:
clearTimeout(timer);
break;
}
}
Hammer.gestures.Hold = {
name: name,
index: 10,
defaults: {
/**
* @property holdTimeout
* @type {Number}
* @default 500
*/
holdTimeout: 500,
/**
* movement allowed while holding
* @property holdThreshold
* @type {Number}
* @default 2
*/
holdThreshold: 2
},
handler: holdGesture
};
})('hold');
/**
* @module gestures
*/
/**
* when a touch is being released from the page
*
* @class Release
* @static
*/
/**
* @event release
* @param {Object} ev
*/
Hammer.gestures.Release = {
name: 'release',
index: Infinity,
handler: function releaseGesture(ev, inst) {
if(ev.eventType == EVENT_RELEASE) {
inst.trigger(this.name, ev);
}
}
};
/**
* @module gestures
*/
/**
* triggers swipe events when the end velocity is above the threshold
* for best usage, set `preventDefault` (on the drag gesture) to `true`
* ````
* hammertime.on("dragleft swipeleft", function(ev) {
* console.log(ev);
* ev.gesture.preventDefault();
* });
* ````
*
* @class Swipe
* @static
*/
/**
* @event swipe
* @param {Object} ev
*/
/**
* @event swipeleft
* @param {Object} ev
*/
/**
* @event swiperight
* @param {Object} ev
*/
/**
* @event swipeup
* @param {Object} ev
*/
/**
* @event swipedown
* @param {Object} ev
*/
Hammer.gestures.Swipe = {
name: 'swipe',
index: 40,
defaults: {
/**
* @property swipeMinTouches
* @type {Number}
* @default 1
*/
swipeMinTouches: 1,
/**
* @property swipeMaxTouches
* @type {Number}
* @default 1
*/
swipeMaxTouches: 1,
/**
* horizontal swipe velocity
* @property swipeVelocityX
* @type {Number}
* @default 0.6
*/
swipeVelocityX: 0.6,
/**
* vertical swipe velocity
* @property swipeVelocityY
* @type {Number}
* @default 0.6
*/
swipeVelocityY: 0.6
},
handler: function swipeGesture(ev, inst) {
if(ev.eventType == EVENT_RELEASE) {
var touches = ev.touches.length,
options = inst.options;
// max touches
if(touches < options.swipeMinTouches ||
touches > options.swipeMaxTouches) {
return;
}
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(ev.velocityX > options.swipeVelocityX ||
ev.velocityY > options.swipeVelocityY) {
// trigger swipe events
inst.trigger(this.name, ev);
inst.trigger(this.name + ev.direction, ev);
}
}
}
};
/**
* @module gestures
*/
/**
* Single tap and a double tap on a place
*
* @class Tap
* @static
*/
/**
* @event tap
* @param {Object} ev
*/
/**
* @event doubletap
* @param {Object} ev
*/
/**
* @param {String} name
*/
(function(name) {
var hasMoved = false;
function tapGesture(ev, inst) {
var options = inst.options,
current = Detection.current,
prev = Detection.previous,
sincePrev,
didDoubleTap;
switch(ev.eventType) {
case EVENT_START:
hasMoved = false;
break;
case EVENT_MOVE:
hasMoved = hasMoved || (ev.distance > options.tapMaxDistance);
break;
case EVENT_END:
if(!Utils.inStr(ev.srcEvent.type, 'cancel') && ev.deltaTime < options.tapMaxTime && !hasMoved) {
// previous gesture, for the double tap since these are two different gesture detections
sincePrev = prev && prev.lastEvent && ev.timeStamp - prev.lastEvent.timeStamp;
didDoubleTap = false;
// check if double tap
if(prev && prev.name == name &&
(sincePrev && sincePrev < options.doubleTapInterval) &&
ev.distance < options.doubleTapDistance) {
inst.trigger('doubletap', ev);
didDoubleTap = true;
}
// do a single tap
if(!didDoubleTap || options.tapAlways) {
current.name = name;
inst.trigger(current.name, ev);
}
}
break;
}
}
Hammer.gestures.Tap = {
name: name,
index: 100,
handler: tapGesture,
defaults: {
/**
* max time of a tap, this is for the slow tappers
* @property tapMaxTime
* @type {Number}
* @default 250
*/
tapMaxTime: 250,
/**
* max distance of movement of a tap, this is for the slow tappers
* @property tapMaxDistance
* @type {Number}
* @default 10
*/
tapMaxDistance: 10,
/**
* always trigger the `tap` event, even while double-tapping
* @property tapAlways
* @type {Boolean}
* @default true
*/
tapAlways: true,
/**
* max distance between two taps
* @property doubleTapDistance
* @type {Number}
* @default 20
*/
doubleTapDistance: 20,
/**
* max time between two taps
* @property doubleTapInterval
* @type {Number}
* @default 300
*/
doubleTapInterval: 300
}
};
})('tap');
/**
* @module gestures
*/
/**
* when a touch is being touched at the page
*
* @class Touch
* @static
*/
/**
* @event touch
* @param {Object} ev
*/
Hammer.gestures.Touch = {
name: 'touch',
index: -Infinity,
defaults: {
/**
* call preventDefault at touchstart, and makes the element blocking by disabling the scrolling of the page,
* but it improves gestures like transforming and dragging.
* be careful with using this, it can be very annoying for users to be stuck on the page
* @property preventDefault
* @type {Boolean}
* @default false
*/
preventDefault: false,
/**
* disable mouse events, so only touch (or pen!) input triggers events
* @property preventMouse
* @type {Boolean}
* @default false
*/
preventMouse: false
},
handler: function touchGesture(ev, inst) {
if(inst.options.preventMouse && ev.pointerType == POINTER_MOUSE) {
ev.stopDetect();
return;
}
if(inst.options.preventDefault) {
ev.preventDefault();
}
if(ev.eventType == EVENT_TOUCH) {
inst.trigger('touch', ev);
}
}
};
/**
* @module gestures
*/
/**
* User want to scale or rotate with 2 fingers
* Preventing the default browser behavior is a good way to improve feel and working. This can be done with the
* `preventDefault` option.
*
* @class Transform
* @static
*/
/**
* @event transform
* @param {Object} ev
*/
/**
* @event transformstart
* @param {Object} ev
*/
/**
* @event transformend
* @param {Object} ev
*/
/**
* @event pinchin
* @param {Object} ev
*/
/**
* @event pinchout
* @param {Object} ev
*/
/**
* @event rotate
* @param {Object} ev
*/
/**
* @param {String} name
*/
(function(name) {
var triggered = false;
function transformGesture(ev, inst) {
switch(ev.eventType) {
case EVENT_START:
triggered = false;
break;
case EVENT_MOVE:
// at least multitouch
if(ev.touches.length < 2) {
return;
}
var scaleThreshold = Math.abs(1 - ev.scale);
var rotationThreshold = Math.abs(ev.rotation);
// when the distance we moved is too small we skip this gesture
// or we can be already in dragging
if(scaleThreshold < inst.options.transformMinScale &&
rotationThreshold < inst.options.transformMinRotation) {
return;
}
// we are transforming!
Detection.current.name = name;
// first time, trigger dragstart event
if(!triggered) {
inst.trigger(name + 'start', ev);
triggered = true;
}
inst.trigger(name, ev); // basic transform event
// trigger rotate event
if(rotationThreshold > inst.options.transformMinRotation) {
inst.trigger('rotate', ev);
}
// trigger pinch event
if(scaleThreshold > inst.options.transformMinScale) {
inst.trigger('pinch', ev);
inst.trigger('pinch' + (ev.scale < 1 ? 'in' : 'out'), ev);
}
break;
case EVENT_RELEASE:
if(triggered && ev.changedLength < 2) {
inst.trigger(name + 'end', ev);
triggered = false;
}
break;
}
}
Hammer.gestures.Transform = {
name: name,
index: 45,
defaults: {
/**
* minimal scale factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
* @property transformMinScale
* @type {Number}
* @default 0.01
*/
transformMinScale: 0.01,
/**
* rotation in degrees
* @property transformMinRotation
* @type {Number}
* @default 1
*/
transformMinRotation: 1
},
handler: transformGesture
};
})('transform');
/**
* @module hammer
*/
// AMD export
if(typeof define == 'function' && define.amd) {
define(function() {
return Hammer;
});
// commonjs export
} else if(typeof module !== 'undefined' && module.exports) {
module.exports = Hammer;
// browser export
} else {
window.Hammer = Hammer;
}
})(window);
/*! iScroll v5.0.6 ~ (c) 2008-2013 Matteo Spinelli ~ http://cubiq.org/license */
var IScroll = (function (window, document, Math) {
var rAF = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) { window.setTimeout(callback, 1000 / 60); };
var utils = (function () {
var me = {};
var _elementStyle = document.createElement('div').style;
var _vendor = (function () {
var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
transform,
i = 0,
l = vendors.length;
for ( ; i < l; i++ ) {
transform = vendors[i] + 'ransform';
if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1);
}
return false;
})();
function _prefixStyle (style) {
if ( _vendor === false ) return false;
if ( _vendor === '' ) return style;
return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
}
me.getTime = Date.now || function getTime () { return new Date().getTime(); };
me.extend = function (target, obj) {
for ( var i in obj ) {
target[i] = obj[i];
}
};
me.addEvent = function (el, type, fn, capture) {
el.addEventListener(type, fn, !!capture);
};
me.removeEvent = function (el, type, fn, capture) {
el.removeEventListener(type, fn, !!capture);
};
me.momentum = function (current, start, time, lowerMargin, wrapperSize) {
var distance = current - start,
speed = Math.abs(distance) / time,
destination,
duration,
deceleration = 0.0006;
destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 );
duration = speed / deceleration;
if ( destination < lowerMargin ) {
destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
distance = Math.abs(destination - current);
duration = distance / speed;
} else if ( destination > 0 ) {
destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
distance = Math.abs(current) + destination;
duration = distance / speed;
}
return {
destination: Math.round(destination),
duration: duration
};
};
var _transform = _prefixStyle('transform');
me.extend(me, {
hasTransform: _transform !== false,
hasPerspective: _prefixStyle('perspective') in _elementStyle,
hasTouch: 'ontouchstart' in window,
hasPointer: navigator.msPointerEnabled,
hasTransition: _prefixStyle('transition') in _elementStyle
});
me.isAndroidBrowser = /Android/.test(window.navigator.appVersion) && /Version\/\d/.test(window.navigator.appVersion);
me.extend(me.style = {}, {
transform: _transform,
transitionTimingFunction: _prefixStyle('transitionTimingFunction'),
transitionDuration: _prefixStyle('transitionDuration'),
transformOrigin: _prefixStyle('transformOrigin')
});
me.hasClass = function (e, c) {
var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
return re.test(e.className);
};
me.addClass = function (e, c) {
if ( me.hasClass(e, c) ) {
return;
}
var newclass = e.className.split(' ');
newclass.push(c);
e.className = newclass.join(' ');
};
me.removeClass = function (e, c) {
if ( !me.hasClass(e, c) ) {
return;
}
var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
e.className = e.className.replace(re, ' ');
};
me.offset = function (el) {
var left = -el.offsetLeft,
top = -el.offsetTop;
// jshint -W084
while (el = el.offsetParent) {
left -= el.offsetLeft;
top -= el.offsetTop;
}
// jshint +W084
return {
left: left,
top: top
};
};
me.preventDefaultException = function (el, exceptions) {
for ( var i in exceptions ) {
if ( exceptions[i].test(el[i]) ) {
return true;
}
}
return false;
};
me.extend(me.eventType = {}, {
touchstart: 1,
touchmove: 1,
touchend: 1,
mousedown: 2,
mousemove: 2,
mouseup: 2,
MSPointerDown: 3,
MSPointerMove: 3,
MSPointerUp: 3
});
me.extend(me.ease = {}, {
quadratic: {
style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
fn: function (k) {
return k * ( 2 - k );
}
},
circular: {
style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
fn: function (k) {
return Math.sqrt( 1 - ( --k * k ) );
}
},
back: {
style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
fn: function (k) {
var b = 4;
return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1;
}
},
bounce: {
style: '',
fn: function (k) {
if ( ( k /= 1 ) < ( 1 / 2.75 ) ) {
return 7.5625 * k * k;
} else if ( k < ( 2 / 2.75 ) ) {
return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
} else if ( k < ( 2.5 / 2.75 ) ) {
return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
} else {
return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
}
}
},
elastic: {
style: '',
fn: function (k) {
var f = 0.22,
e = 0.4;
if ( k === 0 ) { return 0; }
if ( k == 1 ) { return 1; }
return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 );
}
}
});
me.tap = function (e, eventName) {
var ev = document.createEvent('Event');
ev.initEvent(eventName, true, true);
ev.pageX = e.pageX;
ev.pageY = e.pageY;
e.target.dispatchEvent(ev);
};
me.click = function (e) {
var target = e.target,
ev;
if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
ev = document.createEvent('MouseEvents');
ev.initMouseEvent('click', true, true, e.view, 1,
target.screenX, target.screenY, target.clientX, target.clientY,
e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
0, null);
ev._constructed = true;
target.dispatchEvent(ev);
}
};
return me;
})();
function IScroll (el, options) {
this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
this.scroller = this.wrapper.children[0];
this.scrollerStyle = this.scroller.style; // cache style for better performance
this.options = {
// INSERT POINT: OPTIONS
startX: 0,
startY: 0,
scrollY: true,
directionLockThreshold: 5,
momentum: true,
bounce: true,
bounceTime: 600,
bounceEasing: '',
preventDefault: true,
preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ },
HWCompositing: true,
useTransition: true,
useTransform: true
};
for ( var i in options ) {
this.options[i] = options[i];
}
// Normalize options
this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : '';
this.options.useTransition = utils.hasTransition && this.options.useTransition;
this.options.useTransform = utils.hasTransform && this.options.useTransform;
this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough;
this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
// If you want eventPassthrough I have to lock one of the axes
this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY;
this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX;
// With eventPassthrough we also need lockDirection mechanism
this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
if ( this.options.tap === true ) {
this.options.tap = 'tap';
}
// INSERT POINT: NORMALIZATION
// Some defaults
this.x = 0;
this.y = 0;
this.directionX = 0;
this.directionY = 0;
this._events = {};
// INSERT POINT: DEFAULTS
this._init();
this.refresh();
this.scrollTo(this.options.startX, this.options.startY);
this.enable();
}
IScroll.prototype = {
version: '5.0.6',
_init: function () {
this._initEvents();
// INSERT POINT: _init
},
destroy: function () {
this._initEvents(true);
this._execEvent('destroy');
},
_transitionEnd: function (e) {
if ( e.target != this.scroller ) {
return;
}
this._transitionTime(0);
if ( !this.resetPosition(this.options.bounceTime) ) {
this._execEvent('scrollEnd');
}
},
_start: function (e) {
// React to left mouse button only
if ( utils.eventType[e.type] != 1 ) {
if ( e.button !== 0 ) {
return;
}
}
if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) {
return;
}
if ( this.options.preventDefault && !utils.isAndroidBrowser && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
e.preventDefault(); // This seems to break default Android browser
}
var point = e.touches ? e.touches[0] : e,
pos;
this.initiated = utils.eventType[e.type];
this.moved = false;
this.distX = 0;
this.distY = 0;
this.directionX = 0;
this.directionY = 0;
this.directionLocked = 0;
this._transitionTime();
this.isAnimating = false;
this.startTime = utils.getTime();
if ( this.options.useTransition && this.isInTransition ) {
pos = this.getComputedPosition();
this._translate(Math.round(pos.x), Math.round(pos.y));
this._execEvent('scrollEnd');
this.isInTransition = false;
}
this.startX = this.x;
this.startY = this.y;
this.absStartX = this.x;
this.absStartY = this.y;
this.pointX = point.pageX;
this.pointY = point.pageY;
this._execEvent('beforeScrollStart');
},
_move: function (e) {
if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
return;
}
if ( this.options.preventDefault ) { // increases performance on Android? TODO: check!
e.preventDefault();
}
var point = e.touches ? e.touches[0] : e,
deltaX = point.pageX - this.pointX,
deltaY = point.pageY - this.pointY,
timestamp = utils.getTime(),
newX, newY,
absDistX, absDistY;
this.pointX = point.pageX;
this.pointY = point.pageY;
this.distX += deltaX;
this.distY += deltaY;
absDistX = Math.abs(this.distX);
absDistY = Math.abs(this.distY);
// We need to move at least 10 pixels for the scrolling to initiate
if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) {
return;
}
// If you are scrolling in one direction lock the other
if ( !this.directionLocked && !this.options.freeScroll ) {
if ( absDistX > absDistY + this.options.directionLockThreshold ) {
this.directionLocked = 'h'; // lock horizontally
} else if ( absDistY >= absDistX + this.options.directionLockThreshold ) {
this.directionLocked = 'v'; // lock vertically
} else {
this.directionLocked = 'n'; // no lock
}
}
if ( this.directionLocked == 'h' ) {
if ( this.options.eventPassthrough == 'vertical' ) {
e.preventDefault();
} else if ( this.options.eventPassthrough == 'horizontal' ) {
this.initiated = false;
return;
}
deltaY = 0;
} else if ( this.directionLocked == 'v' ) {
if ( this.options.eventPassthrough == 'horizontal' ) {
e.preventDefault();
} else if ( this.options.eventPassthrough == 'vertical' ) {
this.initiated = false;
return;
}
deltaX = 0;
}
deltaX = this.hasHorizontalScroll ? deltaX : 0;
deltaY = this.hasVerticalScroll ? deltaY : 0;
newX = this.x + deltaX;
newY = this.y + deltaY;
// Slow down if outside of the boundaries
if ( newX > 0 || newX < this.maxScrollX ) {
newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
}
if ( newY > 0 || newY < this.maxScrollY ) {
newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
}
this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
if ( !this.moved ) {
this._execEvent('scrollStart');
}
this.moved = true;
this._translate(newX, newY);
/* REPLACE START: _move */
if ( timestamp - this.startTime > 300 ) {
this.startTime = timestamp;
this.startX = this.x;
this.startY = this.y;
}
/* REPLACE END: _move */
},
_end: function (e) {
if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
return;
}
if ( this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
e.preventDefault();
}
var point = e.changedTouches ? e.changedTouches[0] : e,
momentumX,
momentumY,
duration = utils.getTime() - this.startTime,
newX = Math.round(this.x),
newY = Math.round(this.y),
distanceX = Math.abs(newX - this.startX),
distanceY = Math.abs(newY - this.startY),
time = 0,
easing = '';
this.scrollTo(newX, newY); // ensures that the last position is rounded
this.isInTransition = 0;
this.initiated = 0;
this.endTime = utils.getTime();
// reset if we are outside of the boundaries
if ( this.resetPosition(this.options.bounceTime) ) {
return;
}
// we scrolled less than 10 pixels
if ( !this.moved ) {
if ( this.options.tap ) {
utils.tap(e, this.options.tap);
}
if ( this.options.click ) {
utils.click(e);
}
return;
}
if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) {
this._execEvent('flick');
return;
}
// start momentum animation if needed
if ( this.options.momentum && duration < 300 ) {
momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0) : { destination: newX, duration: 0 };
momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0) : { destination: newY, duration: 0 };
newX = momentumX.destination;
newY = momentumY.destination;
time = Math.max(momentumX.duration, momentumY.duration);
this.isInTransition = 1;
}
// INSERT POINT: _end
if ( newX != this.x || newY != this.y ) {
// change easing function when scroller goes out of the boundaries
if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) {
easing = utils.ease.quadratic;
}
this.scrollTo(newX, newY, time, easing);
return;
}
this._execEvent('scrollEnd');
},
_resize: function () {
var that = this;
clearTimeout(this.resizeTimeout);
this.resizeTimeout = setTimeout(function () {
that.refresh();
}, this.options.resizePolling);
},
resetPosition: function (time) {
var x = this.x,
y = this.y;
time = time || 0;
if ( !this.hasHorizontalScroll || this.x > 0 ) {
x = 0;
} else if ( this.x < this.maxScrollX ) {
x = this.maxScrollX;
}
if ( !this.hasVerticalScroll || this.y > 0 ) {
y = 0;
} else if ( this.y < this.maxScrollY ) {
y = this.maxScrollY;
}
if ( x == this.x && y == this.y ) {
return false;
}
this.scrollTo(x, y, time, this.options.bounceEasing);
return true;
},
disable: function () {
this.enabled = false;
},
enable: function () {
this.enabled = true;
},
refresh: function () {
var rf = this.wrapper.offsetHeight; // Force reflow
this.wrapperWidth = this.wrapper.clientWidth;
this.wrapperHeight = this.wrapper.clientHeight;
/* REPLACE START: refresh */
this.scrollerWidth = this.scroller.offsetWidth;
this.scrollerHeight = this.scroller.offsetHeight;
/* REPLACE END: refresh */
this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
if ( !this.hasHorizontalScroll ) {
this.maxScrollX = 0;
this.scrollerWidth = this.wrapperWidth;
}
if ( !this.hasVerticalScroll ) {
this.maxScrollY = 0;
this.scrollerHeight = this.wrapperHeight;
}
this.endTime = 0;
this.directionX = 0;
this.directionY = 0;
this.wrapperOffset = utils.offset(this.wrapper);
this._execEvent('refresh');
this.resetPosition();
// INSERT POINT: _refresh
},
on: function (type, fn) {
if ( !this._events[type] ) {
this._events[type] = [];
}
this._events[type].push(fn);
},
_execEvent: function (type) {
if ( !this._events[type] ) {
return;
}
var i = 0,
l = this._events[type].length;
if ( !l ) {
return;
}
for ( ; i < l; i++ ) {
this._events[type][i].call(this);
}
},
scrollBy: function (x, y, time, easing) {
x = this.x + x;
y = this.y + y;
time = time || 0;
this.scrollTo(x, y, time, easing);
},
scrollTo: function (x, y, time, easing) {
easing = easing || utils.ease.circular;
if ( !time || (this.options.useTransition && easing.style) ) {
this._transitionTimingFunction(easing.style);
this._transitionTime(time);
this._translate(x, y);
} else {
this._animate(x, y, time, easing.fn);
}
},
scrollToElement: function (el, time, offsetX, offsetY, easing) {
el = el.nodeType ? el : this.scroller.querySelector(el);
if ( !el ) {
return;
}
var pos = utils.offset(el);
pos.left -= this.wrapperOffset.left;
pos.top -= this.wrapperOffset.top;
// if offsetX/Y are true we center the element to the screen
if ( offsetX === true ) {
offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
}
if ( offsetY === true ) {
offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
}
pos.left -= offsetX || 0;
pos.top -= offsetY || 0;
pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time;
this.scrollTo(pos.left, pos.top, time, easing);
},
_transitionTime: function (time) {
time = time || 0;
this.scrollerStyle[utils.style.transitionDuration] = time + 'ms';
// INSERT POINT: _transitionTime
},
_transitionTimingFunction: function (easing) {
this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
// INSERT POINT: _transitionTimingFunction
},
_translate: function (x, y) {
if ( this.options.useTransform ) {
/* REPLACE START: _translate */
this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ;
/* REPLACE END: _translate */
} else {
x = Math.round(x);
y = Math.round(y);
this.scrollerStyle.left = x + 'px';
this.scrollerStyle.top = y + 'px';
}
this.x = x;
this.y = y;
// INSERT POINT: _translate
},
_initEvents: function (remove) {
var eventType = remove ? utils.removeEvent : utils.addEvent,
target = this.options.bindToWrapper ? this.wrapper : window;
eventType(window, 'orientationchange', this);
eventType(window, 'resize', this);
if ( this.options.click ) {
eventType(this.wrapper, 'click', this, true);
}
if ( !this.options.disableMouse ) {
eventType(this.wrapper, 'mousedown', this);
eventType(target, 'mousemove', this);
eventType(target, 'mousecancel', this);
eventType(target, 'mouseup', this);
}
if ( utils.hasPointer && !this.options.disablePointer ) {
eventType(this.wrapper, 'MSPointerDown', this);
eventType(target, 'MSPointerMove', this);
eventType(target, 'MSPointerCancel', this);
eventType(target, 'MSPointerUp', this);
}
if ( utils.hasTouch && !this.options.disableTouch ) {
eventType(this.wrapper, 'touchstart', this);
eventType(target, 'touchmove', this);
eventType(target, 'touchcancel', this);
eventType(target, 'touchend', this);
}
eventType(this.scroller, 'transitionend', this);
eventType(this.scroller, 'webkitTransitionEnd', this);
eventType(this.scroller, 'oTransitionEnd', this);
eventType(this.scroller, 'MSTransitionEnd', this);
},
getComputedPosition: function () {
var matrix = window.getComputedStyle(this.scroller, null),
x, y;
if ( this.options.useTransform ) {
matrix = matrix[utils.style.transform].split(')')[0].split(', ');
x = +(matrix[12] || matrix[4]);
y = +(matrix[13] || matrix[5]);
} else {
x = +matrix.left.replace(/[^-\d]/g, '');
y = +matrix.top.replace(/[^-\d]/g, '');
}
return { x: x, y: y };
},
_animate: function (destX, destY, duration, easingFn) {
var that = this,
startX = this.x,
startY = this.y,
startTime = utils.getTime(),
destTime = startTime + duration;
function step () {
var now = utils.getTime(),
newX, newY,
easing;
if ( now >= destTime ) {
that.isAnimating = false;
that._translate(destX, destY);
if ( !that.resetPosition(that.options.bounceTime) ) {
that._execEvent('scrollEnd');
}
return;
}
now = ( now - startTime ) / duration;
easing = easingFn(now);
newX = ( destX - startX ) * easing + startX;
newY = ( destY - startY ) * easing + startY;
that._translate(newX, newY);
if ( that.isAnimating ) {
rAF(step);
}
}
this.isAnimating = true;
step();
},
handleEvent: function (e) {
switch ( e.type ) {
case 'touchstart':
case 'MSPointerDown':
case 'mousedown':
this._start(e);
break;
case 'touchmove':
case 'MSPointerMove':
case 'mousemove':
this._move(e);
break;
case 'touchend':
case 'MSPointerUp':
case 'mouseup':
case 'touchcancel':
case 'MSPointerCancel':
case 'mousecancel':
this._end(e);
break;
case 'orientationchange':
case 'resize':
this._resize();
break;
case 'transitionend':
case 'webkitTransitionEnd':
case 'oTransitionEnd':
case 'MSTransitionEnd':
this._transitionEnd(e);
break;
case 'DOMMouseScroll':
case 'mousewheel':
this._wheel(e);
break;
case 'keydown':
this._key(e);
break;
case 'click':
if ( !e._constructed ) {
e.preventDefault();
e.stopPropagation();
}
break;
}
}
};
IScroll.ease = utils.ease;
return IScroll;
})(window, document, Math);
/**
* MicroEvent - to make any js object an event emitter (server or browser)
*
* - pure javascript - server compatible, browser compatible
* - dont rely on the browser doms
* - super simple - you get it immediatly, no mistery, no magic involved
*
* - create a MicroEventDebug with goodies to debug
* - make it safer to use
*/
/** NOTE: This library is customized for Onsen UI. */
var MicroEvent = function(){};
MicroEvent.prototype = {
on : function(event, fct){
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
once : function(event, fct){
var self = this;
var wrapper = function() {
self.off(event, wrapper);
return fct.apply(null, arguments);
};
this.on(event, wrapper);
},
off : function(event, fct){
this._events = this._events || {};
if( event in this._events === false ) return;
this._events[event].splice(this._events[event].indexOf(fct), 1);
},
emit : function(event /* , args... */){
this._events = this._events || {};
if( event in this._events === false ) return;
for(var i = 0; i < this._events[event].length; i++){
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
};
/**
* mixin will delegate all MicroEvent.js function in the destination object
*
* - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent
*
* @param {Object} the object which will support MicroEvent
*/
MicroEvent.mixin = function(destObject){
var props = ['on', 'once', 'off', 'emit'];
for(var i = 0; i < props.length; i ++){
if( typeof destObject === 'function' ){
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}else{
destObject[props[i]] = MicroEvent.prototype[props[i]];
}
}
}
// export in common js
if( typeof module !== "undefined" && ('exports' in module)){
module.exports = MicroEvent;
}
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-borderradius-boxshadow-cssanimations-csstransforms-csstransforms3d-csstransitions-canvas-svg-shiv-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
*/
;
window.Modernizr = (function( window, document, undefined ) {
var version = '2.6.2',
Modernizr = {},
enableClasses = true,
docElement = document.documentElement,
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
inputElem ,
toString = {}.toString,
prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
omPrefixes = 'Webkit Moz O ms',
cssomPrefixes = omPrefixes.split(' '),
domPrefixes = omPrefixes.toLowerCase().split(' '),
ns = {'svg': 'http://www.w3.org/2000/svg'},
tests = {},
inputs = {},
attrs = {},
classes = [],
slice = classes.slice,
featureName,
injectElementWithStyles = function( rule, callback, nodes, testnames ) {
var style, ret, node, docOverflow,
div = document.createElement('div'),
body = document.body,
fakeBody = body || document.createElement('body');
if ( parseInt(nodes, 10) ) {
while ( nodes-- ) {
node = document.createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
style = ['­','<style id="s', mod, '">', rule, '</style>'].join('');
div.id = mod;
(body ? div : fakeBody).innerHTML += style;
fakeBody.appendChild(div);
if ( !body ) {
fakeBody.style.background = '';
fakeBody.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(fakeBody);
}
ret = callback(div, rule);
if ( !body ) {
fakeBody.parentNode.removeChild(fakeBody);
docElement.style.overflow = docOverflow;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
},
_hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;
if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
hasOwnProp = function (object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function (object, property) {
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) {
var target = this;
if (typeof target != "function") {
throw new TypeError();
}
var args = slice.call(arguments, 1),
bound = function () {
if (this instanceof bound) {
var F = function(){};
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;
};
}
function setCss( str ) {
mStyle.cssText = str;
}
function setCssAll( str1, str2 ) {
return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
}
function is( obj, type ) {
return typeof obj === type;
}
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
function testProps( props, prefixed ) {
for ( var i in props ) {
var prop = props[i];
if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
return prefixed == 'pfx' ? prop : true;
}
}
return false;
}
function testDOMProps( props, obj, elem ) {
for ( var i in props ) {
var item = obj[props[i]];
if ( item !== undefined) {
if (elem === false) return props[i];
if (is(item, 'function')){
return item.bind(elem || obj);
}
return item;
}
}
return false;
}
function testPropsAll( prop, prefixed, elem ) {
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
if(is(prefixed, "string") || is(prefixed, "undefined")) {
return testProps(props, prefixed);
} else {
props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
return testDOMProps(props, prefixed, elem);
}
}
tests['canvas'] = function() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
tests['borderradius'] = function() {
return testPropsAll('borderRadius');
};
tests['boxshadow'] = function() {
return testPropsAll('boxShadow');
};
tests['cssanimations'] = function() {
return testPropsAll('animationName');
};
tests['csstransforms'] = function() {
return !!testPropsAll('transform');
};
tests['csstransforms3d'] = function() {
var ret = !!testPropsAll('perspective');
if ( ret && 'webkitPerspective' in docElement.style ) {
injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
ret = node.offsetLeft === 9 && node.offsetHeight === 3;
});
}
return ret;
};
tests['csstransitions'] = function() {
return testPropsAll('transition');
};
tests['svg'] = function() {
return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
};
for ( var feature in tests ) {
if ( hasOwnProp(tests, feature) ) {
featureName = feature.toLowerCase();
Modernizr[featureName] = tests[feature]();
classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
}
}
Modernizr.addTest = function ( feature, test ) {
if ( typeof feature == 'object' ) {
for ( var key in feature ) {
if ( hasOwnProp( feature, key ) ) {
Modernizr.addTest( key, feature[ key ] );
}
}
} else {
feature = feature.toLowerCase();
if ( Modernizr[feature] !== undefined ) {
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
if (typeof enableClasses !== "undefined" && enableClasses) {
docElement.className += ' ' + (test ? '' : 'no-') + feature;
}
Modernizr[feature] = test;
}
return Modernizr;
};
setCss('');
modElem = inputElem = null;
;(function(window, document) {
var options = window.html5 || {};
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
var supportsHtml5Styles;
var expando = '_html5shiv';
var expanID = 0;
var expandoData = {};
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}()); function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
return node.canHaveChildren && !reSkip.test(nodeName) ? data.frag.appendChild(node) : node;
}
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
getElements().join().replace(/\w+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
} function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
'article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}' +
'mark{background:#FF0;color:#000}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
} var html5 = {
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video',
'shivCSS': (options.shivCSS !== false),
'supportsUnknownElements': supportsUnknownElements,
'shivMethods': (options.shivMethods !== false),
'type': 'default',
'shivDocument': shivDocument,
createElement: createElement,
createDocumentFragment: createDocumentFragment
}; window.html5 = html5;
shivDocument(document);
}(this, document));
Modernizr._version = version;
Modernizr._prefixes = prefixes;
Modernizr._domPrefixes = domPrefixes;
Modernizr._cssomPrefixes = cssomPrefixes;
Modernizr.testProp = function(prop){
return testProps([prop]);
};
Modernizr.testAllProps = testPropsAll;
Modernizr.testStyles = injectElementWithStyles; docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +
(enableClasses ? ' js ' + classes.join(' ') : '');
return Modernizr;
})(this, this.document);
/*yepnope1.5.4|WTFPL*/
(function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}})(this,document);
Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0));};
;
/*
Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola
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 (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var setImmediate;
function addFromSetImmediateArguments(args) {
tasksByHandle[nextHandle] = partiallyApplied.apply(undefined, args);
return nextHandle++;
}
// This function accepts the same arguments as setImmediate, but
// returns a function that requires no arguments.
function partiallyApplied(handler) {
var args = [].slice.call(arguments, 1);
return function() {
if (typeof handler === "function") {
handler.apply(undefined, args);
} else {
(new Function("" + handler))();
}
};
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(partiallyApplied(runIfPresent, handle), 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
task();
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function installNextTickImplementation() {
setImmediate = function() {
var handle = addFromSetImmediateArguments(arguments);
process.nextTick(partiallyApplied(runIfPresent, handle));
return handle;
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
setImmediate = function() {
var handle = addFromSetImmediateArguments(arguments);
global.postMessage(messagePrefix + handle, "*");
return handle;
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
setImmediate = function() {
var handle = addFromSetImmediateArguments(arguments);
channel.port2.postMessage(handle);
return handle;
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
setImmediate = function() {
var handle = addFromSetImmediateArguments(arguments);
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
return handle;
};
}
function installSetTimeoutImplementation() {
setImmediate = function() {
var handle = addFromSetImmediateArguments(arguments);
setTimeout(partiallyApplied(runIfPresent, handle), 0);
return handle;
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 6–8
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
}(new Function("return this")()));
(function() {
function Viewport() {
this.PRE_IOS7_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no";
this.IOS7_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no";
this.DEFAULT_VIEWPORT = "initial-scale=1, maximum-scale=1, user-scalable=no";
this.ensureViewportElement();
this.platform = {};
this.platform.name = this.getPlatformName();
this.platform.version = this.getPlatformVersion();
return this;
};
Viewport.prototype.ensureViewportElement = function(){
this.viewportElement = document.querySelector('meta[name=viewport]');
if(!this.viewportElement){
this.viewportElement = document.createElement('meta');
this.viewportElement.name = "viewport";
document.head.appendChild(this.viewportElement);
}
},
Viewport.prototype.setup = function() {
if (!this.viewportElement) {
return;
}
if (this.viewportElement.getAttribute('data-no-adjust') == "true") {
return;
}
if (this.platform.name == 'ios') {
if (this.platform.version >= 7 && isWebView()) {
this.viewportElement.setAttribute('content', this.IOS7_VIEWPORT);
} else {
this.viewportElement.setAttribute('content', this.PRE_IOS7_VIEWPORT);
}
} else {
this.viewportElement.setAttribute('content', this.DEFAULT_VIEWPORT);
}
function isWebView() {
return !!(window.cordova || window.phonegap || window.PhoneGap);
}
};
Viewport.prototype.getPlatformName = function() {
if (navigator.userAgent.match(/Android/i)) {
return "android";
}
if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
return "ios";
}
// unknown
return undefined;
};
Viewport.prototype.getPlatformVersion = function() {
var start = window.navigator.userAgent.indexOf('OS ');
return window.Number(window.navigator.userAgent.substr(start + 3, 3).replace('_', '.'));
};
window.Viewport = Viewport;
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/back_button.tpl',
'<span \n' +
' class="toolbar-button--quiet {{modifierTemplater(\'toolbar-button--*\')}}" \n' +
' ng-click="$root.ons.findParentComponentUntil(\'ons-navigator\', $event).popPage({cancelIfRunning: true})"\n' +
' ng-show="showBackButton"\n' +
' style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n' +
' \n' +
' <i \n' +
' class="ion-ios-arrow-back ons-back-button__icon" \n' +
' style="vertical-align: top; background-color: transparent; height: 44px; line-height: 44px; font-size: 36px; margin-left: 8px; margin-right: 2px; width: 16px; display: inline-block; padding-top: 1px;"></i>\n' +
'\n' +
' <span \n' +
' style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;" \n' +
' class="back-button__label"></span>\n' +
'</span>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/button.tpl',
'<span class="label ons-button-inner"></span>\n' +
'<span class="spinner button__spinner {{modifierTemplater(\'button--*__spinner\')}}"></span>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/dialog.tpl',
'<div class="dialog-mask"></div>\n' +
'<div class="dialog {{ modifierTemplater(\'dialog--*\') }}"></div>\n' +
'</div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/icon.tpl',
'<i class="fa fa-{{icon}} fa-{{spin}} fa-{{fixedWidth}} fa-rotate-{{rotate}} fa-flip-{{flip}}" ng-class="sizeClass" ng-style="style"></i>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/popover.tpl',
'<div class="popover-mask"></div>\n' +
'<div class="popover popover--{{ direction }} {{ modifierTemplater(\'popover--*\') }}">\n' +
' <div class="popover__content {{ modifierTemplater(\'popover__content--*\') }}"></div>\n' +
' <div class="popover__{{ arrowPosition }}-arrow"></div>\n' +
'</div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/row.tpl',
'<div class="row row-{{align}} ons-row-inner"></div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/sliding_menu.tpl',
'<div class="onsen-sliding-menu__menu ons-sliding-menu-inner"></div>\n' +
'<div class="onsen-sliding-menu__main ons-sliding-menu-inner"></div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/split_view.tpl',
'<div class="onsen-split-view__secondary full-screen ons-split-view-inner"></div>\n' +
'<div class="onsen-split-view__main full-screen ons-split-view-inner"></div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/switch.tpl',
'<label class="switch {{modifierTemplater(\'switch--*\')}}">\n' +
' <input type="checkbox" class="switch__input {{modifierTemplater(\'switch--*__input\')}}" ng-model="model">\n' +
' <div class="switch__toggle {{modifierTemplater(\'switch--*__toggle\')}}"></div>\n' +
'</label>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/tab.tpl',
'<input type="radio" name="tab-bar-{{tabbarId}}" style="display: none">\n' +
'<button class="tab-bar__button tab-bar-inner {{tabbarModifierTemplater(\'tab-bar--*__button\')}} {{modifierTemplater(\'tab-bar__button--*\')}}" ng-click="tryToChange()">\n' +
'</button>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/tab_bar.tpl',
'<div class="ons-tab-bar__content tab-bar__content"></div>\n' +
'<div ng-hide="hideTabs" class="tab-bar ons-tab-bar__footer {{modifierTemplater(\'tab-bar--*\')}} ons-tabbar-inner"></div>\n' +
'');
}]);
})();
(function(module) {
try { module = angular.module('templates-main'); }
catch(err) { module = angular.module('templates-main', []); }
module.run(['$templateCache', function($templateCache) {
'use strict';
$templateCache.put('templates/toolbar_button.tpl',
'<span class="toolbar-button {{modifierTemplater(\'toolbar-button--*\')}} navigation-bar__line-height" ng-transclude></span>\n' +
'');
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
window.DoorLock = (function() {
/**
* Door locking system.
*
* @param {Object} [options]
* @param {Function} [options.log]
*/
var DoorLock = function(options) {
options = options || {};
this._lockList = [];
this._waitList = [];
this._log = options.log || function() {};
};
DoorLock.generateId = (function() {
var i = 0;
return function() {
return i++;
};
})();
DoorLock.prototype = {
/**
* Register a lock.
*
* @return {Function} Callback for unlocking.
*/
lock: function() {
var self = this;
var unlock = function() {
self._unlock(unlock);
};
unlock.id = DoorLock.generateId();
this._lockList.push(unlock);
this._log('lock: ' + (unlock.id));
return unlock;
},
_unlock: function(fn) {
var index = this._lockList.indexOf(fn);
if (index === -1) {
throw new Error('This function is not registered in the lock list.');
}
this._lockList.splice(index, 1);
this._log('unlock: ' + fn.id);
this._tryToFreeWaitList();
},
_tryToFreeWaitList: function() {
while (!this.isLocked() && this._waitList.length > 0) {
this._waitList.shift()();
}
},
/**
* Register a callback for waiting unlocked door.
*
* @params {Function} callback Callback on unlocking the door completely.
*/
waitUnlock: function(callback) {
if (!(callback instanceof Function)) {
throw new Error('The callback param must be a function.');
}
if (this.isLocked()) {
this._waitList.push(callback);
} else {
callback();
}
},
/**
* @return {Boolean}
*/
isLocked: function() {
return this._lockList.length > 0;
}
};
return DoorLock;
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
/**
* @ngdoc object
* @name ons
* @category util
* @description
* [ja]Onsen UIで利用できるグローバルなオブジェクトです。このオブジェクトは、AngularJSのスコープから参照することができます。 [/ja]
* [en]A global object that's used in Onsen UI. This object can be reached from the AngularJS scope.[/en]
*/
/**
* @ngdoc method
* @signature ready(callback)
* @description
* [ja]アプリの初期化に利用するメソッドです。渡された関数は、Onsen UIの初期化が終了している時点で必ず呼ばれます。[/ja]
* [en]Method used to wait for app initialization. The callback will not be executed until Onsen UI has been completely initialized.[/en]
* @param {Function} callback
* [en]Function that executes after Onsen UI has been initialized.[/en]
* [ja]Onsen UIが初期化が完了した後に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature bootstrap([moduleName, [dependencies]])
* @description
* [ja]Onsen UIの初期化を行います。Angular.jsのng-app属性を利用すること無しにOnsen UIを読み込んで初期化してくれます。[/ja]
* [en]Initialize Onsen UI. Can be used to load Onsen UI without using the <code>ng-app</code> attribute from AngularJS.[/en]
* @param {String} [moduleName]
* [en]AngularJS module name.[/en]
* [ja]Angular.jsでのモジュール名[/ja]
* @param {Array} [dependencies]
* [en]List of AngularJS module dependencies.[/en]
* [ja]依存するAngular.jsのモジュール名の配列[/ja]
* @return {Object}
* [en]An AngularJS module object.[/en]
* [ja]AngularJSのModuleオブジェクトを表します。[/ja]
*/
/**
* @ngdoc method
* @signature enableAutoStatusBarFill()
* @description
* [en]Enable status bar fill feature on iOS7 and above.[/en]
* [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を有効にします。[/ja]
*/
/**
* @ngdoc method
* @signature disableAutoStatusBarFill()
* @description
* [en]Disable status bar fill feature on iOS7 and above.[/en]
* [ja]iOS7以上で、ステータスバー部分の高さを自動的に埋める処理を無効にします。[/ja]
*/
/**
* @ngdoc method
* @signature findParentComponentUntil(name, [dom])
* @param {String} name
* [en]Name of component, i.e. 'ons-page'.[/en]
* [ja]コンポーネント名を指定します。例えばons-pageなどを指定します。[/ja]
* @param {Object|jqLite|HTMLElement} [dom]
* [en]$event, jqLite or HTMLElement object.[/en]
* [ja]$eventオブジェクト、jqLiteオブジェクト、HTMLElementオブジェクトのいずれかを指定できます。[/ja]
* @return {Object}
* [en]Component object. Will return null if no component was found.[/en]
* [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja]
* @description
* [en]Find parent component object of <code>dom</code> element.[/en]
* [ja]指定されたdom引数の親要素をたどってコンポーネントを検索します。[/ja]
*/
/**
* @ngdoc method
* @signature findComponent(selector, [dom])
* @param {String} selector
* [en]CSS selector[/en]
* [ja]CSSセレクターを指定します。[/ja]
* @param {HTMLElement} [dom]
* [en]DOM element to search from.[/en]
* [ja]検索対象とするDOM要素を指定します。[/ja]
* @return {Object}
* [en]Component object. Will return null if no component was found.[/en]
* [ja]コンポーネントのオブジェクトを返します。もしコンポーネントが見つからなかった場合にはnullを返します。[/ja]
* @description
* [en]Find component object using CSS selector.[/en]
* [ja]CSSセレクタを使ってコンポーネントのオブジェクトを検索します。[/ja]
*/
/**
* @ngdoc method
* @signature setDefaultDeviceBackButtonListener(listener)
* @param {Function} listener
* [en]Function that executes when device back button is pressed.[/en]
* [ja]デバイスのバックボタンが押された時に実行される関数オブジェクトを指定します。[/ja]
* @description
* [en]Set default handler for device back button.[/en]
* [ja]デバイスのバックボタンのためのデフォルトのハンドラを設定します。[/ja]
*/
/**
* @ngdoc method
* @signature disableDeviceBackButtonHandler()
* @description
* [en]Disable device back button event handler.[/en]
* [ja]デバイスのバックボタンのイベントを受け付けないようにします。[/ja]
*/
/**
* @ngdoc method
* @signature enableDeviceBackButtonHandler()
* @description
* [en]Enable device back button event handler.[/en]
* [ja]デバイスのバックボタンのイベントを受け付けるようにします。[/ja]
*/
/**
* @ngdoc method
* @signature isReady()
* @return {Boolean}
* [en]Will be true if Onsen UI is initialized.[/en]
* [ja]初期化されているかどうかを返します。[/ja]
* @description
* [en]Returns true if Onsen UI is initialized.[/en]
* [ja]Onsen UIがすでに初期化されているかどうかを返すメソッドです。[/ja]
*/
/**
* @ngdoc method
* @signature compile(dom)
* @param {HTMLElement} dom
* [en]Element to compile.[/en]
* [ja]コンパイルする要素を指定します。[/ja]
* @description
* [en]Compile Onsen UI components.[/en]
* [ja]通常のHTMLの要素をOnsen UIのコンポーネントにコンパイルします。[/ja]
*/
/**
* @ngdoc method
* @signature isWebView()
* @return {Boolean}
* [en]Will be true if the app is running in Cordova.[/en]
* [ja]Cordovaで実行されている場合にtrueになります。[/ja]
* @description
* [en]Returns true if running inside Cordova.[/en]
* [ja]Cordovaで実行されているかどうかを返すメソッドです。[/ja]
*/
/**
* @ngdoc method
* @signature createAlertDialog(page, [options])
* @param {String} page
* [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-alert-dialog> component.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Object} [options.parentScope]
* [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en]
* [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja]
* @return {Promise}
* [en]Promise object that resolves to the alert dialog component object.[/en]
* [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
* @description
* [en]Create a alert dialog instance from a template.[/en]
* [ja]テンプレートからアラートダイアログのインスタンスを生成します。[/ja]
*/
/**
* @ngdoc method
* @signature createDialog(page, [options])
* @param {String} page
* [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Object} [options.parentScope]
* [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en]
* [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja]
* @return {Promise}
* [en]Promise object that resolves to the dialog component object.[/en]
* [ja]ダイアログのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
* @description
* [en]Create a dialog instance from a template.[/en]
* [ja]テンプレートからダイアログのインスタンスを生成します。[/ja]
*/
/**
* @ngdoc method
* @signature createPopover(page, [options])
* @param {String} page
* [en]Page name. Can be either an HTML file or an <ons-template> containing a <ons-dialog> component.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Object} [options.parentScope]
* [en]Parent scope of the dialog. Used to bind models and access scope methods from the dialog.[/en]
* [ja]ダイアログ内で利用する親スコープを指定します。ダイアログからモデルやスコープのメソッドにアクセスするのに使います。[/ja]
* @return {Promise}
* [en]Promise object that resolves to the popover component object.[/en]
* [ja]ポップオーバーのコンポーネントオブジェクトを解決するPromiseオブジェクトを返します。[/ja]
* @description
* [en]Create a popover instance from a template.[/en]
* [ja]テンプレートからポップオーバーのインスタンスを生成します。[/ja]
*/
window.ons = (function(){
'use strict';
var module = angular.module('onsen', ['templates-main']);
angular.module('onsen.directives', ['onsen']); // for BC
// JS Global facade for Onsen UI.
var ons = createOnsenFacade();
initKeyboardEvents();
waitDeviceReady();
waitOnsenUILoad();
initAngularModule();
return ons;
function waitDeviceReady() {
var unlockDeviceReady = ons._readyLock.lock();
window.addEventListener('DOMContentLoaded', function() {
if (ons.isWebView()) {
window.document.addEventListener('deviceready', unlockDeviceReady, false);
} else {
unlockDeviceReady();
}
}, false);
}
function waitOnsenUILoad() {
var unlockOnsenUI = ons._readyLock.lock();
module.run(['$compile', '$rootScope', '$onsen', function($compile, $rootScope, $onsen) {
// for initialization hook.
if (document.readyState === 'loading' || document.readyState == 'uninitialized') {
window.addEventListener('DOMContentLoaded', function() {
document.body.appendChild(document.createElement('ons-dummy-for-init'));
});
} else if (document.body) {
document.body.appendChild(document.createElement('ons-dummy-for-init'));
} else {
throw new Error('Invalid initialization state.');
}
$rootScope.$on('$ons-ready', unlockOnsenUI);
}]);
}
function initAngularModule() {
module.value('$onsGlobal', ons);
module.run(['$compile', '$rootScope', '$onsen', '$q', function($compile, $rootScope, $onsen, $q) {
ons._onsenService = $onsen;
ons._qService = $q;
$rootScope.ons = window.ons;
$rootScope.console = window.console;
$rootScope.alert = window.alert;
ons.$compile = $compile;
}]);
}
function initKeyboardEvents() {
ons.softwareKeyboard = new MicroEvent();
ons.softwareKeyboard._visible = false;
var onShow = function() {
ons.softwareKeyboard._visible = true;
ons.softwareKeyboard.emit('show');
},
onHide = function() {
ons.softwareKeyboard._visible = false;
ons.softwareKeyboard.emit('hide');
};
var bindEvents = function() {
if (typeof Keyboard !== 'undefined') {
// https://github.com/martinmose/cordova-keyboard/blob/95f3da3a38d8f8e1fa41fbf40145352c13535a00/README.md
Keyboard.onshow = onShow;
Keyboard.onhide = onHide;
ons.softwareKeyboard.emit('init', {visible: Keyboard.isVisible});
return true;
} else if (typeof cordova.plugins !== 'undefined' && typeof cordova.plugins.Keyboard !== 'undefined') {
// https://github.com/driftyco/ionic-plugins-keyboard/blob/ca27ecf/README.md
window.addEventListener('native.keyboardshow', onShow);
window.addEventListener('native.keyboardhide', onHide);
ons.softwareKeyboard.emit('init', {visible: cordova.plugins.Keyboard.isVisible});
return true;
}
return false;
};
var noPluginError = function() {
console.warn('ons-keyboard: Cordova Keyboard plugin is not present.');
};
document.addEventListener('deviceready', function() {
if (!bindEvents()) {
if (document.querySelector('[ons-keyboard-active]') ||
document.querySelector('[ons-keyboard-inactive]')) {
noPluginError();
}
ons.softwareKeyboard.on = noPluginError;
}
});
}
function createOnsenFacade() {
var ons = {
_readyLock: new DoorLock(),
_onsenService: null,
_config: {
autoStatusBarFill: true
},
_unlockersDict: {},
// Object to attach component variables to when using the var="..." attribute.
// Can be set to null to avoid polluting the global scope.
componentBase: window,
/**
* Bootstrap this document as a Onsen UI application.
*
* @param {String} [name] optional name
* @param {Array} [deps] optional dependency modules
*/
bootstrap : function(name, deps) {
if (angular.isArray(name)) {
deps = name;
name = undefined;
}
if (!name) {
name = 'myOnsenApp';
}
deps = ['onsen'].concat(angular.isArray(deps) ? deps : []);
var module = angular.module(name, deps);
var doc = window.document;
if (doc.readyState == 'loading' || doc.readyState == 'uninitialized' || doc.readyState == 'interactive') {
doc.addEventListener('DOMContentLoaded', function() {
angular.bootstrap(doc.documentElement, [name]);
}, false);
} else if (doc.documentElement) {
angular.bootstrap(doc.documentElement, [name]);
} else {
throw new Error('Invalid state');
}
return module;
},
/**
* Enable status bar fill feature on iOS7 and above.
*/
enableAutoStatusBarFill: function() {
if (this.isReady()) {
throw new Error('This method must be called before ons.isReady() is true.');
}
this._config.autoStatusBarFill = true;
},
/**
* Disable status bar fill feature on iOS7 and above.
*/
disableAutoStatusBarFill: function() {
if (this.isReady()) {
throw new Error('This method must be called before ons.isReady() is true.');
}
this._config.autoStatusBarFill = false;
},
/**
* @param {String} [name]
* @param {Object/jqLite/HTMLElement} dom $event object or jqLite object or HTMLElement object.
* @return {Object}
*/
findParentComponentUntil: function(name, dom) {
var element;
if (dom instanceof HTMLElement) {
element = angular.element(dom);
} else if (dom instanceof angular.element) {
element = dom;
} else if (dom.target) {
element = angular.element(dom.target);
}
return element.inheritedData(name);
},
/**
* @param {Function} listener
*/
setDefaultDeviceBackButtonListener: function(listener) {
this._getOnsenService().getDefaultDeviceBackButtonHandler().setListener(listener);
},
/**
* Disable this framework to handle cordova "backbutton" event.
*/
disableDeviceBackButtonHandler: function() {
this._getOnsenService().DeviceBackButtonHandler.disable();
},
/**
* Enable this framework to handle cordova "backbutton" event.
*/
enableDeviceBackButtonHandler: function() {
this._getOnsenService().DeviceBackButtonHandler.enable();
},
/**
* Find view object correspond dom element queried by CSS selector.
*
* @param {String} selector CSS selector
* @param {HTMLElement} [dom]
* @return {Object/void}
*/
findComponent: function(selector, dom) {
var target = (dom ? dom : document).querySelector(selector);
return target ? angular.element(target).data(target.nodeName.toLowerCase()) || null : null;
},
/**
* @return {Boolean}
*/
isReady: function() {
return !ons._readyLock.isLocked();
},
/**
* @param {HTMLElement} dom
*/
compile : function(dom) {
if (!ons.$compile) {
throw new Error('ons.$compile() is not ready. Wait for initialization with ons.ready().');
}
if (!(dom instanceof HTMLElement)) {
throw new Error('First argument must be an instance of HTMLElement.');
}
var scope = angular.element(dom).scope();
if (!scope) {
throw new Error('AngularJS Scope is null. Argument DOM element must be attached in DOM document.');
}
ons.$compile(dom)(scope);
},
_getOnsenService: function() {
if (!this._onsenService) {
throw new Error('$onsen is not loaded, wait for ons.ready().');
}
return this._onsenService;
},
/**
* @param {Array} [dependencies]
* @param {Function} callback
*/
ready : function(/* dependencies, */callback) {
if (callback instanceof Function) {
if (ons.isReady()) {
callback();
} else {
ons._readyLock.waitUnlock(callback);
}
} else if (angular.isArray(callback) && arguments[1] instanceof Function) {
var dependencies = callback;
callback = arguments[1];
ons.ready(function() {
var $onsen = ons._getOnsenService();
$onsen.waitForVariables(dependencies, callback);
});
}
},
/**
* @return {Boolean}
*/
isWebView: function() {
if (document.readyState === 'loading' || document.readyState == 'uninitialized') {
throw new Error('isWebView() method is available after dom contents loaded.');
}
return !!(window.cordova || window.phonegap || window.PhoneGap);
},
/**
* @param {String} page
* @param {Object} [options]
* @param {Object} [options.parentScope]
* @return {Promise}
*/
createAlertDialog: function(page, options) {
options = options || {};
if (!page) {
throw new Error('Page url must be defined.');
}
var alertDialog = angular.element('<ons-alert-dialog>'),
$onsen = this._getOnsenService();
angular.element(document.body).append(angular.element(alertDialog));
return $onsen.getPageHTMLAsync(page).then(function(html) {
var div = document.createElement('div');
div.innerHTML = html;
var el = angular.element(div.querySelector('ons-alert-dialog'));
// Copy attributes and insert html.
var attrs = el.prop('attributes');
for (var i = 0, l = attrs.length; i < l; i++) {
alertDialog.attr(attrs[i].name, attrs[i].value);
}
alertDialog.html(el.html());
var parentScope;
if (options.parentScope) {
parentScope = options.parentScope.$new();
ons.$compile(alertDialog)(parentScope);
}
else {
ons.compile(alertDialog[0]);
}
if (el.attr('disabled')) {
alertDialog.attr('disabled', 'disabled');
}
if (parentScope) {
alertDialog.data('ons-alert-dialog')._parentScope = parentScope;
}
return alertDialog.data('ons-alert-dialog');
});
},
/**
* @param {String} page
* @param {Object} [options]
* @param {Object} [options.parentScope]
* @return {Promise}
*/
createDialog: function(page, options) {
options = options || {};
if (!page) {
throw new Error('Page url must be defined.');
}
var dialog = angular.element('<ons-dialog>'),
$onsen = this._getOnsenService();
angular.element(document.body).append(angular.element(dialog));
return $onsen.getPageHTMLAsync(page).then(function(html) {
var div = document.createElement('div');
div.innerHTML = html;
var el = angular.element(div.querySelector('ons-dialog'));
// Copy attributes and insert html.
var attrs = el.prop('attributes');
for (var i = 0, l = attrs.length; i < l; i++) {
dialog.attr(attrs[i].name, attrs[i].value);
}
dialog.html(el.html());
var parentScope;
if (options.parentScope) {
parentScope = options.parentScope.$new();
ons.$compile(dialog)(parentScope);
}
else {
ons.compile(dialog[0]);
}
if (el.attr('disabled')) {
dialog.attr('disabled', 'disabled');
}
var deferred = ons._qService.defer();
dialog.on('ons-dialog:init', function(e) {
// Copy "style" attribute from parent.
var child = dialog[0].querySelector('.dialog');
if (el[0].hasAttribute('style')) {
var parentStyle = el[0].getAttribute('style'),
childStyle = child.getAttribute('style'),
newStyle = (function(a, b) {
var c =
(a.substr(-1) === ';' ? a : a + ';') +
(b.substr(-1) === ';' ? b : b + ';');
return c;
})(parentStyle, childStyle);
child.setAttribute('style', newStyle);
}
if (parentScope) {
e.component._parentScope = parentScope;
}
deferred.resolve(e.component);
});
return deferred.promise;
});
},
/**
* @param {String} page
* @param {Object} [options]
* @param {Object} [options.parentScope]
* @return {Promise}
*/
createPopover: function(page, options) {
options = options || {};
if (!page) {
throw new Error('Page url must be defined.');
}
var popover = angular.element('<ons-popover>'),
$onsen = this._getOnsenService();
angular.element(document.body).append(angular.element(popover));
return $onsen.getPageHTMLAsync(page).then(function(html) {
var div = document.createElement('div');
div.innerHTML = html;
var el = angular.element(div.querySelector('ons-popover'));
// Copy attributes and insert html.
var attrs = el.prop('attributes');
for (var i = 0, l = attrs.length; i < l; i++) {
popover.attr(attrs[i].name, attrs[i].value);
}
popover.html(el.html());
var parentScope;
if (options.parentScope) {
parentScope = options.parentScope.$new();
ons.$compile(popover)(parentScope);
}
else {
ons.compile(popover[0]);
}
if (el.attr('disabled')) {
popover.attr('disabled', 'disabled');
}
var deferred = ons._qService.defer();
popover.on('ons-popover:init', function(e) {
// Copy "style" attribute from parent.
var child = popover[0].querySelector('.popover');
if (el[0].hasAttribute('style')) {
var parentStyle = el[0].getAttribute('style'),
childStyle = child.getAttribute('style'),
newStyle = (function(a, b) {
var c =
(a.substr(-1) === ';' ? a : a + ';') +
(b.substr(-1) === ';' ? b : b + ';');
return c;
})(parentStyle, childStyle);
child.setAttribute('style', newStyle);
}
if (parentScope) {
e.component._parentScope = parentScope;
}
deferred.resolve(e.component);
});
return deferred.promise;
});
}
};
return ons;
}
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('AlertDialogView', ['$onsen', 'DialogAnimator', 'SlideDialogAnimator', 'AndroidAlertDialogAnimator', 'IOSAlertDialogAnimator', function($onsen, DialogAnimator, SlideDialogAnimator, AndroidAlertDialogAnimator, IOSAlertDialogAnimator) {
var AlertDialogView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._scope = scope;
this._element = element;
this._attrs = attrs;
this._element.css({
display: 'none',
zIndex: 20001
});
this._dialog = element;
this._visible = false;
this._doorLock = new DoorLock();
this._animation = AlertDialogView._animatorDict[typeof attrs.animation !== 'undefined' ?
attrs.animation : 'default'];
if (!this._animation) {
throw new Error('No such animation: ' + attrs.animation);
}
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
this._createMask(attrs.maskColor);
this._scope.$on('$destroy', this._destroy.bind(this));
},
/**
* Show alert dialog.
*
* @param {Object} [options]
* @param {String} [options.animation] animation type
* @param {Function} [options.callback] callback after dialog is shown
*/
show: function(options) {
options = options || {};
var cancel = false,
callback = options.callback || function() {};
this.emit('preshow', {
alertDialog: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
this._mask.css('display', 'block');
this._mask.css('opacity', 1);
this._element.css('display', 'block');
if (options.animation) {
animation = AlertDialogView._animatorDict[options.animation];
}
animation.show(this, function() {
this._visible = true;
unlock();
this.emit('postshow', {alertDialog: this});
callback();
}.bind(this));
}.bind(this));
}
},
/**
* Hide alert dialog.
*
* @param {Object} [options]
* @param {String} [options.animation] animation type
* @param {Function} [options.callback] callback after dialog is hidden
*/
hide: function(options) {
options = options || {};
var cancel = false,
callback = options.callback || function() {};
this.emit('prehide', {
alertDialog: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
if (options.animation) {
animation = AlertDialogView._animatorDict[options.animation];
}
animation.hide(this, function() {
this._element.css('display', 'none');
this._mask.css('display', 'none');
this._visible = false;
unlock();
this.emit('posthide', {alertDialog: this});
callback();
}.bind(this));
}.bind(this));
}
},
/**
* True if alert dialog is visible.
*
* @return {Boolean}
*/
isShown: function() {
return this._visible;
},
/**
* Destroy alert dialog.
*/
destroy: function() {
if (this._parentScope) {
this._parentScope.$destroy();
this._parentScope = null;
} else {
this._scope.$destroy();
}
},
_destroy: function() {
this.emit('destroy');
this._mask.off();
this._element.remove();
this._mask.remove();
this._deviceBackButtonHandler.destroy();
this._deviceBackButtonHandler = this._scope = this._attrs = this._element = this._mask = null;
},
/**
* Disable or enable alert dialog.
*
* @param {Boolean}
*/
setDisabled: function(disabled) {
if (typeof disabled !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (disabled) {
this._element.attr('disabled', true);
} else {
this._element.removeAttr('disabled');
}
},
/**
* True if alert dialog is disabled.
*
* @return {Boolean}
*/
isDisabled: function() {
return this._element[0].hasAttribute('disabled');
},
/**
* Make alert dialog cancelable or uncancelable.
*
* @param {Boolean}
*/
setCancelable: function(cancelable) {
if (typeof cancelable !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (cancelable) {
this._element.attr('cancelable', true);
} else {
this._element.removeAttr('cancelable');
}
},
isCancelable: function() {
return this._element[0].hasAttribute('cancelable');
},
_cancel: function() {
if (this.isCancelable()) {
this.hide({
callback: function () {
this.emit('cancel');
}.bind(this)
});
}
},
_onDeviceBackButton: function(event) {
if (this.isCancelable()) {
this._cancel.bind(this)();
} else {
event.callParentHandler();
}
},
_createMask: function(color) {
this._mask = angular.element('<div>').addClass('alert-dialog-mask').css({
zIndex: 20000,
display: 'none'
});
this._mask.on('click', this._cancel.bind(this));
if (color) {
this._mask.css('background-color', color);
}
angular.element(document.body).append(this._mask);
}
});
AlertDialogView._animatorDict = {
'default': $onsen.isAndroid() ? new AndroidAlertDialogAnimator() : new IOSAlertDialogAnimator(),
'fade': $onsen.isAndroid() ? new AndroidAlertDialogAnimator() : new IOSAlertDialogAnimator(),
'slide': new SlideDialogAnimator(),
'none': new DialogAnimator()
};
/**
* @param {String} name
* @param {DialogAnimator} animator
*/
AlertDialogView.registerAnimator = function(name, animator) {
if (!(animator instanceof DialogAnimator)) {
throw new Error('"animator" param must be an instance of DialogAnimator');
}
this._animatorDict[name] = animator;
};
MicroEvent.mixin(AlertDialogView);
return AlertDialogView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('AndroidAlertDialogAnimator', ['DialogAnimator', function(DialogAnimator) {
/**
* Android style animator for alert dialog.
*/
var AndroidAlertDialogAnimator = DialogAnimator.extend({
timing: 'cubic-bezier(.1, .7, .4, 1)',
duration: 0.2,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
show: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)',
opacity: 0.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)',
opacity: 1.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
hide: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)',
opacity: 0.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return AndroidAlertDialogAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('AndroidDialogAnimator', ['DialogAnimator', function(DialogAnimator) {
/**
* Android style animator for dialog.
*/
var AndroidDialogAnimator = DialogAnimator.extend({
timing: 'ease-in-out',
duration: 0.3,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
show: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -60%, 0)',
opacity: 0.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0)',
opacity: 1.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
hide: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -60%, 0)',
opacity: 0.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return AndroidDialogAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('ButtonView', ['$onsen', function($onsen) {
var ButtonView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element;
this._scope = scope;
this._attrs = attrs;
},
/**
* Start spinning.
*/
startSpin: function() {
this._attrs.$set('shouldSpin', 'true');
},
/**
* Stop spinning.
*/
stopSpin: function() {
this._attrs.$set('shouldSpin', 'false');
},
/**
* Returns whether button is spinning or not.
*/
isSpinning: function() {
return this._attrs.shouldSpin === 'true';
},
/**
* Set spin animation.
*
* @param {String} animation type
*/
setSpinAnimation: function(animation) {
this._scope.$apply(function() {
var animations = ['slide-left', 'slide-right', 'slide-up',
'slide-down', 'expand-left', 'expand-right', 'expand-up',
'expand-down', 'zoom-out', 'zoom-in'];
if (animations.indexOf(animation) < 0) {
console.warn('Animation ' + animation + 'doesn\'t exist.');
animation = 'slide-left';
}
this._scope.animation = animation;
}.bind(this));
},
/**
* Returns whether the button is disabled or not.
*/
isDisabled: function() {
return this._element[0].hasAttribute('disabled');
},
/**
* Disabled or enable button.
*/
setDisabled: function(disabled) {
if (typeof disabled !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (disabled) {
this._element[0].setAttribute('disabled', '');
} else {
this._element[0].removeAttribute('disabled');
}
}
});
MicroEvent.mixin(ButtonView);
return ButtonView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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
:qaistributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function() {
'use strict;';
var module = angular.module('onsen');
module.factory('CarouselView', ['$onsen', function($onsen) {
var VerticalModeTrait = {
_getScrollDelta: function(event) {
return event.gesture.deltaY;
},
_getScrollVelocity: function(event) {
return event.gesture.velocityY;
},
_getElementSize: function() {
if (!this._currentElementSize) {
this._currentElementSize = this._element[0].getBoundingClientRect().height;
}
return this._currentElementSize;
},
_generateScrollTransform: function(scroll) {
return 'translate3d(0px, ' + -scroll + 'px, 0px)';
},
_layoutCarouselItems: function() {
var children = this._getCarouselItemElements();
var sizeAttr = this._getCarouselItemSizeAttr();
var sizeInfo = this._decomposeSizeString(sizeAttr);
for (var i = 0; i < children.length; i++) {
angular.element(children[i]).css({
position: 'absolute',
height: sizeAttr,
width: '100%',
visibility: 'visible',
left: '0px',
top: (i * sizeInfo.number) + sizeInfo.unit
});
}
},
};
var HorizontalModeTrait = {
_getScrollDelta: function(event) {
return event.gesture.deltaX;
},
_getScrollVelocity: function(event) {
return event.gesture.velocityX;
},
_getElementSize: function() {
if (!this._currentElementSize) {
this._currentElementSize = this._element[0].getBoundingClientRect().width;
}
return this._currentElementSize;
},
_generateScrollTransform: function(scroll) {
return 'translate3d(' + -scroll + 'px, 0px, 0px)';
},
_layoutCarouselItems: function() {
var children = this._getCarouselItemElements();
var sizeAttr = this._getCarouselItemSizeAttr();
var sizeInfo = this._decomposeSizeString(sizeAttr);
for (var i = 0; i < children.length; i++) {
angular.element(children[i]).css({
position: 'absolute',
width: sizeAttr,
height: '100%',
top: '0px',
visibility: 'visible',
left: (i * sizeInfo.number) + sizeInfo.unit
});
}
},
};
/**
* @class CarouselView
*/
var CarouselView = Class.extend({
/**
* @member jqLite Object
*/
_element: undefined,
/**
* @member {Object}
*/
_scope: undefined,
/**
* @member {DoorLock}
*/
_doorLock: undefined,
/**
* @member {Number}
*/
_scroll: undefined,
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element;
this._scope = scope;
this._attrs = attrs;
this._doorLock = new DoorLock();
this._scroll = 0;
this._lastActiveIndex = 0;
this._bindedOnDrag = this._onDrag.bind(this);
this._bindedOnDragEnd = this._onDragEnd.bind(this);
this._bindedOnResize = this._onResize.bind(this);
this._mixin(this._isVertical() ? VerticalModeTrait : HorizontalModeTrait);
this._prepareEventListeners();
this._layoutCarouselItems();
this._setupInitialIndex();
this._attrs.$observe('direction', this._onDirectionChange.bind(this));
this._scope.$on('$destroy', this._destroy.bind(this));
this._saveLastState();
},
_onResize: function() {
this.refresh();
},
_onDirectionChange: function() {
if (this._isVertical()) {
this._element.css({
overflowX: 'auto',
overflowY: ''
});
}
else {
this._element.css({
overflowX: '',
overflowY: 'auto'
});
}
},
_saveLastState: function() {
this._lastState = {
elementSize: this._getCarouselItemSize(),
carouselElementCount: this._getCarouselItemCount(),
width: this._getCarouselItemSize() * this._getCarouselItemCount()
};
},
/**
* @return {Number}
*/
_getCarouselItemSize: function() {
var sizeAttr = this._getCarouselItemSizeAttr();
var sizeInfo = this._decomposeSizeString(sizeAttr);
var elementSize = this._getElementSize();
if (sizeInfo.unit === '%') {
return Math.round(sizeInfo.number / 100 * elementSize);
} else if (sizeInfo.unit === 'px') {
return sizeInfo.number;
} else {
throw new Error('Invalid state');
}
},
/**
* @return {Number}
*/
_getInitialIndex: function() {
var index = parseInt(this._element.attr('initial-index'), 10);
if (typeof index === 'number' && !isNaN(index)) {
return Math.max(Math.min(index, this._getCarouselItemCount() - 1), 0);
} else {
return 0;
}
},
/**
* @return {String}
*/
_getCarouselItemSizeAttr: function() {
var attrName = 'item-' + (this._isVertical() ? 'height' : 'width');
var itemSizeAttr = ('' + this._element.attr(attrName)).trim();
return itemSizeAttr.match(/^\d+(px|%)$/) ? itemSizeAttr : '100%';
},
/**
* @return {Object}
*/
_decomposeSizeString: function(size) {
var matches = size.match(/^(\d+)(px|%)/);
return {
number: parseInt(matches[1], 10),
unit: matches[2],
};
},
_setupInitialIndex: function() {
this._scroll = this._getCarouselItemSize() * this._getInitialIndex();
this._lastActiveIndex = this._getInitialIndex();
this._scrollTo(this._scroll);
},
/**
* @param {Boolean} swipeable
*/
setSwipeable: function(swipeable) {
if (swipeable) {
this._element[0].setAttribute('swipeable', '');
} else {
this._element[0].removeAttribute('swipeable');
}
},
/**
* @return {Boolean}
*/
isSwipeable: function() {
return this._element[0].hasAttribute('swipeable');
},
/**
* @param {Number} ratio
*/
setAutoScrollRatio: function(ratio) {
if (ratio < 0.0 || ratio > 1.0) {
throw new Error('Invalid ratio.');
}
this._element[0].setAttribute('auto-scroll-ratio', ratio);
},
/**
* @return {Number}
*/
getAutoScrollRatio: function(ratio) {
var attr = this._element[0].getAttribute('auto-scroll-ratio');
if (!attr) {
return 0.5;
}
var scrollRatio = parseFloat(attr);
if (scrollRatio < 0.0 || scrollRatio > 1.0) {
throw new Error('Invalid ratio.');
}
return isNaN(scrollRatio) ? 0.5 : scrollRatio;
},
/**
* @param {Number} index
* @param {Object} [options]
* @param {Function} [options.callback]
* @param {String} [options.animation]
*/
setActiveCarouselItemIndex: function(index, options) {
options = options || {};
index = Math.max(0, Math.min(index, this._getCarouselItemCount() - 1));
var scroll = this._getCarouselItemSize() * index;
var max = this._calculateMaxScroll();
this._scroll = Math.max(0, Math.min(max, scroll));
this._scrollTo(this._scroll, {animate: options.animation !== 'none', callback: options.callback});
this._tryFirePostChangeEvent();
},
/**
* @return {Number}
*/
getActiveCarouselItemIndex: function() {
var scroll = this._scroll;
var count = this._getCarouselItemCount();
var size = this._getCarouselItemSize();
if (scroll < 0) {
return 0;
}
for (var i = 0; i < count; i++) {
if (size * i <= scroll && size * (i + 1) > scroll) {
return i;
}
}
// max carousel index
return i;
},
/**
* @param {Object} [options]
* @param {Function} [options.callback]
* @param {String} [options.animation]
*/
next: function(options) {
this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex() + 1, options);
},
/**
* @param {Object} [options]
* @param {Function} [options.callback]
* @param {String} [options.animation]
*/
prev: function(options) {
this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex() - 1, options);
},
/**
* @param {Boolean} enabled
*/
setAutoScrollEnabled: function(enabled) {
if (enabled) {
this._element[0].setAttribute('auto-scroll', '');
} else {
this._element[0].removeAttribute('auto-scroll');
}
},
/**
* @param {Boolean} enabled
*/
isAutoScrollEnabled: function(enabled) {
return this._element[0].hasAttribute('auto-scroll');
},
/**
* @param {Boolean} disabled
*/
setDisabled: function(disabled) {
if (disabled) {
this._element[0].setAttribute('disabled', '');
} else {
this._element[0].removeAttribute('disabled');
}
},
/**
* @return {Boolean}
*/
isDisabled: function() {
return this._element[0].hasAttribute('disabled');
},
/**
* @param {Boolean} scrollable
*/
setOverscrollable: function(scrollable) {
if (scrollable) {
this._element[0].setAttribute('overscrollable', '');
} else {
this._element[0].removeAttribute('overscrollable');
}
},
/**
* @param {Object} trait
*/
_mixin: function(trait) {
Object.keys(trait).forEach(function(key) {
this[key] = trait[key];
}.bind(this));
},
/**
* @return {Boolean}
*/
_isEnabledChangeEvent: function() {
var elementSize = this._getElementSize();
var carouselItemSize = this._getCarouselItemSize();
return this.isAutoScrollEnabled() && elementSize === carouselItemSize;
},
/**
* @return {Boolean}
*/
_isVertical: function() {
return this._element.attr('direction') === 'vertical';
},
_prepareEventListeners: function() {
this._hammer = new Hammer(this._element[0], {
dragMinDistance: 1
});
this._hammer.on('drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown', this._bindedOnDrag);
this._hammer.on('dragend', this._bindedOnDragEnd);
angular.element(window).on('resize', this._bindedOnResize);
},
_tryFirePostChangeEvent: function() {
var currentIndex = this.getActiveCarouselItemIndex();
if (this._lastActiveIndex !== currentIndex) {
var lastActiveIndex = this._lastActiveIndex;
this._lastActiveIndex = currentIndex;
this.emit('postchange', {
carousel: this,
activeIndex: currentIndex,
lastActiveIndex: lastActiveIndex
});
}
},
_onDrag: function(event) {
if (!this.isSwipeable()) {
return;
}
var direction = event.gesture.direction;
if ((this._isVertical() && (direction === 'left' || direction === 'right')) || (!this._isVertical() && (direction === 'up' || direction === 'down'))) {
return;
}
event.stopPropagation();
this._lastDragEvent = event;
var scroll = this._scroll - this._getScrollDelta(event);
this._scrollTo(scroll);
event.gesture.preventDefault();
this._tryFirePostChangeEvent();
},
_onDragEnd: function(event) {
this._currentElementSize = undefined;
this._carouselItemElements = undefined;
if (!this.isSwipeable()) {
return;
}
this._scroll = this._scroll - this._getScrollDelta(event);
if (this._getScrollDelta(event) !== 0) {
event.stopPropagation();
}
if (this._isOverScroll(this._scroll)) {
var waitForAction = false;
this.emit('overscroll', {
carousel: this,
activeIndex: this.getActiveCarouselItemIndex(),
direction: this._getOverScrollDirection(),
waitToReturn: function(promise) {
waitForAction = true;
promise.then(
function() {
this._scrollToKillOverScroll();
}.bind(this)
);
}.bind(this)
});
if (!waitForAction) {
this._scrollToKillOverScroll();
}
} else {
this._startMomemtumScroll(event);
}
this._lastDragEvent = null;
event.gesture.preventDefault();
},
_getTouchEvents: function() {
var EVENTS = [
'drag', 'dragstart', 'dragend',
'dragup', 'dragdown', 'dragleft',
'dragright', 'swipe', 'swipeup',
'swipedown', 'swipeleft', 'swiperight'
];
return EVENTS.join(' ');
},
/**
* @return {Boolean}
*/
isOverscrollable: function() {
return this._element[0].hasAttribute('overscrollable');
},
_startMomemtumScroll: function(event) {
if (this._lastDragEvent) {
var velocity = this._getScrollVelocity(this._lastDragEvent);
var duration = 0.3;
var scrollDelta = duration * 100 * velocity;
var scroll = this._scroll + (this._getScrollDelta(this._lastDragEvent) > 0 ? -scrollDelta : scrollDelta);
scroll = this._normalizeScrollPosition(scroll);
this._scroll = scroll;
animit(this._getCarouselItemElements())
.queue({
transform: this._generateScrollTransform(this._scroll)
}, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
done();
this._tryFirePostChangeEvent();
}.bind(this))
.play();
}
},
_normalizeScrollPosition: function(scroll) {
var max = this._calculateMaxScroll();
if (this.isAutoScrollEnabled()) {
var arr = [];
var size = this._getCarouselItemSize();
for (var i = 0; i < this._getCarouselItemCount(); i++) {
if (max >= i * size) {
arr.push(i * size);
}
}
arr.push(max);
arr.sort(function(left, right) {
left = Math.abs(left - scroll);
right = Math.abs(right - scroll);
return left - right;
});
arr = arr.filter(function(item, pos) {
return !pos || item != arr[pos - 1];
});
var lastScroll = this._lastActiveIndex * size,
scrollRatio = Math.abs(scroll - lastScroll) / size;
if (scrollRatio <= this.getAutoScrollRatio()) {
return lastScroll;
}
else if (scrollRatio > this.getAutoScrollRatio() && scrollRatio < 1.0) {
if (arr[0] === lastScroll && arr.length > 1) {
return arr[1];
}
}
return arr[0];
} else {
return Math.max(0, Math.min(max, scroll));
}
},
/**
* @return {Array}
*/
_getCarouselItemElements: function() {
var nodeList = this._element[0].children,
rv = [];
for (var i = nodeList.length; i--; ) {
rv.unshift(nodeList[i]);
}
rv = rv.filter(function(item) {
return item.nodeName.toLowerCase() === 'ons-carousel-item';
});
return rv;
},
/**
* @param {Number} scroll
* @param {Object} [options]
*/
_scrollTo: function(scroll, options) {
options = options || {};
var self = this;
var isOverscrollable = this.isOverscrollable();
if (options.animate) {
animit(this._getCarouselItemElements())
.queue({
transform: this._generateScrollTransform(normalizeScroll(scroll))
}, {
duration: 0.3,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play(options.callback);
} else {
animit(this._getCarouselItemElements())
.queue({
transform: this._generateScrollTransform(normalizeScroll(scroll))
})
.play(options.callback);
}
function normalizeScroll(scroll) {
var ratio = 0.35;
if (scroll < 0) {
return isOverscrollable ? Math.round(scroll * ratio) : 0;
}
var maxScroll = self._calculateMaxScroll();
if (maxScroll < scroll) {
return isOverscrollable ? maxScroll + Math.round((scroll - maxScroll) * ratio) : maxScroll;
}
return scroll;
}
},
_calculateMaxScroll: function() {
var max = this._getCarouselItemCount() * this._getCarouselItemSize() - this._getElementSize();
return Math.ceil(max < 0 ? 0 : max); // Need to return an integer value.
},
_isOverScroll: function(scroll) {
if (scroll < 0 || scroll > this._calculateMaxScroll()) {
return true;
}
return false;
},
_getOverScrollDirection: function() {
if (this._isVertical()) {
if (this._scroll <= 0) {
return 'up';
}
else {
return 'down';
}
}
else {
if (this._scroll <= 0) {
return 'left';
}
else {
return 'right';
}
}
},
_scrollToKillOverScroll: function() {
var duration = 0.4;
if (this._scroll < 0) {
animit(this._getCarouselItemElements())
.queue({
transform: this._generateScrollTransform(0)
}, {
duration: duration,
timing: 'cubic-bezier(.1, .4, .1, 1)'
})
.play();
this._scroll = 0;
return;
}
var maxScroll = this._calculateMaxScroll();
if (maxScroll < this._scroll) {
animit(this._getCarouselItemElements())
.queue({
transform: this._generateScrollTransform(maxScroll)
}, {
duration: duration,
timing: 'cubic-bezier(.1, .4, .1, 1)'
})
.play();
this._scroll = maxScroll;
return;
}
return;
},
/**
* @return {Number}
*/
_getCarouselItemCount: function() {
return this._getCarouselItemElements().length;
},
/**
* Refresh carousel item layout.
*/
refresh: function() {
// Bug fix
if (this._getCarouselItemSize() === 0) {
return;
}
this._mixin(this._isVertical() ? VerticalModeTrait : HorizontalModeTrait);
this._layoutCarouselItems();
if (this._lastState && this._lastState.width > 0) {
var scroll = this._scroll;
if (this._isOverScroll(scroll)) {
this._scrollToKillOverScroll();
}
else {
if (this.isAutoScrollEnabled()) {
scroll = this._normalizeScrollPosition(scroll);
}
this._scrollTo(scroll);
}
}
this._saveLastState();
this.emit('refresh', {
carousel: this
});
},
/**
*/
first: function() {
this.setActiveCarouselItemIndex(0);
},
/**
*/
last: function() {
this.setActiveCarouselItemIndex(
Math.max(this._getCarouselItemCount() - 1, 0)
);
},
_destroy: function() {
this.emit('destroy');
this._hammer.off('drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown', this._bindedOnDrag);
this._hammer.off('dragend', this._bindedOnDragEnd);
angular.element(window).off('resize', this._bindedOnResize);
this._element = this._scope = this._attrs = null;
}
});
MicroEvent.mixin(CarouselView);
return CarouselView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('DialogView', ['$onsen', 'DialogAnimator', 'IOSDialogAnimator', 'AndroidDialogAnimator', 'SlideDialogAnimator', function($onsen, DialogAnimator, IOSDialogAnimator, AndroidDialogAnimator, SlideDialogAnimator) {
var DialogView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._scope = scope;
this._element = element;
this._attrs = attrs;
this._element.css('display', 'none');
this._dialog = angular.element(element[0].querySelector('.dialog'));
this._mask = angular.element(element[0].querySelector('.dialog-mask'));
this._dialog.css('z-index', 20001);
this._mask.css('z-index', 20000);
this._mask.on('click', this._cancel.bind(this));
this._visible = false;
this._doorLock = new DoorLock();
this._animation = DialogView._animatorDict[typeof attrs.animation !== 'undefined' ?
attrs.animation : 'default'];
if (!this._animation) {
throw new Error('No such animation: ' + attrs.animation);
}
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
this._scope.$on('$destroy', this._destroy.bind(this));
},
/**
* @return {Object}
*/
getDeviceBackButtonHandler: function() {
return this._deviceBackButtonHandler;
},
/**
* Show dialog.
*
* @param {Object} [options]
* @param {String} [options.animation] animation type
* @param {Function} [options.callback] callback after dialog is shown
*/
show: function(options) {
options = options || {};
var cancel = false,
callback = options.callback || function() {};
this.emit('preshow', {
dialog: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
this._element.css('display', 'block');
this._mask.css('opacity', 1);
if (options.animation) {
animation = DialogView._animatorDict[options.animation];
}
animation.show(this, function() {
this._visible = true;
unlock();
this.emit('postshow', {dialog: this});
callback();
}.bind(this));
}.bind(this));
}
},
/**
* Hide dialog.
*
* @param {Object} [options]
* @param {String} [options.animation] animation type
* @param {Function} [options.callback] callback after dialog is hidden
*/
hide: function(options) {
options = options || {};
var cancel = false,
callback = options.callback || function() {};
this.emit('prehide', {
dialog: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
if (options.animation) {
animation = DialogView._animatorDict[options.animation];
}
animation.hide(this, function() {
this._element.css('display', 'none');
this._visible = false;
unlock();
this.emit('posthide', {dialog: this});
callback();
}.bind(this));
}.bind(this));
}
},
/**
* True if dialog is visible.
*
* @return {Boolean}
*/
isShown: function() {
return this._visible;
},
/**
* Destroy dialog.
*/
destroy: function() {
if (this._parentScope) {
this._parentScope.$destroy();
this._parentScope = null;
} else {
this._scope.$destroy();
}
},
_destroy: function() {
this.emit('destroy');
this._element.remove();
this._deviceBackButtonHandler.destroy();
this._mask.off();
this._deviceBackButtonHandler = this._scope = this._attrs = this._element = this._dialog = this._mask = null;
},
/**
* Disable or enable dialog.
*
* @param {Boolean}
*/
setDisabled: function(disabled) {
if (typeof disabled !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (disabled) {
this._element.attr('disabled', true);
} else {
this._element.removeAttr('disabled');
}
},
/**
* True if dialog is disabled.
*
* @return {Boolean}
*/
isDisabled: function() {
return this._element[0].hasAttribute('disabled');
},
/**
* Make dialog cancelable or uncancelable.
*
* @param {Boolean}
*/
setCancelable: function(cancelable) {
if (typeof cancelable !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (cancelable) {
this._element.attr('cancelable', true);
} else {
this._element.removeAttr('cancelable');
}
},
/**
* True if the dialog is cancelable.
*
* @return {Boolean}
*/
isCancelable: function() {
return this._element[0].hasAttribute('cancelable');
},
_cancel: function() {
if (this.isCancelable()) {
this.hide({
callback: function () {
this.emit('cancel');
}.bind(this)
});
}
},
_onDeviceBackButton: function(event) {
if (this.isCancelable()) {
this._cancel.bind(this)();
} else {
event.callParentHandler();
}
}
});
DialogView._animatorDict = {
'default': $onsen.isAndroid() ? new AndroidDialogAnimator() : new IOSDialogAnimator(),
'fade': $onsen.isAndroid() ? new AndroidDialogAnimator() : new IOSDialogAnimator(),
'slide': new SlideDialogAnimator(),
'none': new DialogAnimator()
};
/**
* @param {String} name
* @param {DialogAnimator} animator
*/
DialogView.registerAnimator = function(name, animator) {
if (!(animator instanceof DialogAnimator)) {
throw new Error('"animator" param must be an instance of DialogAnimator');
}
this._animatorDict[name] = animator;
};
MicroEvent.mixin(DialogView);
return DialogView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('DialogAnimator', function() {
var DialogAnimator = Class.extend({
show: function(dialog, callback) {
callback();
},
hide: function(dialog, callback) {
callback();
}
});
return DialogAnimator;
});
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('FadePopoverAnimator', ['PopoverAnimator', function(PopoverAnimator) {
/**
* Fade animator for popover.
*/
var FadePopoverAnimator = PopoverAnimator.extend({
timing: 'cubic-bezier(.1, .7, .4, 1)',
duration: 0.2,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} popover
* @param {Function} callback
*/
show: function(popover, callback) {
var pop = popover._element[0].querySelector('.popover'),
mask = popover._element[0].querySelector('.popover-mask');
animit.runAll(
animit(mask)
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(pop)
.queue({
transform: 'scale3d(1.3, 1.3, 1.0)',
opacity: 0
})
.queue({
transform: 'scale3d(1.0, 1.0, 1.0)',
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} popover
* @param {Function} callback
*/
hide: function(popover, callback) {
var pop = popover._element[0].querySelector('.popover'),
mask = popover._element[0].querySelector('.popover-mask');
animit.runAll(
animit(mask)
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(pop)
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return FadePopoverAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('FadeTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) {
/**
* Fade-in screen transition.
*/
var FadeTransitionAnimator = NavigatorTransitionAnimator.extend({
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} callback
*/
push: function(enterPage, leavePage, callback) {
animit.runAll(
animit([enterPage.getPageView().getContentElement(), enterPage.getPageView().getBackgroundElement()])
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 0
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1
},
duration: 0.4,
timing: 'linear'
})
.resetStyle()
.queue(function(done) {
callback();
done();
}),
animit(enterPage.getPageView().getToolbarElement())
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 0
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1
},
duration: 0.4,
timing: 'linear'
})
.resetStyle()
);
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} done
*/
pop: function(enterPage, leavePage, callback) {
animit.runAll(
animit([leavePage.getPageView().getContentElement(), leavePage.getPageView().getBackgroundElement()])
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 0
},
duration: 0.4,
timing: 'linear'
})
.queue(function(done) {
callback();
done();
}),
animit(leavePage.getPageView().getToolbarElement())
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 0
},
duration: 0.4,
timing: 'linear'
})
);
}
});
return FadeTransitionAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('GenericView', ['$onsen', function($onsen) {
var GenericView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element;
this._scope = scope;
}
});
MicroEvent.mixin(GenericView);
return GenericView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('IOSAlertDialogAnimator', ['DialogAnimator', function(DialogAnimator) {
/**
* iOS style animator for alert dialog.
*/
var IOSAlertDialogAnimator = DialogAnimator.extend({
timing: 'cubic-bezier(.1, .7, .4, 1)',
duration: 0.2,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
show: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)',
opacity: 0.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)',
opacity: 1.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
hide: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
opacity: 1.0
},
duration: 0
})
.queue({
css: {
opacity: 0.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return IOSAlertDialogAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('IOSDialogAnimator', ['DialogAnimator', function(DialogAnimator) {
/**
* iOS style animator for dialog.
*/
var IOSDialogAnimator = DialogAnimator.extend({
timing: 'ease-in-out',
duration: 0.3,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
show: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, 300%, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0)'
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
hide: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3d(-50%, -50%, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-50%, 300%, 0)'
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return IOSDialogAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('IOSSlideTransitionAnimator', ['NavigatorTransitionAnimator', 'PageView', function(NavigatorTransitionAnimator, PageView) {
/**
* Slide animator for navigator transition like iOS's screen slide transition.
*/
var IOSSlideTransitionAnimator = NavigatorTransitionAnimator.extend({
/** Black mask */
backgroundMask : angular.element(
'<div style="position: absolute; width: 100%;' +
'height: 100%; background-color: black; opacity: 0;"></div>'
),
_decompose: function(page) {
var elements = [];
var left = page.getPageView().getToolbarLeftItemsElement();
var right = page.getPageView().getToolbarRightItemsElement();
var other = []
.concat(left.children.length === 0 ? left : excludeBackButtonLabel(left.children))
.concat(right.children.length === 0 ? right : excludeBackButtonLabel(right.children));
var pageLabels = [
page.getPageView().getToolbarCenterItemsElement(),
page.getPageView().getToolbarBackButtonLabelElement()
];
return {
pageLabels: pageLabels,
other: other,
content: page.getPageView().getContentElement(),
background: page.getPageView().getBackgroundElement(),
toolbar: page.getPageView().getToolbarElement(),
bottomToolbar: page.getPageView().getBottomToolbarElement()
};
function excludeBackButtonLabel(elements) {
var result = [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].nodeName.toLowerCase() === 'ons-back-button') {
result.push(elements[i].querySelector('.ons-back-button__icon'));
} else {
result.push(elements[i]);
}
}
return result;
}
},
_shouldAnimateToolbar: function(enterPage, leavePage) {
var bothPageHasToolbar =
enterPage.getPageView().hasToolbarElement() &&
leavePage.getPageView().hasToolbarElement();
var noAndroidLikeToolbar =
!angular.element(enterPage.getPageView().getToolbarElement()).hasClass('navigation-bar--android') &&
!angular.element(leavePage.getPageView().getToolbarElement()).hasClass('navigation-bar--android');
return bothPageHasToolbar && noAndroidLikeToolbar;
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} callback
*/
push: function(enterPage, leavePage, callback) {
var mask = this.backgroundMask.remove();
leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0].nextSibling);
var enterPageDecomposition = this._decompose(enterPage);
var leavePageDecomposition = this._decompose(leavePage);
var delta = (function() {
var rect = leavePage.element[0].getBoundingClientRect();
return Math.round(((rect.right - rect.left) / 2) * 0.6);
})();
var maskClear = animit(mask[0])
.queue({
opacity: 0,
transform: 'translate3d(0, 0, 0)'
})
.queue({
opacity: 0.1
}, {
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
.queue(function(done) {
mask.remove();
done();
});
var shouldAnimateToolbar = this._shouldAnimateToolbar(enterPage, leavePage);
if (shouldAnimateToolbar) {
enterPage.element.css({zIndex: 'auto'});
leavePage.element.css({zIndex: 'auto'});
animit.runAll(
maskClear,
animit([enterPageDecomposition.content, enterPageDecomposition.bottomToolbar, enterPageDecomposition.background])
.queue({
css: {
transform: 'translate3D(100%, 0px, 0px)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)',
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(enterPageDecomposition.toolbar)
.queue({
css: {
background: 'none',
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 0, 0, 0)'
},
duration: 0
})
.wait(0.3)
.resetStyle({
duration: 0.1,
transition:
'background-color 0.1s linear, ' +
'border-color 0.1s linear'
}),
animit(enterPageDecomposition.pageLabels)
.queue({
css: {
transform: 'translate3d(' + delta + 'px, 0, 0)',
opacity: 0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(enterPageDecomposition.other)
.queue({
css: {opacity: 0},
duration: 0
})
.queue({
css: {opacity: 1},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit([leavePageDecomposition.content, leavePageDecomposition.bottomToolbar, leavePageDecomposition.background])
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(-25%, 0px, 0px)',
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
.queue(function(done) {
enterPage.element.css({zIndex: ''});
leavePage.element.css({zIndex: ''});
callback();
done();
}),
animit(leavePageDecomposition.pageLabels)
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(-' + delta + 'px, 0, 0)',
opacity: 0,
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(leavePageDecomposition.other)
.queue({
css: {opacity: 1},
duration: 0
})
.queue({
css: {opacity: 0},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
);
} else {
animit.runAll(
maskClear,
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(100%, 0px, 0px)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)',
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0, 0, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(-25%, 0px, 0px)'
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} done
*/
pop: function(enterPage, leavePage, done) {
var mask = this.backgroundMask.remove();
enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0].nextSibling);
var enterPageDecomposition = this._decompose(enterPage);
var leavePageDecomposition = this._decompose(leavePage);
var delta = (function() {
var rect = leavePage.element[0].getBoundingClientRect();
return Math.round(((rect.right - rect.left) / 2) * 0.6);
})();
var maskClear = animit(mask[0])
.queue({
opacity: 0.1,
transform: 'translate3d(0, 0, 0)'
})
.queue({
opacity: 0
}, {
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
.queue(function(done) {
mask.remove();
done();
});
var shouldAnimateToolbar = this._shouldAnimateToolbar(enterPage, leavePage);
if (shouldAnimateToolbar) {
enterPage.element.css({zIndex: 'auto'});
leavePage.element.css({zIndex: 'auto'});
animit.runAll(
maskClear,
animit([enterPageDecomposition.content, enterPageDecomposition.bottomToolbar, enterPageDecomposition.background])
.queue({
css: {
transform: 'translate3D(-25%, 0px, 0px)',
opacity: 0.9
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(enterPageDecomposition.pageLabels)
.queue({
css: {
transform: 'translate3d(-' + delta + 'px, 0, 0)',
opacity: 0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(enterPageDecomposition.toolbar)
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(enterPageDecomposition.other)
.queue({
css: {opacity: 0},
duration: 0
})
.queue({
css: {opacity: 1},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit([leavePageDecomposition.content, leavePageDecomposition.bottomToolbar, leavePageDecomposition.background])
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(100%, 0px, 0px)'
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.wait(0)
.queue(function(finish) {
enterPage.element.css({zIndex: ''});
leavePage.element.css({zIndex: ''});
done();
finish();
}),
animit(leavePageDecomposition.other)
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 0,
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
}),
animit(leavePageDecomposition.toolbar)
.queue({
css: {
background: 'none',
backgroundColor: 'rgba(0, 0, 0, 0)',
borderColor: 'rgba(0, 0, 0, 0)'
},
duration: 0
}),
animit(leavePageDecomposition.pageLabels)
.queue({
css: {
transform: 'translate3d(0, 0, 0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3d(' + delta + 'px, 0, 0)',
opacity: 0,
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
);
} else {
animit.runAll(
maskClear,
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(-25%, 0px, 0px)',
opacity: 0.9
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle(),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(100%, 0px, 0px)'
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(finish) {
done();
finish();
})
);
}
}
});
return IOSSlideTransitionAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('LazyRepeatView', ['$onsen', '$document', '$compile', function($onsen, $document, $compile) {
var LazyRepeatView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs, linker) {
this._element = element;
this._scope = scope;
this._attrs = attrs;
this._linker = linker;
this._parentElement = element.parent();
this._pageContent = this._findPageContent();
if (!this._pageContent) {
throw new Error('ons-lazy-repeat must be a descendant of an <ons-page> object.');
}
this._itemHeightSum = [];
this._maxIndex = 0;
this._delegate = this._getDelegate();
this._renderedElements = {};
this._addEventListeners();
this._scope.$watch(this._countItems.bind(this), this._onChange.bind(this));
this._scope.$on('$destroy', this._destroy.bind(this));
this._onChange();
},
_getDelegate: function() {
var delegate = this._scope.$eval(this._attrs.onsLazyRepeat);
if (typeof delegate === 'undefined') {
/*jshint evil:true */
delegate = eval(this._attrs.onsLazyRepeat);
}
return delegate;
},
_countItems: function() {
return this._delegate.countItems();
},
_getItemHeight: function(i) {
return this._delegate.calculateItemHeight(i);
},
_getTopOffset: function() {
return this._parentElement[0].getBoundingClientRect().top;
},
_render: function() {
var items = this._getItemsInView(),
keep = {};
this._parentElement.css('height', this._itemHeightSum[this._maxIndex] + 'px');
for (var i = 0, l = items.length; i < l; i ++) {
var _item = items[i];
this._renderElement(_item);
keep[_item.index] = true;
}
for (var key in this._renderedElements) {
if (this._renderedElements.hasOwnProperty(key) && !keep.hasOwnProperty(key)) {
this._removeElement(key);
}
}
},
_isRendered: function(i) {
return this._renderedElements.hasOwnProperty(i);
},
_renderElement: function(item) {
if (this._isRendered(item.index)) {
// Update content even if it's already added to DOM
// to account for changes within the list.
var currentItem = this._renderedElements[item.index];
if (this._delegate.configureItemScope) {
this._delegate.configureItemScope(item.index, currentItem.scope);
}
// Fix position.
var element = this._renderedElements[item.index].element;
element[0].style.top = item.top + 'px';
return;
}
var childScope = this._scope.$new();
this._addSpecialProperties(item.index, childScope);
this._linker(childScope, function(clone) {
if (this._delegate.configureItemScope) {
this._delegate.configureItemScope(item.index, childScope);
}
else if (this._delegate.createItemContent) {
clone.append(this._delegate.createItemContent(item.index));
$compile(clone[0].firstChild)(childScope);
}
this._parentElement.append(clone);
clone.css({
position: 'absolute',
top: item.top + 'px',
left: '0px',
right: '0px',
display: 'none'
});
var element = {
element: clone,
scope: childScope
};
// Don't show elements before they are finished rendering.
this._scope.$evalAsync(function() {
clone.css('display', 'block');
});
this._renderedElements[item.index] = element;
}.bind(this));
},
_removeElement: function(i) {
if (!this._isRendered(i)) {
return;
}
var element = this._renderedElements[i];
if (this._delegate.destroyItemScope) {
this._delegate.destroyItemScope(i, element.scope);
}
else if (this._delegate.destroyItemContent) {
this._delegate.destroyItemContent(i, element.element.children()[0]);
}
element.element.remove();
element.scope.$destroy();
element.element = element.scope = null;
delete this._renderedElements[i];
},
_removeAllElements: function() {
for (var key in this._renderedElements) {
if (this._removeElement.hasOwnProperty(key)) {
this._removeElement(key);
}
}
},
_calculateStartIndex: function(current) {
var start = 0,
end = this._maxIndex;
// Binary search for index at top of screen so
// we can speed up rendering.
while (true) {
var middle = Math.floor((start + end) / 2),
value = current + this._itemHeightSum[middle];
if (end < start) {
return 0;
}
else if (value >= 0 && value - this._getItemHeight(middle) < 0) {
return middle;
}
else if (isNaN(value) || value >= 0) {
end = middle - 1;
}
else {
start = middle + 1;
}
}
},
_recalculateItemHeightSum: function() {
var sums = this._itemHeightSum;
for (var i = 0, sum = 0; i < Math.min(sums.length, this._countItems()); i++) {
sum += this._getItemHeight(i);
sums[i] = sum;
}
},
_getItemsInView: function() {
var topOffset = this._getTopOffset(),
topPosition = topOffset,
cnt = this._countItems();
if (cnt !== this._itemCount){
this._recalculateItemHeightSum();
this._maxIndex = cnt - 1;
}
this._itemCount = cnt;
var startIndex = this._calculateStartIndex(topPosition);
startIndex = Math.max(startIndex - 30, 0);
if (startIndex > 0) {
topPosition += this._itemHeightSum[startIndex - 1];
}
var items = [];
for (var i = startIndex; i < cnt && topPosition < 4 * window.innerHeight; i++) {
var h = this._getItemHeight(i);
if (i >= this._itemHeightSum.length) {
this._itemHeightSum = this._itemHeightSum.concat(new Array(100));
}
if (i > 0) {
this._itemHeightSum[i] = this._itemHeightSum[i - 1] + h;
}
else {
this._itemHeightSum[i] = h;
}
this._maxIndex = Math.max(i, this._maxIndex);
items.push({
index: i,
top: topPosition - topOffset
});
topPosition += h;
}
return items;
},
_addSpecialProperties: function(i, scope) {
scope.$index = i;
scope.$first = i === 0;
scope.$last = i === this._countItems() - 1;
scope.$middle = !scope.$first && !scope.$last;
scope.$even = i % 2 === 0;
scope.$odd = !scope.$even;
},
_onChange: function() {
this._render();
},
_findPageContent: function() {
var e = this._element[0];
while(e.parentNode) {
e = e.parentNode;
if (e.className) {
if (e.className.split(/\s+/).indexOf('page__content') >= 0) {
break;
}
}
}
return e;
},
_debounce: function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
},
_doubleFireOnTouchend: function(){
this._render();
this._debounce(this._render.bind(this), 100);
},
_addEventListeners: function() {
if (ons.platform.isIOS()) {
this._boundOnChange = this._debounce(this._onChange.bind(this), 30);
} else {
this._boundOnChange = this._onChange.bind(this);
}
this._pageContent.addEventListener('scroll', this._boundOnChange, true);
if (ons.platform.isIOS()) {
this._pageContent.addEventListener('touchmove', this._boundOnChange, true);
this._pageContent.addEventListener('touchend', this._doubleFireOnTouchend, true);
}
$document[0].addEventListener('resize', this._boundOnChange, true);
},
_removeEventListeners: function() {
this._pageContent.removeEventListener('scroll', this._boundOnChange, true);
if (ons.platform.isIOS()) {
this._pageContent.removeEventListener('touchmove', this._boundOnChange, true);
this._pageContent.removeEventListener('touchend', this._doubleFireOnTouchend, true);
}
$document[0].removeEventListener('resize', this._boundOnChange, true);
},
_destroy: function() {
this._removeEventListeners();
this._removeAllElements();
this._parentElement = this._renderedElements = this._element = this._scope = this._attrs = null;
}
});
return LazyRepeatView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('LiftTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) {
/**
* Lift screen transition.
*/
var LiftTransitionAnimator = NavigatorTransitionAnimator.extend({
/** Black mask */
backgroundMask : angular.element(
'<div style="position: absolute; width: 100%;' +
'height: 100%; background-color: black;"></div>'
),
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} callback
*/
push: function(enterPage, leavePage, callback) {
var mask = this.backgroundMask.remove();
leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0]);
var maskClear = animit(mask[0])
.wait(0.6)
.queue(function(done) {
mask.remove();
done();
});
animit.runAll(
maskClear,
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(0, 100%, 0)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.wait(0.2)
.resetStyle()
.queue(function(done) {
callback();
done();
}),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1.0
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, -10%, 0)',
opacity: 0.9
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
);
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} callback
*/
pop: function(enterPage, leavePage, callback) {
var mask = this.backgroundMask.remove();
enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0]);
animit.runAll(
animit(mask[0])
.wait(0.4)
.queue(function(done) {
mask.remove();
done();
}),
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(0, -10%, 0)',
opacity: 0.9
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
opacity: 1.0
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.resetStyle()
.wait(0.4)
.queue(function(done) {
callback();
done();
}),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0, 0, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 100%, 0)'
},
duration: 0.4,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
);
}
});
return LiftTransitionAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('ModalView', ['$onsen', '$rootScope', function($onsen, $rootScope) {
var ModalView = Class.extend({
_element: undefined,
_scope: undefined,
/**
* @param {Object} scope
* @param {jqLite} element
*/
init: function(scope, element) {
this._scope = scope;
this._element = element;
var pageView = $rootScope.ons.findParentComponentUntil('ons-page', this._element);
if (pageView) {
this._pageContent = angular.element(pageView._element[0].querySelector('.page__content'));
}
this._scope.$on('$destroy', this._destroy.bind(this));
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
this.hide();
},
getDeviceBackButtonHandler: function() {
return this._deviceBackButtonHandler;
},
/**
* Show modal view.
*/
show: function() {
this._element.css('display', 'table');
},
_isVisible: function() {
return this._element[0].clientWidth > 0;
},
_onDeviceBackButton: function() {
// Do nothing and stop device-backbutton handler chain.
return;
},
/**
* Hide modal view.
*/
hide: function() {
this._element.css('display', 'none');
},
/**
* Toggle modal view visibility.
*/
toggle: function() {
if (this._isVisible()) {
return this.hide.apply(this, arguments);
} else {
return this.show.apply(this, arguments);
}
},
_destroy: function() {
this.emit('destroy', {page: this});
this._deviceBackButtonHandler.destroy();
this._element = this._scope = null;
}
});
MicroEvent.mixin(ModalView);
return ModalView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
var NavigatorPageObject = Class.extend({
/**
* @param {Object} params
* @param {Object} params.page
* @param {Object} params.element
* @param {Object} params.pageScope
* @param {Object} params.options
* @param {Object} params.navigator
*/
init: function(params) {
this.page = params.page;
this.name = params.page;
this.element = params.element;
this.pageScope = params.pageScope;
this.options = params.options;
this.navigator = params.navigator;
// Block events while page is being animated to stop scrolling, pressing buttons, etc.
this._blockEvents = function(event) {
if (this.navigator._isPopping || this.navigator._isPushing) {
event.preventDefault();
event.stopPropagation();
}
}.bind(this);
this.element.on(this._pointerEvents, this._blockEvents);
},
_pointerEvents: 'touchmove',
/**
* @return {PageView}
*/
getPageView: function() {
if (!this._pageView) {
this._pageView = this.element.inheritedData('ons-page');
if (!this._pageView) {
throw new Error('Fail to fetch PageView from ons-page element.');
}
}
return this._pageView;
},
destroy: function() {
this.pageScope.$destroy();
this.element.off(this._pointerEvents, this._blockEvents);
this.element.remove();
this.element = null;
this._pageView = null;
this.pageScope = null;
this.options = null;
var index = this.navigator.pages.indexOf(this);
if (index !== -1) {
this.navigator.pages.splice(index, 1);
}
this.navigator = null;
}
});
module.factory('NavigatorView', ['$http', '$parse', '$templateCache', '$compile', '$onsen', '$timeout', 'SimpleSlideTransitionAnimator', 'NavigatorTransitionAnimator', 'LiftTransitionAnimator', 'NullTransitionAnimator', 'IOSSlideTransitionAnimator', 'FadeTransitionAnimator', function($http, $parse, $templateCache, $compile, $onsen, $timeout,
SimpleSlideTransitionAnimator, NavigatorTransitionAnimator, LiftTransitionAnimator,
NullTransitionAnimator, IOSSlideTransitionAnimator, FadeTransitionAnimator) {
/**
* Manages the page navigation backed by page stack.
*
* @class NavigatorView
*/
var NavigatorView = Class.extend({
/**
* @member {jqLite} Object
*/
_element: undefined,
/**
* @member {Object} Object
*/
_attrs: undefined,
/**
* @member {Array}
*/
pages: undefined,
/**
* @member {Object}
*/
_scope: undefined,
/**
* @member {DoorLock}
*/
_doorLock: undefined,
/**
* @member {Boolean}
*/
_profiling: false,
/**
* @param {Object} scope
* @param {jqLite} element jqLite Object to manage with navigator
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element || angular.element(window.document.body);
this._scope = scope || this._element.scope();
this._attrs = attrs;
this._doorLock = new DoorLock();
this.pages = [];
this._isPopping = this._isPushing = false;
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
this._scope.$on('$destroy', this._destroy.bind(this));
},
_destroy: function() {
this.emit('destroy');
this.pages.forEach(function(page) {
page.destroy();
});
this._deviceBackButtonHandler.destroy();
this._deviceBackButtonHandler = null;
this._element = this._scope = this._attrs = null;
},
_onDeviceBackButton: function(event) {
if (this.pages.length > 1) {
this._scope.$evalAsync(this.popPage.bind(this));
} else {
event.callParentHandler();
}
},
/**
* @param element jqLite Object
* @return jqLite Object
*/
_normalizePageElement: function(element) {
for (var i = 0; i < element.length; i++) {
if (element[i].nodeType === 1) {
return angular.element(element[i]);
}
}
throw new Error('invalid state');
},
_createPageElementAndLinkFunction : function(templateHTML, pageScope, done) {
var div = document.createElement('div');
div.innerHTML = templateHTML.trim();
var pageElement = angular.element(div);
var hasPage = div.childElementCount === 1 &&
div.childNodes[0].nodeName.toLowerCase() === 'ons-page';
if (hasPage) {
pageElement = angular.element(div.childNodes[0]);
} else {
throw new Error('You can not supply no "ons-page" element to "ons-navigator".');
}
var link = $compile(pageElement);
return {
element: pageElement,
link: function() {
link(pageScope);
safeApply(pageScope);
}
};
function safeApply(scope) {
var phase = scope.$root.$$phase;
if (phase !== '$apply' && phase !== '$digest') {
scope.$apply();
}
}
},
/**
* Insert page object that has the specified pageUrl into the page stack and
* if options object is specified, apply the options.
*
* @param {Number} index
* @param {String} page
* @param {Object} [options]
* @param {String/NavigatorTransitionAnimator} [options.animation]
*/
insertPage: function(index, page, options) {
options = options || {};
if (options && typeof options != 'object') {
throw new Error('options must be an object. You supplied ' + options);
}
if (index === this.pages.length) {
return this.pushPage.apply(this, [].slice.call(arguments, 1));
}
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock();
$onsen.getPageHTMLAsync(page).then(function(templateHTML) {
var pageScope = this._createPageScope();
var object = this._createPageElementAndLinkFunction(templateHTML, pageScope);
var element = object.element;
var link = object.link;
element = this._normalizePageElement(element);
var pageObject = this._createPageObject(page, element, pageScope, options);
if (this.pages.length > 0) {
index = normalizeIndex(index);
this._element[0].insertBefore(element[0], this.pages[index] ? this.pages[index].element[0] : null);
this.pages.splice(index, 0, pageObject);
link();
setTimeout(function() {
if (this.getCurrentPage() !== pageObject) {
element.css('display', 'none');
}
unlock();
element = null;
}.bind(this), 1000 / 60);
} else {
this._element.append(element);
this.pages.push(pageObject);
link();
unlock();
element = null;
}
}.bind(this), function() {
unlock();
throw new Error('Page is not found: ' + page);
});
}.bind(this));
var normalizeIndex = function(index) {
if (index < 0) {
index = this.pages.length + index;
}
return index;
}.bind(this);
},
/**
* Pushes the specified pageUrl into the page stack and
* if options object is specified, apply the options.
*
* @param {String} page
* @param {Object} [options]
* @param {String/NavigatorTransitionAnimator} [options.animation]
* @param {Function} [options.onTransitionEnd]
*/
pushPage: function(page, options) {
if (this._profiling) {
console.time('pushPage');
}
options = options || {};
if (options.cancelIfRunning && this._isPushing) {
return;
}
if (options && typeof options != 'object') {
throw new Error('options must be an object. You supplied ' + options);
}
if (this._emitPrePushEvent()) {
return;
}
this._doorLock.waitUnlock(function() {
this._pushPage(page, options);
}.bind(this));
},
_pushPage: function(page, options) {
var unlock = this._doorLock.lock();
var done = function() {
unlock();
if (this._profiling) {
console.timeEnd('pushPage');
}
};
$onsen.getPageHTMLAsync(page).then(function(templateHTML) {
var pageScope = this._createPageScope();
var object = this._createPageElementAndLinkFunction(templateHTML, pageScope);
setImmediate(function() {
this._pushPageDOM(page, object.element, object.link, pageScope, options, done);
object = null;
}.bind(this));
}.bind(this), function() {
done();
throw new Error('Page is not found: ' + page);
}.bind(this));
},
getDeviceBackButtonHandler: function() {
return this._deviceBackButtonHandler;
},
/**
* @param {Object} options pushPage()'s options parameter
* @param {NavigatorTransitionAnimator} [defaultAnimator]
*/
_getAnimatorOption: function(options, defaultAnimator) {
var animator = null;
if (options.animation instanceof NavigatorTransitionAnimator) {
return options.animation;
}
if (typeof options.animation === 'string') {
animator = NavigatorView._transitionAnimatorDict[options.animation];
}
if (!animator && this._element.attr('animation')) {
animator = NavigatorView._transitionAnimatorDict[this._element.attr('animation')];
}
if (!animator) {
animator = defaultAnimator || NavigatorView._transitionAnimatorDict['default'];
}
if (!(animator instanceof NavigatorTransitionAnimator)) {
throw new Error('"animator" is not an instance of NavigatorTransitionAnimator.');
}
return animator;
},
_createPageScope: function() {
return this._scope.$new();
},
/**
* @param {String} page
* @param {jqLite} element
* @param {Object} pageScope
* @param {Object} options
*/
_createPageObject: function(page, element, pageScope, options) {
options.animator = this._getAnimatorOption(options);
return new NavigatorPageObject({
page: page,
element: element,
pageScope: pageScope,
options: options,
navigator: this
});
},
/**
* @param {String} page Page name.
* @param {Object} element
* @param {Function} link
* @param {Object} pageScope
* @param {Object} options
* @param {Function} [unlock]
*/
_pushPageDOM: function(page, element, link, pageScope, options, unlock) {
if (this._profiling) {
console.time('pushPageDOM');
}
unlock = unlock || function() {};
options = options || {};
element = this._normalizePageElement(element);
var pageObject = this._createPageObject(page, element, pageScope, options);
var event = {
enterPage: pageObject,
leavePage: this.pages[this.pages.length - 1],
navigator: this
};
this.pages.push(pageObject);
var done = function() {
if (this.pages[this.pages.length - 2]) {
this.pages[this.pages.length - 2].element.css('display', 'none');
}
if (this._profiling) {
console.timeEnd('pushPageDOM');
}
this._isPushing = false;
unlock();
this.emit('postpush', event);
if (typeof options.onTransitionEnd === 'function') {
options.onTransitionEnd();
}
element = null;
}.bind(this);
this._isPushing = true;
if (this.pages.length > 1) {
var leavePage = this.pages.slice(-2)[0];
var enterPage = this.pages.slice(-1)[0];
this._element.append(element);
link();
options.animator.push(enterPage, leavePage, done);
element = null;
} else {
this._element.append(element);
link();
done();
element = null;
}
},
/**
* @return {Boolean} Whether if event is canceled.
*/
_emitPrePushEvent: function() {
var isCanceled = false;
var prePushEvent = {
navigator: this,
currentPage: this.getCurrentPage(),
cancel: function() {
isCanceled = true;
}
};
this.emit('prepush', prePushEvent);
return isCanceled;
},
/**
* @return {Boolean} Whether if event is canceled.
*/
_emitPrePopEvent: function() {
var isCanceled = false;
var leavePage = this.getCurrentPage();
var prePopEvent = {
navigator: this,
currentPage: leavePage,
leavePage: leavePage,
enterPage: this.pages[this.pages.length - 2],
cancel: function() {
isCanceled = true;
}
};
this.emit('prepop', prePopEvent);
return isCanceled;
},
/**
* Pops current page from the page stack.
* @param {Object} [options]
* @param {Function} [options.onTransitionEnd]
*/
popPage: function(options) {
options = options || {};
if (options.cancelIfRunning && this._isPopping) {
return;
}
this._doorLock.waitUnlock(function() {
if (this.pages.length <= 1) {
throw new Error('NavigatorView\'s page stack is empty.');
}
if (this._emitPrePopEvent()) {
return;
}
this._popPage(options);
}.bind(this));
},
_popPage: function(options) {
var unlock = this._doorLock.lock();
var leavePage = this.pages.pop();
if (this.pages[this.pages.length - 1]) {
this.pages[this.pages.length - 1].element.css('display', 'block');
}
var enterPage = this.pages[this.pages.length -1];
var event = {
leavePage: leavePage,
enterPage: this.pages[this.pages.length - 1],
navigator: this
};
var callback = function() {
leavePage.destroy();
this._isPopping = false;
unlock();
this.emit('postpop', event);
event.leavePage = null;
if (typeof options.onTransitionEnd === 'function') {
options.onTransitionEnd();
}
}.bind(this);
this._isPopping = true;
var animator = this._getAnimatorOption(options, leavePage.options.animator);
animator.pop(enterPage, leavePage, callback);
},
/**
* Replaces the current page with the specified one.
*
* @param {String} page
* @param {Object} [options]
*/
replacePage: function(page, options) {
options = options || {};
var onTransitionEnd = options.onTransitionEnd || function() {};
options.onTransitionEnd = function() {
if (this.pages.length > 1) {
this.pages[this.pages.length - 2].destroy();
}
onTransitionEnd();
}.bind(this);
this.pushPage(page, options);
},
/**
* Clears page stack and add the specified pageUrl to the page stack.
* If options object is specified, apply the options.
* the options object include all the attributes of this navigator.
*
* @param {String} page
* @param {Object} [options]
*/
resetToPage: function(page, options) {
options = options || {};
if (!options.animator && !options.animation) {
options.animation = 'none';
}
var onTransitionEnd = options.onTransitionEnd || function() {};
var self = this;
options.onTransitionEnd = function() {
while (self.pages.length > 1) {
self.pages.shift().destroy();
}
onTransitionEnd();
};
this.pushPage(page, options);
},
/**
* Get current page's navigator item.
*
* Use this method to access options passed by pushPage() or resetToPage() method.
* eg. ons.navigator.getCurrentPage().options
*
* @return {Object}
*/
getCurrentPage: function() {
return this.pages[this.pages.length - 1];
},
/**
* Retrieve the entire page stages of the navigator.
*
* @return {Array}
*/
getPages: function() {
return this.pages;
},
/**
* @return {Boolean}
*/
canPopPage: function() {
return this.pages.length > 1;
}
});
// Preset transition animators.
NavigatorView._transitionAnimatorDict = {
'default': $onsen.isAndroid() ? new SimpleSlideTransitionAnimator() : new IOSSlideTransitionAnimator(),
'slide': $onsen.isAndroid() ? new SimpleSlideTransitionAnimator() : new IOSSlideTransitionAnimator(),
'simpleslide': new SimpleSlideTransitionAnimator(),
'lift': new LiftTransitionAnimator(),
'fade': new FadeTransitionAnimator(),
'none': new NullTransitionAnimator()
};
/**
* @param {String} name
* @param {NavigatorTransitionAnimator} animator
*/
NavigatorView.registerTransitionAnimator = function(name, animator) {
if (!(animator instanceof NavigatorTransitionAnimator)) {
throw new Error('"animator" param must be an instance of NavigatorTransitionAnimator');
}
this._transitionAnimatorDict[name] = animator;
};
MicroEvent.mixin(NavigatorView);
return NavigatorView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('NavigatorTransitionAnimator', function() {
var NavigatorTransitionAnimator = Class.extend({
push: function(enterPage, leavePage, callback) {
callback();
},
pop: function(enterPage, leavePage, callback) {
callback();
}
});
return NavigatorTransitionAnimator;
});
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
/**
* Null animator do screen transition with no animations.
*/
module.factory('NullTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) {
var NullTransitionAnimator = NavigatorTransitionAnimator.extend({});
return NullTransitionAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('OverlaySlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) {
var OverlaySlidingMenuAnimator = SlidingMenuAnimator.extend({
_blackMask: undefined,
_isRight: false,
_element: false,
_menuPage: false,
_mainPage: false,
_width: false,
_duration: false,
/**
* @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element
* @param {jqLite} mainPage
* @param {jqLite} menuPage
* @param {Object} options
* @param {String} options.width "width" style value
* @param {Boolean} options.isRight
*/
setup: function(element, mainPage, menuPage, options) {
options = options || {};
this._width = options.width || '90%';
this._isRight = !!options.isRight;
this._element = element;
this._mainPage = mainPage;
this._menuPage = menuPage;
this._duration = 0.4;
menuPage.css('box-shadow', '0px 0 10px 0px rgba(0, 0, 0, 0.2)');
menuPage.css({
width: options.width,
display: 'none',
zIndex: 2
});
// Fix for transparent menu page on iOS8.
menuPage.css('-webkit-transform', 'translate3d(0px, 0px, 0px)');
mainPage.css({zIndex: 1});
if (this._isRight) {
menuPage.css({
right: '-' + options.width,
left: 'auto'
});
} else {
menuPage.css({
right: 'auto',
left: '-' + options.width
});
}
this._blackMask = angular.element('<div></div>').css({
backgroundColor: 'black',
top: '0px',
left: '0px',
right: '0px',
bottom: '0px',
position: 'absolute',
display: 'none',
zIndex: 0
});
element.prepend(this._blackMask);
},
/**
* @param {Object} options
* @param {String} options.width
*/
onResized: function(options) {
this._menuPage.css('width', options.width);
if (this._isRight) {
this._menuPage.css({
right: '-' + options.width,
left: 'auto'
});
} else {
this._menuPage.css({
right: 'auto',
left: '-' + options.width
});
}
if (options.isOpened) {
var max = this._menuPage[0].clientWidth;
var menuStyle = this._generateMenuPageStyle(max);
animit(this._menuPage[0]).queue(menuStyle).play();
}
},
/**
*/
destroy: function() {
if (this._blackMask) {
this._blackMask.remove();
this._blackMask = null;
}
this._mainPage.removeAttr('style');
this._menuPage.removeAttr('style');
this._element = this._mainPage = this._menuPage = null;
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
openMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
this._menuPage.css('display', 'block');
this._blackMask.css('display', 'block');
var max = this._menuPage[0].clientWidth;
var menuStyle = this._generateMenuPageStyle(max);
var mainPageStyle = this._generateMainPageStyle(max);
setTimeout(function() {
animit(this._mainPage[0])
.queue(mainPageStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
callback();
done();
})
.play();
animit(this._menuPage[0])
.queue(menuStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
closeMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
this._blackMask.css({display: 'block'});
var menuPageStyle = this._generateMenuPageStyle(0);
var mainPageStyle = this._generateMainPageStyle(0);
setTimeout(function() {
animit(this._mainPage[0])
.queue(mainPageStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
this._menuPage.css('display', 'none');
callback();
done();
}.bind(this))
.play();
animit(this._menuPage[0])
.queue(menuPageStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Object} options
* @param {Number} options.distance
* @param {Number} options.maxDistance
*/
translateMenu: function(options) {
this._menuPage.css('display', 'block');
this._blackMask.css({display: 'block'});
var menuPageStyle = this._generateMenuPageStyle(Math.min(options.maxDistance, options.distance));
var mainPageStyle = this._generateMainPageStyle(Math.min(options.maxDistance, options.distance));
delete mainPageStyle.opacity;
animit(this._menuPage[0])
.queue(menuPageStyle)
.play();
if (Object.keys(mainPageStyle).length > 0) {
animit(this._mainPage[0])
.queue(mainPageStyle)
.play();
}
},
_generateMenuPageStyle: function(distance) {
var max = this._menuPage[0].clientWidth;
var x = this._isRight ? -distance : distance;
var transform = 'translate3d(' + x + 'px, 0, 0)';
return {
transform: transform,
'box-shadow': distance === 0 ? 'none' : '0px 0 10px 0px rgba(0, 0, 0, 0.2)'
};
},
_generateMainPageStyle: function(distance) {
var max = this._menuPage[0].clientWidth;
var opacity = 1 - (0.1 * distance / max);
return {
opacity: opacity
};
},
copy: function() {
return new OverlaySlidingMenuAnimator();
}
});
return OverlaySlidingMenuAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('PageView', ['$onsen', '$parse', function($onsen, $parse) {
var PageView = Class.extend({
_registeredToolbarElement : false,
_registeredBottomToolbarElement : false,
_nullElement : window.document.createElement('div'),
_toolbarElement : null,
_bottomToolbarElement : null,
init: function(scope, element, attrs) {
this._scope = scope;
this._element = element;
this._attrs = attrs;
this._registeredToolbarElement = false;
this._registeredBottomToolbarElement = false;
this._nullElement = window.document.createElement('div');
this._toolbarElement = angular.element(this._nullElement);
this._bottomToolbarElement = angular.element(this._nullElement);
this._clearListener = scope.$on('$destroy', this._destroy.bind(this));
this._userDeviceBackButtonListener = angular.noop;
if (this._attrs.ngDeviceBackbutton || this._attrs.onDeviceBackbutton) {
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
}
},
_onDeviceBackButton: function($event) {
this._userDeviceBackButtonListener($event);
// ng-device-backbutton
if (this._attrs.ngDeviceBackbutton) {
$parse(this._attrs.ngDeviceBackbutton)(this._scope, {$event: $event});
}
// on-device-backbutton
/* jshint ignore:start */
if (this._attrs.onDeviceBackbutton) {
var lastEvent = window.$event;
window.$event = $event;
new Function(this._attrs.onDeviceBackbutton)();
window.$event = lastEvent;
}
/* jshint ignore:end */
},
/**
* @param {Function} callback
*/
setDeviceBackButtonHandler: function(callback) {
if (!this._deviceBackButtonHandler) {
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
}
this._userDeviceBackButtonListener = callback;
},
/**
* @return {Object/null}
*/
getDeviceBackButtonHandler: function() {
return this._deviceBackButtonHandler || null;
},
/**
* Register toolbar element to this page.
*
* @param {jqLite} element
*/
registerToolbar: function(element) {
if (this._registeredToolbarElement) {
throw new Error('This page\'s toolbar is already registered.');
}
angular.element(this.getContentElement()).attr('no-status-bar-fill', '');
element.remove();
var statusFill = this._element[0].querySelector('.page__status-bar-fill');
if (statusFill) {
angular.element(statusFill).after(element);
} else {
this._element.prepend(element);
}
this._toolbarElement = element;
this._registeredToolbarElement = true;
},
/**
* Register toolbar element to this page.
*
* @param {jqLite} element
*/
registerBottomToolbar: function(element) {
if (this._registeredBottomToolbarElement) {
throw new Error('This page\'s bottom-toolbar is already registered.');
}
element.remove();
this._bottomToolbarElement = element;
this._registeredBottomToolbarElement = true;
var fill = angular.element(document.createElement('div'));
fill.addClass('page__bottom-bar-fill');
fill.css({width: '0px', height: '0px'});
this._element.prepend(fill);
this._element.append(element);
},
/**
* @param {jqLite} element
*/
registerExtraElement: function(element) {
if (!this._extraElement) {
this._extraElement = angular.element('<div></div>');
this._extraElement.addClass('page__extra');
this._extraElement.css({
'z-index': '10001'
});
this._element.append(this._extraElement);
}
this._extraElement.append(element.remove());
},
/**
* @return {Boolean}
*/
hasToolbarElement : function() {
return !!this._registeredToolbarElement;
},
/**
* @return {Boolean}
*/
hasBottomToolbarElement : function() {
return !!this._registeredBottomToolbarElement;
},
/**
* @return {HTMLElement}
*/
getContentElement : function() {
for (var i = 0; i < this._element.length; i++) {
if (this._element[i].querySelector) {
var content = this._element[i].querySelector('.page__content');
if (content) {
return content;
}
}
}
throw Error('fail to get ".page__content" element.');
},
/**
* @return {HTMLElement}
*/
getBackgroundElement : function() {
for (var i = 0; i < this._element.length; i++) {
if (this._element[i].querySelector) {
var content = this._element[i].querySelector('.page__background');
if (content) {
return content;
}
}
}
throw Error('fail to get ".page__background" element.');
},
/**
* @return {HTMLElement}
*/
getToolbarElement : function() {
return this._toolbarElement[0] || this._nullElement;
},
/**
* @return {HTMLElement}
*/
getBottomToolbarElement : function() {
return this._bottomToolbarElement[0] || this._nullElement;
},
/**
* @return {HTMLElement}
*/
getToolbarLeftItemsElement : function() {
return this._toolbarElement[0].querySelector('.left') || this._nullElement;
},
/**
* @return {HTMLElement}
*/
getToolbarCenterItemsElement : function() {
return this._toolbarElement[0].querySelector('.center') || this._nullElement;
},
/**
* @return {HTMLElement}
*/
getToolbarRightItemsElement : function() {
return this._toolbarElement[0].querySelector('.right') || this._nullElement;
},
/**
* @return {HTMLElement}
*/
getToolbarBackButtonLabelElement : function() {
return this._toolbarElement[0].querySelector('ons-back-button .back-button__label') || this._nullElement;
},
_destroy: function() {
this.emit('destroy', {page: this});
if (this._deviceBackButtonHandler) {
this._deviceBackButtonHandler.destroy();
this._deviceBackButtonHandler = null;
}
this._element = null;
this._toolbarElement = null;
this._nullElement = null;
this._bottomToolbarElement = null;
this._extraElement = null;
this._scope = null;
this._clearListener();
}
});
MicroEvent.mixin(PageView);
return PageView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('PopoverView', ['$onsen', 'PopoverAnimator', 'FadePopoverAnimator', function($onsen, PopoverAnimator, FadePopoverAnimator) {
var PopoverView = Class.extend({
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element;
this._scope = scope;
this._attrs = attrs;
this._mask = angular.element(this._element[0].querySelector('.popover-mask'));
this._popover = angular.element(this._element[0].querySelector('.popover'));
this._mask.css('z-index', 20000);
this._popover.css('z-index', 20001);
this._element.css('display', 'none');
if (attrs.maskColor) {
this._mask.css('background-color', attrs.maskColor);
}
this._mask.on('click', this._cancel.bind(this));
this._visible = false;
this._doorLock = new DoorLock();
this._animation = PopoverView._animatorDict[typeof attrs.animation !== 'undefined' ?
attrs.animation : 'fade'];
if (!this._animation) {
throw new Error('No such animation: ' + attrs.animation);
}
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
this._onChange = function() {
setImmediate(function() {
if (this._currentTarget) {
this._positionPopover(this._currentTarget);
}
}.bind(this));
}.bind(this);
this._popover[0].addEventListener('DOMNodeInserted', this._onChange, false);
this._popover[0].addEventListener('DOMNodeRemoved', this._onChange, false);
window.addEventListener('resize', this._onChange, false);
this._scope.$on('$destroy', this._destroy.bind(this));
},
_onDeviceBackButton: function(event) {
if (this.isCancelable()) {
this._cancel.bind(this)();
} else {
event.callParentHandler();
}
},
_setDirection: function(direction) {
if (direction === 'up') {
this._scope.direction = direction;
this._scope.arrowPosition = 'bottom';
} else if (direction === 'left') {
this._scope.direction = direction;
this._scope.arrowPosition = 'right';
} else if (direction === 'down') {
this._scope.direction = direction;
this._scope.arrowPosition = 'top';
} else if (direction == 'right') {
this._scope.direction = direction;
this._scope.arrowPosition = 'left';
} else {
throw new Error('Invalid direction.');
}
if (!this._scope.$$phase) {
this._scope.$apply();
}
},
_positionPopoverByDirection: function(target, direction) {
var el = angular.element(this._element[0].querySelector('.popover')),
pos = target.getBoundingClientRect(),
own = el[0].getBoundingClientRect(),
arrow = angular.element(el.children()[1]),
offset = 14,
margin = 6,
radius = parseInt(window.getComputedStyle(el[0].querySelector('.popover__content')).borderRadius);
arrow.css({
top: '',
left: ''
});
// This is the difference between the side and the hypothenuse of the arrow.
var diff = (function(x) {
return (x / 2) * Math.sqrt(2) - x / 2;
})(parseInt(window.getComputedStyle(arrow[0]).width));
// This is the limit for the arrow. If it's moved further than this it's outside the popover.
var limit = margin + radius + diff;
this._setDirection(direction);
// Position popover next to the target.
if (['left', 'right'].indexOf(direction) > -1) {
if (direction == 'left') {
el.css('left', (pos.right - pos.width - own.width - offset) + 'px');
} else {
el.css('left', (pos.right + offset) + 'px');
}
el.css('top', (pos.bottom - pos.height / 2 - own.height / 2) + 'px');
} else {
if (direction == 'up') {
el.css('top', (pos.bottom - pos.height - own.height - offset) + 'px');
} else {
el.css('top', (pos.bottom + offset) + 'px');
}
el.css('left', (pos.right - pos.width / 2 - own.width / 2) + 'px');
}
own = el[0].getBoundingClientRect();
// Keep popover inside window and arrow inside popover.
if (['left', 'right'].indexOf(direction) > -1) {
if (own.top < margin) {
arrow.css('top', Math.max(own.height / 2 + own.top - margin, limit) + 'px');
el.css('top', margin + 'px');
} else if (own.bottom > window.innerHeight - margin) {
arrow.css('top', Math.min(own.height / 2 - (window.innerHeight - own.bottom) + margin, own.height - limit) + 'px');
el.css('top', (window.innerHeight - own.height - margin) + 'px');
}
} else {
if (own.left < margin) {
arrow.css('left', Math.max(own.width / 2 + own.left - margin, limit) + 'px');
el.css('left', margin + 'px');
} else if (own.right > window.innerWidth - margin) {
arrow.css('left', Math.min(own.width / 2 - (window.innerWidth - own.right) + margin, own.width - limit) + 'px');
el.css('left', (window.innerWidth - own.width - margin) + 'px');
}
}
},
_positionPopover: function(target) {
var directions;
if (!this._element.attr('direction')) {
directions = ['up', 'down', 'left', 'right'];
} else {
directions = this._element.attr('direction').split(/\s+/);
}
var position = target.getBoundingClientRect();
// The popover should be placed on the side with the most space.
var scores = {
left: position.left,
right: window.innerWidth - position.right,
up: position.top,
down: window.innerHeight - position.bottom
};
var orderedDirections = Object.keys(scores).sort(function(a, b) {return -(scores[a] - scores[b]);});
for (var i = 0, l = orderedDirections.length; i < l; i++) {
var direction = orderedDirections[i];
if (directions.indexOf(direction) > -1) {
this._positionPopoverByDirection(target, direction);
return;
}
}
},
/**
* Show popover.
*
* @param {HTMLElement} [target] target element
* @param {String} [target] css selector
* @param {Event} [target] event
* @param {Object} [options] options
* @param {String} [options.animation] animation type
*/
show: function(target, options) {
if (typeof target === 'string') {
target = document.querySelector(target);
} else if (target instanceof Event) {
target = target.target;
}
if (!target) {
throw new Error('Target undefined');
}
options = options || {};
var cancel = false;
this.emit('preshow', {
popover: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
this._element.css('display', 'block');
this._currentTarget = target;
this._positionPopover(target);
if (options.animation) {
animation = PopoverView._animatorDict[options.animation];
}
animation.show(this, function() {
this._visible = true;
this._positionPopover(target);
unlock();
this.emit('postshow', {popover: this});
}.bind(this));
}.bind(this));
}
},
/**
* Hide popover.
*
* @param {Object} [options] options
* @param {String} [options.animation] animation type
*/
hide: function(options) {
options = options || {};
var cancel = false;
this.emit('prehide', {
popover: this,
cancel: function() { cancel = true; }
});
if (!cancel) {
this._doorLock.waitUnlock(function() {
var unlock = this._doorLock.lock(),
animation = this._animation;
if (options.animation) {
animation = PopoverView._animatorDict[options.animation];
}
animation.hide(this, function() {
this._element.css('display', 'none');
this._visible = false;
unlock();
this.emit('posthide', {popover: this});
}.bind(this));
}.bind(this));
}
},
/**
* Returns whether the popover is visible or not.
*
* @return {Boolean}
*/
isShown: function() {
return this._visible;
},
/**
* Destroy the popover and remove it from the DOM tree.
*/
destroy: function() {
if (this._parentScope) {
this._parentScope.$destroy();
this._parentScope = null;
} else {
this._scope.$destroy();
}
},
_destroy: function() {
this.emit('destroy');
this._deviceBackButtonHandler.destroy();
this._popover[0].removeEventListener('DOMNodeInserted', this._onChange, false);
this._popover[0].removeEventListener('DOMNodeRemoved', this._onChange, false);
window.removeEventListener('resize', this._onChange, false);
this._mask.off();
this._mask.remove();
this._popover.remove();
this._element.remove();
this._onChange = this._deviceBackButtonHandler = this._mask = this._popover = this._element = this._scope = null;
},
/**
* Set whether the popover should be cancelable or not.
*
* @param {Boolean}
*/
setCancelable: function(cancelable) {
if (typeof cancelable !== 'boolean') {
throw new Error('Argument must be a boolean.');
}
if (cancelable) {
this._element.attr('cancelable', true);
} else {
this._element.removeAttr('cancelable');
}
},
/**
* Return whether the popover is cancelable or not.
*
* @return {Boolean}
*/
isCancelable: function() {
return this._element[0].hasAttribute('cancelable');
},
_cancel: function() {
if (this.isCancelable()) {
this.hide();
}
},
});
PopoverView._animatorDict = {
'fade': new FadePopoverAnimator(),
'none': new PopoverAnimator()
};
/**
* @param {String} name
* @param {PopoverAnimator} animator
*/
PopoverView.registerAnimator = function(name, animator) {
if (!(animator instanceof PopoverAnimator)) {
throw new Error('"animator" param must be an instance of PopoverAnimator');
}
this._animatorDict[name] = animator;
};
MicroEvent.mixin(PopoverView);
return PopoverView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('PopoverAnimator', function() {
var PopoverAnimator = Class.extend({
show: function(popover, callback) {
callback();
},
hide: function(popover, callback) {
callback();
}
});
return PopoverAnimator;
});
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('PullHookView', ['$onsen', '$parse', function($onsen, $parse) {
var PullHookView = Class.extend({
STATE_INITIAL: 'initial',
STATE_PREACTION: 'preaction',
STATE_ACTION: 'action',
/**
* @param {Object} scope
* @param {jqLite} element
* @param {Object} attrs
*/
init: function(scope, element, attrs) {
this._element = element;
this._scope = scope;
this._attrs = attrs;
this._scrollElement = this._createScrollElement();
this._pageElement = this._scrollElement.parent();
if (!this._pageElement.hasClass('page__content') && !this._pageElement.hasClass('ons-scroller__content')) {
throw new Error('<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.');
}
this._currentTranslation = 0;
this._createEventListeners();
this._setState(this.STATE_INITIAL, true);
this._setStyle();
this._scope.$on('$destroy', this._destroy.bind(this));
},
_createScrollElement: function() {
var scrollElement = angular.element('<div>')
.addClass('scroll');
var pageElement = this._element.parent(),
children = pageElement.children();
pageElement.append(scrollElement);
scrollElement.append(children);
return scrollElement;
},
_setStyle: function() {
var h = this._getHeight();
this._element.css({
top: '-' + h + 'px',
height: h + 'px',
lineHeight: h + 'px'
});
},
_onScroll: function(event) {
var el = this._pageElement[0];
if (el.scrollTop < 0) {
el.scrollTop = 0;
}
},
_generateTranslationTransform: function(scroll) {
return 'translate3d(0px, ' + scroll + 'px, 0px)';
},
_onDrag: function(event) {
if (this.isDisabled()) {
return;
}
// Ignore when dragging left and right.
if (event.gesture.direction === 'left' || event.gesture.direction === 'right') {
return;
}
// Hack to make it work on Android 4.4 WebView. Scrolls manually near the top of the page so
// there will be no inertial scroll when scrolling down. Allowing default scrolling will
// kill all 'touchmove' events.
var el = this._pageElement[0];
el.scrollTop = this._startScroll - event.gesture.deltaY;
if (el.scrollTop < window.innerHeight && event.gesture.direction !== 'up') {
event.gesture.preventDefault();
}
if (this._currentTranslation === 0 && this._getCurrentScroll() === 0) {
this._transitionDragLength = event.gesture.deltaY;
var direction = event.gesture.interimDirection;
if (direction === 'down') {
this._transitionDragLength -= 1;
}
else {
this._transitionDragLength += 1;
}
}
var scroll = event.gesture.deltaY - this._startScroll;
scroll = Math.max(scroll, 0);
if (this._thresholdHeightEnabled() && scroll >= this._getThresholdHeight()) {
event.gesture.stopDetect();
setImmediate(function() {
this._setState(this.STATE_ACTION);
this._translateTo(this._getHeight(), {animate: true});
this._waitForAction(this._onDone.bind(this));
}.bind(this));
}
else if (scroll >= this._getHeight()) {
this._setState(this.STATE_PREACTION);
}
else {
this._setState(this.STATE_INITIAL);
}
event.stopPropagation();
this._translateTo(scroll);
},
_onDragStart: function(event) {
if (this.isDisabled()) {
return;
}
this._startScroll = this._getCurrentScroll();
},
_onDragEnd: function(event) {
if (this.isDisabled()) {
return;
}
if (this._currentTranslation > 0) {
var scroll = this._currentTranslation;
if (scroll > this._getHeight()) {
this._setState(this.STATE_ACTION);
this._translateTo(this._getHeight(), {animate: true});
this._waitForAction(this._onDone.bind(this));
}
else {
this._translateTo(0, {animate: true});
}
}
},
_waitForAction: function(done) {
if (this._attrs.ngAction) {
this._scope.$eval(this._attrs.ngAction, {$done: done});
}
else if (this._attrs.onAction) {
/*jshint evil:true */
eval(this._attrs.onAction);
}
else {
done();
}
},
_onDone: function(done) {
// Check if the pull hook still exists.
if (this._element) {
this._translateTo(0, {animate: true});
this._setState(this.STATE_INITIAL);
}
},
_getHeight: function() {
return parseInt(this._element[0].getAttribute('height') || '64', 10);
},
setHeight: function(height) {
this._element[0].setAttribute('height', height + 'px');
this._setStyle();
},
setThresholdHeight: function(thresholdHeight) {
this._element[0].setAttribute('threshold-height', thresholdHeight + 'px');
},
_getThresholdHeight: function() {
return parseInt(this._element[0].getAttribute('threshold-height') || '96', 10);
},
_thresholdHeightEnabled: function() {
var th = this._getThresholdHeight();
return th > 0 && th >= this._getHeight();
},
_setState: function(state, noEvent) {
var oldState = this._getState();
this._scope.$evalAsync(function() {
this._element[0].setAttribute('state', state);
if (!noEvent && oldState !== this._getState()) {
this.emit('changestate', {
state: state,
pullHook: this
});
}
}.bind(this));
},
_getState: function() {
return this._element[0].getAttribute('state');
},
getCurrentState: function() {
return this._getState();
},
_getCurrentScroll: function() {
return this._pageElement[0].scrollTop;
},
isDisabled: function() {
return this._element[0].hasAttribute('disabled');
},
setDisabled: function(disabled) {
if (disabled) {
this._element[0].setAttribute('disabled', '');
}
else {
this._element[0].removeAttribute('disabled');
}
},
_translateTo: function(scroll, options) {
options = options || {};
this._currentTranslation = scroll;
if (options.animate) {
animit(this._scrollElement[0])
.queue({
transform: this._generateTranslationTransform(scroll)
}, {
duration: 0.3,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play(options.callback);
}
else {
animit(this._scrollElement[0])
.queue({
transform: this._generateTranslationTransform(scroll)
})
.play(options.callback);
}
},
_getMinimumScroll: function() {
var scrollHeight = this._scrollElement[0].getBoundingClientRect().height,
pageHeight = this._pageElement[0].getBoundingClientRect().height;
if (scrollHeight > pageHeight) {
return -(scrollHeight - pageHeight);
}
else {
return 0;
}
},
_createEventListeners: function() {
var element = this._scrollElement.parent();
this._hammer = new Hammer(element[0], {
dragMinDistance: 1,
dragDistanceCorrection: false
});
// Event listeners
this._bindedOnDrag = this._onDrag.bind(this);
this._bindedOnDragStart = this._onDragStart.bind(this);
this._bindedOnDragEnd = this._onDragEnd.bind(this);
this._bindedOnScroll = this._onScroll.bind(this);
// Bind listeners
this._hammer.on('drag', this._bindedOnDrag);
this._hammer.on('dragstart', this._bindedOnDragStart);
this._hammer.on('dragend', this._bindedOnDragEnd);
element.on('scroll', this._bindedOnScroll);
},
_destroyEventListeners: function() {
var element = this._scrollElement.parent();
this._hammer.off('drag', this._bindedOnDrag);
this._hammer.off('dragstart', this._bindedOnDragStart);
this._hammer.off('dragend', this._bindedOnDragEnd);
element.off('scroll', this._bindedOnScroll);
},
_destroy: function() {
this.emit('destroy');
this._destroyEventListeners();
this._element = this._scope = this._attrs = null;
}
});
MicroEvent.mixin(PullHookView);
return PullHookView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('PushSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) {
var PushSlidingMenuAnimator = SlidingMenuAnimator.extend({
_isRight: false,
_element: undefined,
_menuPage: undefined,
_mainPage: undefined,
_width: undefined,
_duration: false,
/**
* @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element
* @param {jqLite} mainPage
* @param {jqLite} menuPage
* @param {Object} options
* @param {String} options.width "width" style value
* @param {Boolean} options.isRight
*/
setup: function(element, mainPage, menuPage, options) {
options = options || {};
this._element = element;
this._mainPage = mainPage;
this._menuPage = menuPage;
this._isRight = !!options.isRight;
this._width = options.width || '90%';
this._duration = 0.4;
menuPage.css({
width: options.width,
display: 'none'
});
if (this._isRight) {
menuPage.css({
right: '-' + options.width,
left: 'auto'
});
} else {
menuPage.css({
right: 'auto',
left: '-' + options.width
});
}
},
/**
* @param {Object} options
* @param {String} options.width
* @param {Object} options.isRight
*/
onResized: function(options) {
this._menuPage.css('width', options.width);
if (this._isRight) {
this._menuPage.css({
right: '-' + options.width,
left: 'auto'
});
} else {
this._menuPage.css({
right: 'auto',
left: '-' + options.width
});
}
if (options.isOpened) {
var max = this._menuPage[0].clientWidth;
var mainPageTransform = this._generateAbovePageTransform(max);
var menuPageStyle = this._generateBehindPageStyle(max);
animit(this._mainPage[0]).queue({transform: mainPageTransform}).play();
animit(this._menuPage[0]).queue(menuPageStyle).play();
}
},
/**
*/
destroy: function() {
this._mainPage.removeAttr('style');
this._menuPage.removeAttr('style');
this._element = this._mainPage = this._menuPage = null;
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
openMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
this._menuPage.css('display', 'block');
var max = this._menuPage[0].clientWidth;
var aboveTransform = this._generateAbovePageTransform(max);
var behindStyle = this._generateBehindPageStyle(max);
setTimeout(function() {
animit(this._mainPage[0])
.queue({
transform: aboveTransform
}, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
callback();
done();
})
.play();
animit(this._menuPage[0])
.queue(behindStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
closeMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
var aboveTransform = this._generateAbovePageTransform(0);
var behindStyle = this._generateBehindPageStyle(0);
setTimeout(function() {
animit(this._mainPage[0])
.queue({
transform: aboveTransform
}, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue({
transform: 'translate3d(0, 0, 0)'
})
.queue(function(done) {
this._menuPage.css('display', 'none');
callback();
done();
}.bind(this))
.play();
animit(this._menuPage[0])
.queue(behindStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
done();
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Object} options
* @param {Number} options.distance
* @param {Number} options.maxDistance
*/
translateMenu: function(options) {
this._menuPage.css('display', 'block');
var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance));
var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance));
animit(this._mainPage[0])
.queue({transform: aboveTransform})
.play();
animit(this._menuPage[0])
.queue(behindStyle)
.play();
},
_generateAbovePageTransform: function(distance) {
var x = this._isRight ? -distance : distance;
var aboveTransform = 'translate3d(' + x + 'px, 0, 0)';
return aboveTransform;
},
_generateBehindPageStyle: function(distance) {
var max = this._menuPage[0].clientWidth;
var behindX = this._isRight ? -distance : distance;
var behindTransform = 'translate3d(' + behindX + 'px, 0, 0)';
return {
transform: behindTransform
};
},
copy: function() {
return new PushSlidingMenuAnimator();
}
});
return PushSlidingMenuAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('RevealSlidingMenuAnimator', ['SlidingMenuAnimator', function(SlidingMenuAnimator) {
var RevealSlidingMenuAnimator = SlidingMenuAnimator.extend({
_blackMask: undefined,
_isRight: false,
_menuPage: undefined,
_element: undefined,
_mainPage: undefined,
_duration: undefined,
/**
* @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element
* @param {jqLite} mainPage
* @param {jqLite} menuPage
* @param {Object} options
* @param {String} options.width "width" style value
* @param {Boolean} options.isRight
*/
setup: function(element, mainPage, menuPage, options) {
this._element = element;
this._menuPage = menuPage;
this._mainPage = mainPage;
this._isRight = !!options.isRight;
this._width = options.width || '90%';
this._duration = 0.4;
mainPage.css({
boxShadow: '0px 0 10px 0px rgba(0, 0, 0, 0.2)'
});
menuPage.css({
width: options.width,
opacity: 0.9,
display: 'none'
});
if (this._isRight) {
menuPage.css({
right: '0px',
left: 'auto'
});
} else {
menuPage.css({
right: 'auto',
left: '0px'
});
}
this._blackMask = angular.element('<div></div>').css({
backgroundColor: 'black',
top: '0px',
left: '0px',
right: '0px',
bottom: '0px',
position: 'absolute',
display: 'none'
});
element.prepend(this._blackMask);
// Dirty fix for broken rendering bug on android 4.x.
animit(mainPage[0]).queue({transform: 'translate3d(0, 0, 0)'}).play();
},
/**
* @param {Object} options
* @param {Boolean} options.isOpened
* @param {String} options.width
*/
onResized: function(options) {
this._width = options.width;
this._menuPage.css('width', this._width);
if (options.isOpened) {
var max = this._menuPage[0].clientWidth;
var aboveTransform = this._generateAbovePageTransform(max);
var behindStyle = this._generateBehindPageStyle(max);
animit(this._mainPage[0]).queue({transform: aboveTransform}).play();
animit(this._menuPage[0]).queue(behindStyle).play();
}
},
/**
* @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element
* @param {jqLite} mainPage
* @param {jqLite} menuPage
*/
destroy: function() {
if (this._blackMask) {
this._blackMask.remove();
this._blackMask = null;
}
if (this._mainPage) {
this._mainPage.attr('style', '');
}
if (this._menuPage) {
this._menuPage.attr('style', '');
}
this._mainPage = this._menuPage = this._element = undefined;
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
openMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
this._menuPage.css('display', 'block');
this._blackMask.css('display', 'block');
var max = this._menuPage[0].clientWidth;
var aboveTransform = this._generateAbovePageTransform(max);
var behindStyle = this._generateBehindPageStyle(max);
setTimeout(function() {
animit(this._mainPage[0])
.queue({
transform: aboveTransform
}, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
callback();
done();
})
.play();
animit(this._menuPage[0])
.queue(behindStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Function} callback
* @param {Boolean} instant
*/
closeMenu: function(callback, instant) {
var duration = instant === true ? 0.0 : this._duration;
this._blackMask.css('display', 'block');
var aboveTransform = this._generateAbovePageTransform(0);
var behindStyle = this._generateBehindPageStyle(0);
setTimeout(function() {
animit(this._mainPage[0])
.queue({
transform: aboveTransform
}, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue({
transform: 'translate3d(0, 0, 0)'
})
.queue(function(done) {
this._menuPage.css('display', 'none');
callback();
done();
}.bind(this))
.play();
animit(this._menuPage[0])
.queue(behindStyle, {
duration: duration,
timing: 'cubic-bezier(.1, .7, .1, 1)'
})
.queue(function(done) {
done();
})
.play();
}.bind(this), 1000 / 60);
},
/**
* @param {Object} options
* @param {Number} options.distance
* @param {Number} options.maxDistance
*/
translateMenu: function(options) {
this._menuPage.css('display', 'block');
this._blackMask.css('display', 'block');
var aboveTransform = this._generateAbovePageTransform(Math.min(options.maxDistance, options.distance));
var behindStyle = this._generateBehindPageStyle(Math.min(options.maxDistance, options.distance));
delete behindStyle.opacity;
animit(this._mainPage[0])
.queue({transform: aboveTransform})
.play();
animit(this._menuPage[0])
.queue(behindStyle)
.play();
},
_generateAbovePageTransform: function(distance) {
var x = this._isRight ? -distance : distance;
var aboveTransform = 'translate3d(' + x + 'px, 0, 0)';
return aboveTransform;
},
_generateBehindPageStyle: function(distance) {
var max = this._menuPage[0].getBoundingClientRect().width;
var behindDistance = (distance - max) / max * 10;
behindDistance = isNaN(behindDistance) ? 0 : Math.max(Math.min(behindDistance, 0), -10);
var behindX = this._isRight ? -behindDistance : behindDistance;
var behindTransform = 'translate3d(' + behindX + '%, 0, 0)';
var opacity = 1 + behindDistance / 100;
return {
transform: behindTransform,
opacity: opacity
};
},
copy: function() {
return new RevealSlidingMenuAnimator();
}
});
return RevealSlidingMenuAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('SimpleSlideTransitionAnimator', ['NavigatorTransitionAnimator', function(NavigatorTransitionAnimator) {
/**
* Slide animator for navigator transition.
*/
var SimpleSlideTransitionAnimator = NavigatorTransitionAnimator.extend({
/** Black mask */
backgroundMask : angular.element(
'<div style="z-index: 2; position: absolute; width: 100%;' +
'height: 100%; background-color: black; opacity: 0;"></div>'
),
timing: 'cubic-bezier(.1, .7, .4, 1)',
duration: 0.3,
blackMaskOpacity: 0.4,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} callback
*/
push: function(enterPage, leavePage, callback) {
var mask = this.backgroundMask.remove();
leavePage.element[0].parentNode.insertBefore(mask[0], leavePage.element[0].nextSibling);
animit.runAll(
animit(mask[0])
.queue({
opacity: 0,
transform: 'translate3d(0, 0, 0)'
})
.queue({
opacity: this.blackMaskOpacity
}, {
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
mask.remove();
done();
}),
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(100%, 0, 0)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0, 0, 0)',
},
duration: this.duration,
timing: this.timing
})
.resetStyle(),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0, 0, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(-45%, 0px, 0px)'
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.wait(0.2)
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} enterPage
* @param {Object} leavePage
* @param {Function} done
*/
pop: function(enterPage, leavePage, done) {
var mask = this.backgroundMask.remove();
enterPage.element[0].parentNode.insertBefore(mask[0], enterPage.element[0].nextSibling);
animit.runAll(
animit(mask[0])
.queue({
opacity: this.blackMaskOpacity,
transform: 'translate3d(0, 0, 0)'
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
mask.remove();
done();
}),
animit(enterPage.element[0])
.queue({
css: {
transform: 'translate3D(-45%, 0px, 0px)',
opacity: 0.9
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)',
opacity: 1.0
},
duration: this.duration,
timing: this.timing
})
.resetStyle(),
animit(leavePage.element[0])
.queue({
css: {
transform: 'translate3D(0px, 0px, 0px)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(100%, 0px, 0px)'
},
duration: this.duration,
timing: this.timing
})
.wait(0.2)
.queue(function(finish) {
done();
finish();
})
);
}
});
return SimpleSlideTransitionAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('SlideDialogAnimator', ['DialogAnimator', function(DialogAnimator) {
/**
* Slide animator for dialog.
*/
var SlideDialogAnimator = DialogAnimator.extend({
timing: 'cubic-bezier(.1, .7, .4, 1)',
duration: 0.2,
init: function(options) {
options = options || {};
this.timing = options.timing || this.timing;
this.duration = options.duration !== undefined ? options.duration : this.duration;
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
show: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 0
})
.queue({
opacity: 1.0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3D(-50%, -350%, 0)',
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(-50%, -50%, 0)',
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
},
/**
* @param {Object} dialog
* @param {Function} callback
*/
hide: function(dialog, callback) {
callback = callback ? callback : function() {};
animit.runAll(
animit(dialog._mask[0])
.queue({
opacity: 1.0
})
.queue({
opacity: 0
}, {
duration: this.duration,
timing: this.timing
}),
animit(dialog._dialog[0])
.queue({
css: {
transform: 'translate3D(-50%, -50%, 0)'
},
duration: 0
})
.queue({
css: {
transform: 'translate3D(-50%, -350%, 0)'
},
duration: this.duration,
timing: this.timing
})
.resetStyle()
.queue(function(done) {
callback();
done();
})
);
}
});
return SlideDialogAnimator;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
var SlidingMenuViewModel = Class.extend({
/**
* @member Number
*/
_distance: 0,
/**
* @member Number
*/
_maxDistance: undefined,
/**
* @param {Object} options
* @param {Number} maxDistance
*/
init: function(options) {
if (!angular.isNumber(options.maxDistance)) {
throw new Error('options.maxDistance must be number');
}
this.setMaxDistance(options.maxDistance);
},
/**
* @param {Number} maxDistance
*/
setMaxDistance: function(maxDistance) {
if (maxDistance <= 0) {
throw new Error('maxDistance must be greater then zero.');
}
if (this.isOpened()) {
this._distance = maxDistance;
}
this._maxDistance = maxDistance;
},
/**
* @return {Boolean}
*/
shouldOpen: function() {
return !this.isOpened() && this._distance >= this._maxDistance / 2;
},
/**
* @return {Boolean}
*/
shouldClose: function() {
return !this.isClosed() && this._distance < this._maxDistance / 2;
},
openOrClose: function(options) {
if (this.shouldOpen()) {
this.open(options);
} else if (this.shouldClose()) {
this.close(options);
}
},
close: function(options) {
var callback = options.callback || function() {};
if (!this.isClosed()) {
this._distance = 0;
this.emit('close', options);
} else {
callback();
}
},
open: function(options) {
var callback = options.callback || function() {};
if (!this.isOpened()) {
this._distance = this._maxDistance;
this.emit('open', options);
} else {
callback();
}
},
/**
* @return {Boolean}
*/
isClosed: function() {
return this._distance === 0;
},
/**
* @return {Boolean}
*/
isOpened: function() {
return this._distance === this._maxDistance;
},
/**
* @return {Number}
*/
getX: function() {
return this._distance;
},
/**
* @return {Number}
*/
getMaxDistance: function() {
return this._maxDistance;
},
/**
* @param {Number} x
*/
translate: function(x) {
this._distance = Math.max(1, Math.min(this._maxDistance - 1, x));
var options = {
distance: this._distance,
maxDistance: this._maxDistance
};
this.emit('translate', options);
},
toggle: function() {
if (this.isClosed()) {
this.open();
} else {
this.close();
}
}
});
MicroEvent.mixin(SlidingMenuViewModel);
module.factory('SlidingMenuView', ['$onsen', '$compile', 'SlidingMenuAnimator', 'RevealSlidingMenuAnimator', 'PushSlidingMenuAnimator', 'OverlaySlidingMenuAnimator', function($onsen, $compile, SlidingMenuAnimator, RevealSlidingMenuAnimator,
PushSlidingMenuAnimator, OverlaySlidingMenuAnimator) {
var SlidingMenuView = Class.extend({
_scope: undefined,
_attrs: undefined,
_element: undefined,
_menuPage: undefined,
_mainPage: undefined,
_doorLock: undefined,
_isRightMenu: false,
init: function(scope, element, attrs) {
this._scope = scope;
this._attrs = attrs;
this._element = element;
this._menuPage = angular.element(element[0].querySelector('.onsen-sliding-menu__menu'));
this._mainPage = angular.element(element[0].querySelector('.onsen-sliding-menu__main'));
this._doorLock = new DoorLock();
this._isRightMenu = attrs.side === 'right';
// Close menu on tap event.
this._mainPageHammer = new Hammer(this._mainPage[0]);
this._bindedOnTap = this._onTap.bind(this);
var maxDistance = this._normalizeMaxSlideDistanceAttr();
this._logic = new SlidingMenuViewModel({maxDistance: Math.max(maxDistance, 1)});
this._logic.on('translate', this._translate.bind(this));
this._logic.on('open', function(options) {
this._open(options);
}.bind(this));
this._logic.on('close', function(options) {
this._close(options);
}.bind(this));
attrs.$observe('maxSlideDistance', this._onMaxSlideDistanceChanged.bind(this));
attrs.$observe('swipeable', this._onSwipeableChanged.bind(this));
this._bindedOnWindowResize = this._onWindowResize.bind(this);
window.addEventListener('resize', this._bindedOnWindowResize);
this._boundHandleEvent = this._handleEvent.bind(this);
this._bindEvents();
if (attrs.mainPage) {
this.setMainPage(attrs.mainPage);
}
if (attrs.menuPage) {
this.setMenuPage(attrs.menuPage);
}
this._deviceBackButtonHandler = $onsen.DeviceBackButtonHandler.create(this._element, this._onDeviceBackButton.bind(this));
var unlock = this._doorLock.lock();
window.setTimeout(function() {
var maxDistance = this._normalizeMaxSlideDistanceAttr();
this._logic.setMaxDistance(maxDistance);
this._menuPage.css({opacity: 1});
this._animator = this._getAnimatorOption();
this._animator.setup(
this._element,
this._mainPage,
this._menuPage,
{
isRight: this._isRightMenu,
width: this._attrs.maxSlideDistance || '90%'
}
);
unlock();
}.bind(this), 400);
scope.$on('$destroy', this._destroy.bind(this));
if (!attrs.swipeable) {
this.setSwipeable(true);
}
},
getDeviceBackButtonHandler: function() {
return this._deviceBackButtonHandler;
},
_onDeviceBackButton: function(event) {
if (this.isMenuOpened()) {
this.closeMenu();
} else {
event.callParentHandler();
}
},
_onTap: function() {
if (this.isMenuOpened()) {
this.closeMenu();
}
},
_refreshMenuPageWidth: function() {
var width = ('maxSlideDistance' in this._attrs) ? this._attrs.maxSlideDistance : '90%';
if (this._animator) {
this._animator.onResized({
isOpened: this._logic.isOpened(),
width: width
});
}
},
_destroy: function() {
this.emit('destroy');
this._deviceBackButtonHandler.destroy();
window.removeEventListener('resize', this._bindedOnWindowResize);
this._mainPageHammer.off('tap', this._bindedOnTap);
this._element = this._scope = this._attrs = null;
},
_getAnimatorOption: function() {
var animator = SlidingMenuView._animatorDict[this._attrs.type];
if (!(animator instanceof SlidingMenuAnimator)) {
animator = SlidingMenuView._animatorDict['default'];
}
return animator.copy();
},
_onSwipeableChanged: function(swipeable) {
swipeable = swipeable === '' || swipeable === undefined || swipeable == 'true';
this.setSwipeable(swipeable);
},
/**
* @param {Boolean} enabled
*/
setSwipeable: function(enabled) {
if (enabled) {
this._activateHammer();
} else {
this._deactivateHammer();
}
},
_onWindowResize: function() {
this._recalculateMAX();
this._refreshMenuPageWidth();
},
_onMaxSlideDistanceChanged: function() {
this._recalculateMAX();
this._refreshMenuPageWidth();
},
/**
* @return {Number}
*/
_normalizeMaxSlideDistanceAttr: function() {
var maxDistance = this._attrs.maxSlideDistance;
if (!('maxSlideDistance' in this._attrs)) {
maxDistance = 0.9 * this._mainPage[0].clientWidth;
} else if (typeof maxDistance == 'string') {
if (maxDistance.indexOf('px', maxDistance.length - 2) !== -1) {
maxDistance = parseInt(maxDistance.replace('px', ''), 10);
} else if (maxDistance.indexOf('%', maxDistance.length - 1) > 0) {
maxDistance = maxDistance.replace('%', '');
maxDistance = parseFloat(maxDistance) / 100 * this._mainPage[0].clientWidth;
}
} else {
throw new Error('invalid state');
}
return maxDistance;
},
_recalculateMAX: function() {
var maxDistance = this._normalizeMaxSlideDistanceAttr();
if (maxDistance) {
this._logic.setMaxDistance(parseInt(maxDistance, 10));
}
},
_activateHammer: function(){
this._hammertime.on('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent);
},
_deactivateHammer: function(){
this._hammertime.off('touch dragleft dragright swipeleft swiperight release', this._boundHandleEvent);
},
_bindEvents: function() {
this._hammertime = new Hammer(this._element[0], {
dragMinDistance: 1
});
},
_appendMainPage: function(pageUrl, templateHTML) {
var pageScope = this._scope.$new();
var pageContent = angular.element(templateHTML);
var link = $compile(pageContent);
this._mainPage.append(pageContent);
if (this._currentPageElement) {
this._currentPageElement.remove();
this._currentPageScope.$destroy();
}
link(pageScope);
this._currentPageElement = pageContent;
this._currentPageScope = pageScope;
this._currentPageUrl = pageUrl;
},
/**
* @param {String}
*/
_appendMenuPage: function(templateHTML) {
var pageScope = this._scope.$new();
var pageContent = angular.element(templateHTML);
var link = $compile(pageContent);
this._menuPage.append(pageContent);
if (this._currentMenuPageScope) {
this._currentMenuPageScope.$destroy();
this._currentMenuPageElement.remove();
}
link(pageScope);
this._currentMenuPageElement = pageContent;
this._currentMenuPageScope = pageScope;
},
/**
* @param {String} page
* @param {Object} options
* @param {Boolean} [options.closeMenu]
* @param {Boolean} [options.callback]
*/
setMenuPage: function(page, options) {
if (page) {
options = options || {};
options.callback = options.callback || function() {};
var self = this;
$onsen.getPageHTMLAsync(page).then(function(html) {
self._appendMenuPage(angular.element(html));
if (options.closeMenu) {
self.close();
}
options.callback();
}, function() {
throw new Error('Page is not found: ' + page);
});
} else {
throw new Error('cannot set undefined page');
}
},
/**
* @param {String} pageUrl
* @param {Object} options
* @param {Boolean} [options.closeMenu]
* @param {Boolean} [options.callback]
*/
setMainPage: function(pageUrl, options) {
options = options || {};
options.callback = options.callback || function() {};
var done = function() {
if (options.closeMenu) {
this.close();
}
options.callback();
}.bind(this);
if (this.currentPageUrl === pageUrl) {
done();
return;
}
if (pageUrl) {
var self = this;
$onsen.getPageHTMLAsync(pageUrl).then(function(html) {
self._appendMainPage(pageUrl, html);
done();
}, function() {
throw new Error('Page is not found: ' + page);
});
} else {
throw new Error('cannot set undefined page');
}
},
_handleEvent: function(event) {
if (this._doorLock.isLocked()) {
return;
}
if (this._isInsideIgnoredElement(event.target)){
event.gesture.stopDetect();
}
switch (event.type) {
case 'dragleft':
case 'dragright':
if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) {
return;
}
event.gesture.preventDefault();
var deltaX = event.gesture.deltaX;
var deltaDistance = this._isRightMenu ? -deltaX : deltaX;
var startEvent = event.gesture.startEvent;
if (!('isOpened' in startEvent)) {
startEvent.isOpened = this._logic.isOpened();
}
if (deltaDistance < 0 && this._logic.isClosed()) {
break;
}
if (deltaDistance > 0 && this._logic.isOpened()) {
break;
}
var distance = startEvent.isOpened ?
deltaDistance + this._logic.getMaxDistance() : deltaDistance;
this._logic.translate(distance);
break;
case 'swipeleft':
event.gesture.preventDefault();
if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) {
return;
}
if (this._isRightMenu) {
this.open();
} else {
this.close();
}
event.gesture.stopDetect();
break;
case 'swiperight':
event.gesture.preventDefault();
if (this._logic.isClosed() && !this._isInsideSwipeTargetArea(event)) {
return;
}
if (this._isRightMenu) {
this.close();
} else {
this.open();
}
event.gesture.stopDetect();
break;
case 'release':
this._lastDistance = null;
if (this._logic.shouldOpen()) {
this.open();
} else if (this._logic.shouldClose()) {
this.close();
}
break;
}
},
/**
* @param {jqLite} element
* @return {Boolean}
*/
_isInsideIgnoredElement: function(element) {
do {
if (element.getAttribute && element.getAttribute('sliding-menu-ignore')) {
return true;
}
element = element.parentNode;
} while (element);
return false;
},
_isInsideSwipeTargetArea: function(event) {
var x = event.gesture.center.pageX;
if (!('_swipeTargetWidth' in event.gesture.startEvent)) {
event.gesture.startEvent._swipeTargetWidth = this._getSwipeTargetWidth();
}
var targetWidth = event.gesture.startEvent._swipeTargetWidth;
return this._isRightMenu ? this._mainPage[0].clientWidth - x < targetWidth : x < targetWidth;
},
_getSwipeTargetWidth: function() {
var targetWidth = this._attrs.swipeTargetWidth;
if (typeof targetWidth == 'string') {
targetWidth = targetWidth.replace('px', '');
}
var width = parseInt(targetWidth, 10);
if (width < 0 || !targetWidth) {
return this._mainPage[0].clientWidth;
} else {
return width;
}
},
closeMenu: function() {
return this.close.apply(this, arguments);
},
/**
* Close sliding-menu page.
*
* @param {Object} options
*/
close: function(options) {
options = options || {};
options = typeof options == 'function' ? {callback: options} : options;
if (!this._logic.isClosed()) {
this.emit('preclose', {
slidingMenu: this
});
this._doorLock.waitUnlock(function() {
this._logic.close(options);
}.bind(this));
}
},
_close: function(options) {
var callback = options.callback || function() {},
unlock = this._doorLock.lock(),
instant = options.animation == 'none';
this._animator.closeMenu(function() {
unlock();
this._mainPage.children().css('pointer-events', '');
this._mainPageHammer.off('tap', this._bindedOnTap);
this.emit('postclose', {
slidingMenu: this
});
callback();
}.bind(this), instant);
},
/**
* Open sliding-menu page.
*
* @param {Object} [options]
* @param {Function} [options.callback]
*/
openMenu: function() {
return this.open.apply(this, arguments);
},
/**
* Open sliding-menu page.
*
* @param {Object} [options]
* @param {Function} [options.callback]
*/
open: function(options) {
options = options || {};
options = typeof options == 'function' ? {callback: options} : options;
this.emit('preopen', {
slidingMenu: this
});
this._doorLock.waitUnlock(function() {
this._logic.open(options);
}.bind(this));
},
_open: function(options) {
var callback = options.callback || function() {},
unlock = this._doorLock.lock(),
instant = options.animation == 'none';
this._animator.openMenu(function() {
unlock();
this._mainPage.children().css('pointer-events', 'none');
this._mainPageHammer.on('tap', this._bindedOnTap);
this.emit('postopen', {
slidingMenu: this
});
callback();
}.bind(this), instant);
},
/**
* Toggle sliding-menu page.
* @param {Object} [options]
* @param {Function} [options.callback]
*/
toggle: function(options) {
if (this._logic.isClosed()) {
this.open(options);
} else {
this.close(options);
}
},
/**
* Toggle sliding-menu page.
*/
toggleMenu: function() {
return this.toggle.apply(this, arguments);
},
/**
* @return {Boolean}
*/
isMenuOpened: function() {
return this._logic.isOpened();
},
/**
* @param {Object} event
*/
_translate: function(event) {
this._animator.translateMenu(event);
}
});
// Preset sliding menu animators.
SlidingMenuView._animatorDict = {
'default': new RevealSlidingMenuAnimator(),
'overlay': new OverlaySlidingMenuAnimator(),
'reveal': new RevealSlidingMenuAnimator(),
'push': new PushSlidingMenuAnimator()
};
/**
* @param {String} name
* @param {NavigatorTransitionAnimator} animator
*/
SlidingMenuView.registerSlidingMenuAnimator = function(name, animator) {
if (!(animator instanceof SlidingMenuAnimator)) {
throw new Error('"animator" param must be an instance of SlidingMenuAnimator');
}
this._animatorDict[name] = animator;
};
MicroEvent.mixin(SlidingMenuView);
return SlidingMenuView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('SlidingMenuAnimator', function() {
return Class.extend({
/**
* @param {jqLite} element "ons-sliding-menu" or "ons-split-view" element
* @param {jqLite} mainPage
* @param {jqLite} menuPage
* @param {Object} options
* @param {String} options.width "width" style value
* @param {Boolean} options.isRight
*/
setup: function(element, mainPage, menuPage, options) {
},
/**
* @param {Object} options
* @param {Boolean} options.isRight
* @param {Boolean} options.isOpened
* @param {String} options.width
*/
onResized: function(options) {
},
/**
* @param {Function} callback
*/
openMenu: function(callback) {
},
/**
* @param {Function} callback
*/
closeClose: function(callback) {
},
/**
*/
destroy: function() {
},
/**
* @param {Object} options
* @param {Number} options.distance
* @param {Number} options.maxDistance
*/
translateMenu: function(mainPage, menuPage, options) {
},
/**
* @return {SlidingMenuAnimator}
*/
copy: function() {
throw new Error('Override copy method.');
}
});
});
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict';
var module = angular.module('onsen');
module.factory('SplitView', ['$compile', 'RevealSlidingMenuAnimator', '$onsen', '$onsGlobal', function($compile, RevealSlidingMenuAnimator, $onsen, $onsGlobal) {
var SPLIT_MODE = 0;
var COLLAPSE_MODE = 1;
var MAIN_PAGE_RATIO = 0.9;
var ON_PAGE_READY = 'onPageReady';
var SplitView = Class.extend({
init: function(scope, element, attrs) {
element.addClass('onsen-sliding-menu');
this._element = element;
this._scope = scope;
this._attrs = attrs;
this._mainPage = angular.element(element[0].querySelector('.onsen-split-view__main'));
this._secondaryPage = angular.element(element[0].querySelector('.onsen-split-view__secondary'));
this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO;
this._mode = SPLIT_MODE;
this._doorLock = new DoorLock();
this._doSplit = false;
this._doCollapse = false;
$onsGlobal.orientation.on('change', this._onResize.bind(this));
this._animator = new RevealSlidingMenuAnimator();
this._element.css('display', 'none');
if (attrs.mainPage) {
this.setMainPage(attrs.mainPage);
}
if (attrs.secondaryPage) {
this.setSecondaryPage(attrs.secondaryPage);
}
var unlock = this._doorLock.lock();
this._considerChangingCollapse();
this._setSize();
setTimeout(function() {
this._element.css('display', 'block');
unlock();
}.bind(this), 1000 / 60 * 2);
scope.$on('$destroy', this._destroy.bind(this));
},
/**
* @param {String} templateHTML
*/
_appendSecondPage: function(templateHTML) {
var pageScope = this._scope.$new();
var pageContent = $compile(templateHTML)(pageScope);
this._secondaryPage.append(pageContent);
if (this._currentSecondaryPageElement) {
this._currentSecondaryPageElement.remove();
this._currentSecondaryPageScope.$destroy();
}
this._currentSecondaryPageElement = pageContent;
this._currentSecondaryPageScope = pageScope;
},
/**
* @param {String} templateHTML
*/
_appendMainPage: function(templateHTML) {
var pageScope = this._scope.$new();
var pageContent = $compile(templateHTML)(pageScope);
this._mainPage.append(pageContent);
if (this._currentPage) {
this._currentPage.remove();
this._currentPageScope.$destroy();
}
this._currentPage = pageContent;
this._currentPageScope = pageScope;
},
/**
* @param {String} page
*/
setSecondaryPage : function(page) {
if (page) {
$onsen.getPageHTMLAsync(page).then(function(html) {
this._appendSecondPage(angular.element(html.trim()));
}.bind(this), function() {
throw new Error('Page is not found: ' + page);
});
} else {
throw new Error('cannot set undefined page');
}
},
/**
* @param {String} page
*/
setMainPage : function(page) {
if (page) {
$onsen.getPageHTMLAsync(page).then(function(html) {
this._appendMainPage(angular.element(html.trim()));
}.bind(this), function() {
throw new Error('Page is not found: ' + page);
});
} else {
throw new Error('cannot set undefined page');
}
},
_onResize: function() {
var lastMode = this._mode;
this._considerChangingCollapse();
if (lastMode === COLLAPSE_MODE && this._mode === COLLAPSE_MODE) {
this._animator.onResized({
isOpened: false,
width: '90%'
});
}
this._max = this._mainPage[0].clientWidth * MAIN_PAGE_RATIO;
},
_considerChangingCollapse: function() {
var should = this._shouldCollapse();
if (should && this._mode !== COLLAPSE_MODE) {
this._fireUpdateEvent();
if (this._doSplit) {
this._activateSplitMode();
} else {
this._activateCollapseMode();
}
} else if (!should && this._mode === COLLAPSE_MODE) {
this._fireUpdateEvent();
if (this._doCollapse) {
this._activateCollapseMode();
} else {
this._activateSplitMode();
}
}
this._doCollapse = this._doSplit = false;
},
update: function() {
this._fireUpdateEvent();
var should = this._shouldCollapse();
if (this._doSplit) {
this._activateSplitMode();
} else if (this._doCollapse) {
this._activateCollapseMode();
} else if (should) {
this._activateCollapseMode();
} else if (!should) {
this._activateSplitMode();
}
this._doSplit = this._doCollapse = false;
},
_getOrientation: function() {
if ($onsGlobal.orientation.isPortrait()) {
return 'portrait';
} else {
return 'landscape';
}
},
getCurrentMode: function() {
if (this._mode === COLLAPSE_MODE) {
return 'collapse';
} else {
return 'split';
}
},
_shouldCollapse: function() {
var c = 'portrait';
if (typeof this._attrs.collapse === 'string') {
c = this._attrs.collapse.trim();
}
if (c == 'portrait') {
return $onsGlobal.orientation.isPortrait();
} else if (c == 'landscape') {
return $onsGlobal.orientation.isLandscape();
} else if (c.substr(0,5) == 'width') {
var num = c.split(' ')[1];
if (num.indexOf('px') >= 0) {
num = num.substr(0,num.length-2);
}
var width = window.innerWidth;
return isNumber(num) && width < num;
} else {
var mq = window.matchMedia(c);
return mq.matches;
}
},
_setSize: function() {
if (this._mode === SPLIT_MODE) {
if (!this._attrs.mainPageWidth) {
this._attrs.mainPageWidth = '70';
}
var secondarySize = 100 - this._attrs.mainPageWidth.replace('%', '');
this._secondaryPage.css({
width: secondarySize + '%',
opacity: 1
});
this._mainPage.css({
width: this._attrs.mainPageWidth + '%'
});
this._mainPage.css('left', secondarySize + '%');
}
},
_fireEvent: function(name) {
this.emit(name, {
splitView: this,
width: window.innerWidth,
orientation: this._getOrientation()
});
},
_fireUpdateEvent: function() {
var that = this;
this.emit('update', {
splitView: this,
shouldCollapse: this._shouldCollapse(),
currentMode: this.getCurrentMode(),
split: function() {
that._doSplit = true;
that._doCollapse = false;
},
collapse: function() {
that._doSplit = false;
that._doCollapse = true;
},
width: window.innerWidth,
orientation: this._getOrientation()
});
},
_activateCollapseMode: function() {
if (this._mode !== COLLAPSE_MODE) {
this._fireEvent('precollapse');
this._secondaryPage.attr('style', '');
this._mainPage.attr('style', '');
this._mode = COLLAPSE_MODE;
this._animator.setup(
this._element,
this._mainPage,
this._secondaryPage,
{isRight: false, width: '90%'}
);
this._fireEvent('postcollapse');
}
},
_activateSplitMode: function() {
if (this._mode !== SPLIT_MODE) {
this._fireEvent('presplit');
this._animator.destroy();
this._secondaryPage.attr('style', '');
this._mainPage.attr('style', '');
this._mode = SPLIT_MODE;
this._setSize();
this._fireEvent('postsplit');
}
},
_destroy: function() {
this.emit('destroy');
this._element = null;
this._scope = null;
}
});
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
MicroEvent.mixin(SplitView);
return SplitView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
module.factory('SwitchView', ['$onsen', function($onsen) {
var SwitchView = Class.extend({
/**
* @param {jqLite} element
* @param {Object} scope
* @param {Object} attrs
*/
init: function(element, scope, attrs) {
this._element = element;
this._checkbox = angular.element(element[0].querySelector('input[type=checkbox]'));
this._scope = scope;
attrs.$observe('disabled', function(disabled) {
if (!!element.attr('disabled')) {
this._checkbox.attr('disabled', 'disabled');
} else {
this._checkbox.removeAttr('disabled');
}
}.bind(this));
this._checkbox.on('change', function(event) {
this.emit('change', {'switch': this, value: this._checkbox[0].checked, isInteractive: true});
}.bind(this));
},
/**
* @return {Boolean}
*/
isChecked: function() {
return this._checkbox[0].checked;
},
/**
* @param {Boolean}
*/
setChecked: function(isChecked) {
isChecked = !!isChecked;
if (this._checkbox[0].checked != isChecked) {
this._scope.model = isChecked;
this._checkbox[0].checked = isChecked;
this._scope.$evalAsync();
this.emit('change', {'switch': this, value: isChecked, isInteractive: false});
}
},
/**
* @return {HTMLElement}
*/
getCheckboxElement: function() {
return this._checkbox[0];
}
});
MicroEvent.mixin(SwitchView);
return SwitchView;
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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() {
'use strict;';
var module = angular.module('onsen');
module.factory('TabbarAnimator', function() {
var TabbarAnimator = Class.extend({
/**
* @param {jqLite} enterPage
* @param {jqLite} leavePage
*/
apply: function(enterPage, leavePage, done) {
throw new Error('This method must be implemented.');
}
});
return TabbarAnimator;
});
module.factory('TabbarNoneAnimator', ['TabbarAnimator', function(TabbarAnimator) {
var TabbarNoneAnimator = TabbarAnimator.extend({
/**
* @param {jqLite} enterPage
* @param {jqLite} leavePage
*/
apply: function(enterPage, leavePage, done) {
done();
}
});
return TabbarNoneAnimator;
}]);
module.factory('TabbarFadeAnimator', ['TabbarAnimator', function(TabbarAnimator) {
var TabbarFadeAnimator = TabbarAnimator.extend({
/**
* @param {jqLite} enterPage
* @param {jqLite} leavePage
*/
apply: function(enterPage, leavePage, done) {
animit.runAll(
animit(enterPage[0])
.queue({
transform: 'translate3D(0, 0, 0)',
opacity: 0
})
.queue({
transform: 'translate3D(0, 0, 0)',
opacity: 1
}, {
duration: 0.4,
timing: 'linear'
})
.resetStyle()
.queue(function(callback) {
done();
callback();
}),
animit(leavePage[0])
.queue({
transform: 'translate3D(0, 0, 0)',
opacity: 1
})
.queue({
transform: 'translate3D(0, 0, 0)',
opacity: 0
}, {
duration: 0.4,
timing: 'linear'
})
);
}
});
return TabbarFadeAnimator;
}]);
module.factory('TabbarView', ['$onsen', '$compile', 'TabbarAnimator', 'TabbarNoneAnimator', 'TabbarFadeAnimator', function($onsen, $compile, TabbarAnimator, TabbarNoneAnimator, TabbarFadeAnimator) {
var TabbarView = Class.extend({
_tabbarId: undefined,
_tabItems: undefined,
init: function(scope, element, attrs) {
this._scope = scope;
this._element = element;
this._attrs = attrs;
this._tabbarId = Date.now();
this._tabItems = [];
this._contentElement = angular.element(element[0].querySelector('.ons-tab-bar__content'));
this._tabbarElement = angular.element(element[0].querySelector('.ons-tab-bar__footer'));
this._scope.$on('$destroy', this._destroy.bind(this));
if (this._hasTopTabbar()) {
this._prepareForTopTabbar();
}
},
_prepareForTopTabbar: function() {
this._contentElement.attr('no-status-bar-fill', '');
setImmediate(function() {
this._contentElement.addClass('tab-bar--top__content');
this._tabbarElement.addClass('tab-bar--top');
}.bind(this));
var page = ons.findParentComponentUntil('ons-page', this._element[0]);
if (page) {
this._element.css('top', window.getComputedStyle(page.getContentElement(), null).getPropertyValue('padding-top'));
}
if ($onsen.shouldFillStatusBar(this._element[0])) {
// Adjustments for IOS7
var fill = angular.element(document.createElement('div'));
fill.addClass('tab-bar__status-bar-fill');
fill.css({width: '0px', height: '0px'});
this._element.prepend(fill);
}
},
_hasTopTabbar: function() {
return this._attrs.position === 'top';
},
/**
* @param {Number} index
* @param {Object} [options]
* @param {Boolean} [options.keepPage]
* @param {String} [options.animation]
* @return {Boolean} success or not
*/
setActiveTab: function(index, options) {
options = options || {};
var previousTabItem = this._tabItems[this.getActiveTabIndex()];
var selectedTabItem = this._tabItems[index];
if ((typeof selectedTabItem.noReload !== 'undefined' || selectedTabItem.isPersistent()) &&
index === this.getActiveTabIndex()) {
this.emit('reactive', {
index: index,
tabItem: selectedTabItem,
});
return false;
}
var needLoad = selectedTabItem.page && !options.keepPage;
if (!selectedTabItem) {
return false;
}
var canceled = false;
this.emit('prechange', {
index: index,
tabItem: selectedTabItem,
cancel: function() {
canceled = true;
}
});
if (canceled) {
selectedTabItem.setInactive();
if (previousTabItem) {
previousTabItem.setActive();
}
return false;
}
selectedTabItem.setActive();
if (needLoad) {
var removeElement = true;
if (previousTabItem && previousTabItem.isPersistent()) {
removeElement = false;
previousTabItem._pageElement = this._currentPageElement;
}
var params = {
callback: function() {
this.emit('postchange', {index: index, tabItem: selectedTabItem});
}.bind(this),
_removeElement: removeElement
};
if (options.animation) {
params.animation = options.animation;
}
if (selectedTabItem.isPersistent() && selectedTabItem._pageElement) {
this._loadPersistentPageDOM(selectedTabItem._pageElement, params);
}
else {
this._loadPage(selectedTabItem.page, params);
}
}
for (var i = 0; i < this._tabItems.length; i++) {
if (this._tabItems[i] != selectedTabItem) {
this._tabItems[i].setInactive();
} else {
if (!needLoad) {
this.emit('postchange', {index: index, tabItem: selectedTabItem});
}
}
}
return true;
},
/**
* @param {Boolean} visible
*/
setTabbarVisibility: function(visible) {
this._scope.hideTabs = !visible;
this._onTabbarVisibilityChanged();
},
_onTabbarVisibilityChanged: function() {
if (this._hasTopTabbar()) {
if (this._scope.hideTabs) {
this._contentElement.css('top', '0px');
} else {
this._contentElement.css('top', '');
}
} else {
if (this._scope.hideTabs) {
this._contentElement.css('bottom', '0px');
} else {
this._contentElement.css('bottom', '');
}
}
},
/**
* @param {Object} tabItem
*/
addTabItem: function(tabItem) {
this._tabItems.push(tabItem);
},
/**
* @return {Number} When active tab is not found, returns -1.
*/
getActiveTabIndex: function() {
var tabItem;
for (var i = 0; i < this._tabItems.length; i++) {
tabItem = this._tabItems[i];
if (tabItem.isActive()) {
return i;
}
}
return -1;
},
/**
* @param {String} page
* @param {Object} [options]
* @param {Object} [options.animation]
* @param {Object} [options.callback]
*/
loadPage: function(page, options) {
return this._loadPage(page, options);
},
/**
* @param {String} page
* @param {Object} [options]
* @param {Object} [options.animation]
*/
_loadPage: function(page, options) {
$onsen.getPageHTMLAsync(page).then(function(html) {
var pageElement = angular.element(html.trim());
this._loadPageDOM(pageElement, options);
}.bind(this), function() {
throw new Error('Page is not found: ' + page);
});
},
/**
* @param {jqLite} element
* @param {Object} scope
* @param {Object} options
* @param {Object} options.animation
*/
_switchPage: function(element, options) {
if (this._currentPageElement) {
var oldPageElement = this._currentPageElement;
var oldPageScope = this._currentPageScope;
this._currentPageElement = element;
this._currentPageScope = element.data('_scope');
this._getAnimatorOption(options).apply(element, oldPageElement, function() {
if (options._removeElement) {
oldPageElement.remove();
oldPageScope.$destroy();
}
else {
oldPageElement.css('display', 'none');
}
if (options.callback instanceof Function) {
options.callback();
}
});
} else {
this._currentPageElement = element;
this._currentPageScope = element.data('_scope');
if (options.callback instanceof Function) {
options.callback();
}
}
},
/**
* @param {jqLite} element
* @param {Object} options
* @param {Object} options.animation
*/
_loadPageDOM: function(element, options) {
options = options || {};
var pageScope = this._scope.$new();
var link = $compile(element);
this._contentElement.append(element);
var pageContent = link(pageScope);
pageScope.$evalAsync();
this._switchPage(pageContent, options);
},
/**
* @param {jqLite} element
* @param {Object} options
* @param {Object} options.animation
*/
_loadPersistentPageDOM: function(element, options) {
options = options || {};
element.css('display', 'block');
this._switchPage(element, options);
},
/**
* @param {Object} options
* @param {String} [options.animation]
* @return {TabbarAnimator}
*/
_getAnimatorOption: function(options) {
var animationAttr = this._element.attr('animation') || 'default';
return TabbarView._animatorDict[options.animation || animationAttr] || TabbarView._animatorDict['default'];
},
_destroy: function() {
this.emit('destroy');
this._element = this._scope = this._attrs = null;
}
});
MicroEvent.mixin(TabbarView);
// Preset transition animators.
TabbarView._animatorDict = {
'default': new TabbarNoneAnimator(),
'none': new TabbarNoneAnimator(),
'fade': new TabbarFadeAnimator()
};
/**
* @param {String} name
* @param {NavigatorTransitionAnimator} animator
*/
TabbarView.registerAnimator = function(name, animator) {
if (!(animator instanceof TabbarAnimator)) {
throw new Error('"animator" param must be an instance of TabbarAnimator');
}
this._animatorDict[name] = animator;
};
return TabbarView;
}]);
})();
/**
* @ngdoc directive
* @id alert-dialog
* @name ons-alert-dialog
* @category dialog
* @modifier android
* [en]Display an Android style alert dialog.[/en]
* [ja]Androidライクなスタイルを表示します。[/ja]
* @description
* [en]Alert dialog that is displayed on top of the current screen.[/en]
* [ja]現在のスクリーンにアラートダイアログを表示します。[/ja]
* @codepen Qwwxyp
* @guide UsingAlert
* [en]Learn how to use the alert dialog.[/en]
* [ja]アラートダイアログの使い方の解説。[/ja]
* @seealso ons-dialog
* [en]ons-dialog component[/en]
* [ja]ons-dialogコンポーネント[/ja]
* @seealso ons-popover
* [en]ons-popover component[/en]
* [ja]ons-dialogコンポーネント[/ja]
* @seealso ons.notification
* [en]Using ons.notification utility functions.[/en]
* [ja]アラートダイアログを表示するには、ons.notificationオブジェクトのメソッドを使うこともできます。[/ja]
* @example
* <script>
* ons.ready(function() {
* ons.createAlertDialog('alert.html').then(function(alertDialog) {
* alertDialog.show();
* });
* });
* </script>
*
* <script type="text/ons-template" id="alert.html">
* <ons-alert-dialog animation="default" cancelable>
* <div class="alert-dialog-title">Warning!</div>
* <div class="alert-dialog-content">
* An error has occurred!
* </div>
* <div class="alert-dialog-footer">
* <button class="alert-dialog-button">OK</button>
* </div>
* </ons-alert-dialog>
* </script>
*/
/**
* @ngdoc event
* @name preshow
* @description
* [en]Fired just before the alert dialog is displayed.[/en]
* [ja]アラートダイアログが表示される直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.alertDialog
* [en]Alert dialog object.[/en]
* [ja]アラートダイアログのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Execute to stop the dialog from showing.[/en]
* [ja]この関数を実行すると、アラートダイアログの表示を止めます。[/ja]
*/
/**
* @ngdoc event
* @name postshow
* @description
* [en]Fired just after the alert dialog is displayed.[/en]
* [ja]アラートダイアログが表示された直後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.alertDialog
* [en]Alert dialog object.[/en]
* [ja]アラートダイアログのオブジェクト。[/ja]
*/
/**
* @ngdoc event
* @name prehide
* @description
* [en]Fired just before the alert dialog is hidden.[/en]
* [ja]アラートダイアログが隠れる直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.alertDialog
* [en]Alert dialog object.[/en]
* [ja]アラートダイアログのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Execute to stop the dialog from hiding.[/en]
* [ja]この関数を実行すると、アラートダイアログが閉じようとするのを止めます。[/ja]
*/
/**
* @ngdoc event
* @name posthide
* @description
* [en]Fired just after the alert dialog is hidden.[/en]
* [ja]アラートダイアログが隠れた後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.alertDialog
* [en]Alert dialog object.[/en]
* [ja]アラートダイアログのオブジェクト。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this alert dialog.[/en]
* [ja]このアラートダイアログを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the dialog.[/en]
* [ja]ダイアログの見た目を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name cancelable
* @description
* [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en]
* [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]If this attribute is set the dialog is disabled.[/en]
* [ja]この属性がある時、アラートダイアログはdisabled状態になります。[/ja]
*/
/**
* @ngdoc attribute
* @name animation
* @type {String}
* @default default
* @description
* [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en]
* [ja]ダイアログを表示する際のアニメーション名を指定します。デフォルトでは"none"か"default"が指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name mask-color
* @type {String}
* @default rgba(0, 0, 0, 0.2)
* @description
* [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en]
* [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-preshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en]
* [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prehide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en]
* [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en]
* [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-posthide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en]
* [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature show([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクトです。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "fade", "slide" and "none".[/en]
* [ja]アニメーション名を指定します。指定できるのは、"fade", "slide", "none"のいずれかです。[/ja]
* @param {Function} [options.callback]
* [en]Function to execute after the dialog has been revealed.[/en]
* [ja]ダイアログが表示され終わった時に呼び出されるコールバックを指定します。[/ja]
* @description
* [en]Show the alert dialog.[/en]
* [ja]ダイアログを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature hide([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "fade", "slide" and "none".[/en]
* [ja]アニメーション名を指定します。"fade", "slide", "none"のいずれかを指定します。[/ja]
* @param {Function} [options.callback]
* [en]Function to execute after the dialog has been hidden.[/en]
* [ja]このダイアログが閉じた時に呼び出されるコールバックを指定します。[/ja]
* @description
* [en]Hide the alert dialog.[/en]
* [ja]ダイアログを閉じます。[/ja]
*/
/**
* @ngdoc method
* @signature isShown()
* @description
* [en]Returns whether the dialog is visible or not.[/en]
* [ja]ダイアログが表示されているかどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is currently visible.[/en]
* [ja]ダイアログが表示されていればtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature destroy()
* @description
* [en]Destroy the alert dialog and remove it from the DOM tree.[/en]
* [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja]
*/
/**
* @ngdoc method
* @signature setCancelable(cancelable)
* @description
* [en]Define whether the dialog can be canceled by the user or not.[/en]
* [ja]アラートダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja]
* @param {Boolean} cancelable
* [en]If true the dialog will be cancelable.[/en]
* [ja]キャンセルできるかどうかを真偽値で指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isCancelable()
* @description
* [en]Returns whether the dialog is cancelable or not.[/en]
* [ja]このアラートダイアログがキャンセル可能かどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is cancelable.[/en]
* [ja]キャンセル可能であればtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @description
* [en]Disable or enable the alert dialog.[/en]
* [ja]このアラートダイアログをdisabled状態にするかどうかを設定します。[/ja]
* @param {Boolean} disabled
* [en]If true the dialog will be disabled.[/en]
* [ja]disabled状態にするかどうかを真偽値で指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @description
* [en]Returns whether the dialog is disabled or enabled.[/en]
* [ja]このアラートダイアログがdisabled状態かどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is disabled.[/en]
* [ja]disabled状態であればtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火された際に呼び出されるコールバックを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出されるコールバックを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしlistenerパラメータが指定されなかった場合、そのイベントのリスナーが全て削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーの関数オブジェクトを渡します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
/**
* Alert dialog directive.
*/
module.directive('onsAlertDialog', ['$onsen', 'AlertDialogView', function($onsen, AlertDialogView) {
return {
restrict: 'E',
replace: false,
scope: true,
transclude: false,
compile: function(element, attrs) {
var modifierTemplater = $onsen.generateModifierTemplater(attrs);
element.addClass('alert-dialog ' + modifierTemplater('alert-dialog--*'));
var titleElement = angular.element(element[0].querySelector('.alert-dialog-title')),
contentElement = angular.element(element[0].querySelector('.alert-dialog-content'));
if (titleElement.length) {
titleElement.addClass(modifierTemplater('alert-dialog-title--*'));
}
if (contentElement.length) {
contentElement.addClass(modifierTemplater('alert-dialog-content--*'));
}
return {
pre: function(scope, element, attrs) {
var alertDialog = new AlertDialogView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, alertDialog);
$onsen.registerEventHandlers(alertDialog, 'preshow prehide postshow posthide destroy');
$onsen.addModifierMethods(alertDialog, 'alert-dialog--*', element);
if (titleElement.length) {
$onsen.addModifierMethods(alertDialog, 'alert-dialog-title--*', titleElement);
}
if (contentElement.length) {
$onsen.addModifierMethods(alertDialog, 'alert-dialog-content--*', contentElement);
}
if ($onsen.isAndroid()) {
alertDialog.addModifier('android');
}
element.data('ons-alert-dialog', alertDialog);
scope.$on('$destroy', function() {
alertDialog._events = undefined;
$onsen.removeModifierMethods(alertDialog);
element.data('ons-alert-dialog', undefined);
element = null;
});
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id back_button
* @name ons-back-button
* @category toolbar
* @description
* [en]Back button component for ons-toolbar. Can be used with ons-navigator to provide back button support.[/en]
* [ja]ons-toolbarに配置できる「戻るボタン」用コンポーネントです。ons-navigatorと共に使用し、ページを1つ前に戻る動作を行います。[/ja]
* @codepen aHmGL
* @seealso ons-toolbar
* [en]ons-toolbar component[/en]
* [ja]ons-toolbarコンポーネント[/ja]
* @seealso ons-navigator
* [en]ons-navigator component[/en]
* [ja]ons-navigatorコンポーネント[/en]
* @guide Addingatoolbar
* [en]Adding a toolbar[/en]
* [ja]ツールバーの追加[/ja]
* @guide Returningfromapage
* [en]Returning from a page[/en]
* [ja]一つ前のページに戻る[/ja]
* @example
* <ons-back-button>
* Back
* </ons-back-button>
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsBackButton', ['$onsen', '$compile', 'GenericView', 'ComponentCleaner', function($onsen, $compile, GenericView, ComponentCleaner) {
return {
restrict: 'E',
replace: false,
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/back_button.tpl',
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: true,
scope: true,
link: {
pre: function(scope, element, attrs, controller, transclude) {
var backButton = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, backButton);
element.data('ons-back-button', backButton);
scope.$on('$destroy', function() {
backButton._events = undefined;
$onsen.removeModifierMethods(backButton);
element.data('ons-back-button', undefined);
element = null;
});
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
var navigator = ons.findParentComponentUntil('ons-navigator', element);
scope.$watch(function() { return navigator.pages.length; }, function(nbrOfPages) {
scope.showBackButton = nbrOfPages > 1;
});
$onsen.addModifierMethods(backButton, 'toolbar-button--*', element.children());
transclude(scope, function(clonedElement) {
if (clonedElement[0]) {
element[0].querySelector('.back-button__label').appendChild(clonedElement[0]);
}
});
ComponentCleaner.onDestroy(scope, function() {
ComponentCleaner.destroyScope(scope);
ComponentCleaner.destroyAttributes(attrs);
element = null;
scope = null;
attrs = null;
});
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
}
};
}]);
})();
/**
* @ngdoc directive
* @id bottom_toolbar
* @name ons-bottom-toolbar
* @category toolbar
* @description
* [en]Toolbar component that is positioned at the bottom of the page.[/en]
* [ja]ページ下部に配置されるツールバー用コンポーネントです。[/ja]
* @modifier transparent
* [en]Make the toolbar transparent.[/en]
* [ja]ツールバーの背景を透明にして表示します。[/ja]
* @seealso ons-toolbar [en]ons-toolbar component[/en][ja]ons-toolbarコンポーネント[/ja]
* @guide Addingatoolbar
* [en]Adding a toolbar[/en]
* [ja]ツールバーの追加[/ja]
* @example
* <ons-bottom-toolbar>
* <div style="text-align: center; line-height: 44px">Text</div>
* </ons-bottom-toolbar>
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the toolbar.[/en]
* [ja]ツールバーの見た目の表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name inline
* @description
* [en]Display the toolbar as an inline element.[/en]
* [ja]この属性があると、ツールバーを画面下部ではなくスクロール領域内にそのまま表示します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsBottomToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclde.
transclude: false,
scope: false,
compile: function(element, attrs) {
var modifierTemplater = $onsen.generateModifierTemplater(attrs),
inline = typeof attrs.inline !== 'undefined';
element.addClass('bottom-bar');
element.addClass(modifierTemplater('bottom-bar--*'));
element.css({'z-index': 0});
if (inline) {
element.css('position', 'static');
}
return {
pre: function(scope, element, attrs) {
var bottomToolbar = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, bottomToolbar);
element.data('ons-bottomToolbar', bottomToolbar);
scope.$on('$destroy', function() {
bottomToolbar._events = undefined;
$onsen.removeModifierMethods(bottomToolbar);
element.data('ons-bottomToolbar', undefined);
element = null;
});
$onsen.addModifierMethods(bottomToolbar, 'bottom-bar--*', element);
var pageView = element.inheritedData('ons-page');
if (pageView && !inline) {
pageView.registerBottomToolbar(element);
}
},
post: function(scope, element, attrs) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id button
* @name ons-button
* @category form
* @modifier outline
* [en]Button with outline and transparent background[/en]
* [ja]アウトラインを持ったボタンを表示します。[/ja]
* @modifier light
* [en]Button that doesn't stand out.[/en]
* [ja]目立たないボタンを表示します。[/ja]
* @modifier quiet
* [en]Button with no outline and or background..[/en]
* [ja]枠線や背景が無い文字だけのボタンを表示します。[/ja]
* @modifier cta
* [en]Button that really stands out.[/en]
* [ja]目立つボタンを表示します。[/ja]
* @modifier large
* [en]Large button that covers the width of the screen.[/en]
* [ja]横いっぱいに広がる大きなボタンを表示します。[/ja]
* @modifier large--quiet
* [en]Large quiet button.[/en]
* [ja]横いっぱいに広がるquietボタンを表示します。[/ja]
* @modifier large--cta
* [en]Large call to action button.[/en]
* [ja]横いっぱいに広がるctaボタンを表示します。[/ja]
* @description
* [en]Button component. If you want to place a button in a toolbar, use ons-toolbar-button or ons-back-button instead.[/en]
* [ja]ボタン用コンポーネント。ツールバーにボタンを設置する場合は、ons-toolbar-buttonもしくはons-back-buttonコンポーネントを使用します。[/ja]
* @codepen hLayx
* @guide Button [en]Guide for ons-button[/en][ja]ons-buttonの使い方[/ja]
* @guide OverridingCSSstyles [en]More details about modifier attribute[/en][ja]modifier属性の使い方[/ja]
* @example
* <ons-button modifier="large--cta">
* Tap Me
* </ons-button>
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the button.[/en]
* [ja]ボタンの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name should-spin
* @type {Boolean}
* @description
* [en]Specify if the button should have a spinner. [/en]
* [ja]ボタンにスピナーを表示する場合に指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name animation
* @type {String}
* @description
* [en]The animation when the button transitions to and from the spinner. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in".[/en]
* [ja]スピナーを表示する場合のアニメーションを指定します。"slide-left" (デフォルト), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in"のいずれかを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]Specify if button should be disabled.[/en]
* [ja]ボタンを無効化する場合は指定します。[/ja]
*/
/**
* @ngdoc method
* @signature startSpin()
* @description
* [en]Show spinner on the button.[/en]
* [ja]ボタンにスピナーを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature stopSpin()
* @description
* [en]Remove spinner from button.[/en]
* [ja]ボタンのスピナーを隠します。[/ja]
*/
/**
* @ngdoc method
* @signature isSpinning()
* @return {Boolean}
* [en]true if the button is spinning.[/en]
* [ja]spinしているかどうかを返します。[/ja]
* @description
* [en]Return whether the spinner is visible or not.[/en]
* [ja]ボタン内にスピナーが表示されているかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setSpinAnimation(animation)
* @description
* [en]Set spin animation. Possible values are "slide-left" (default), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in".[/en]
* [ja]スピナーを表示する場合のアニメーションを指定します。"slide-left" (デフォルト), "slide-right", "slide-up", "slide-down", "expand-left", "expand-right", "expand-up", "expand-down", "zoom-out", "zoom-in"のいずれかを指定します。[/ja]
* @param {String} animation
* [en]Animation name.[/en]
* [ja]アニメーション名を指定します。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @description
* [en]Disable or enable the button.[/en]
* [ja]このボタンをdisabled状態にするかどうかを設定します。[/ja]
* @param {String} disabled
* [en]If true the button will be disabled.[/en]
* [ja]disabled状態にするかどうかを真偽値で指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @return {Boolean}
* [en]true if the button is disabled.[/en]
* [ja]ボタンがdisabled状態になっているかどうかを返します。[/ja]
* @description
* [en]Returns whether the button is disabled or enabled.[/en]
* [ja]このボタンがdisabled状態かどうかを返します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsButton', ['$onsen', 'ButtonView', function($onsen, ButtonView) {
return {
restrict: 'E',
replace: false,
transclude: true,
scope: {
animation: '@',
},
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/button.tpl',
link: function(scope, element, attrs, _, transclude) {
var button = new ButtonView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, button);
element.data('ons-button', button);
scope.$on('$destroy', function() {
button._events = undefined;
$onsen.removeModifierMethods(button);
element.data('ons-button', undefined);
element = null;
});
var initialAnimation = 'slide-left';
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
element.addClass('button effeckt-button');
element.addClass(scope.modifierTemplater('button--*'));
element.addClass(initialAnimation);
$onsen.addModifierMethods(button, 'button--*', element);
transclude(scope.$parent, function(cloned) {
angular.element(element[0].querySelector('.ons-button-inner')).append(cloned);
});
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
scope.item = {};
// if animation is not specified -> default is slide-left
scope.item.animation = initialAnimation;
scope.$watch('animation', function(newAnimation) {
if (newAnimation) {
if (scope.item.animation) {
element.removeClass(scope.item.animation);
}
scope.item.animation = newAnimation;
element.addClass(scope.item.animation);
}
});
attrs.$observe('shouldSpin', function(shouldSpin) {
if (shouldSpin === 'true') {
element.attr('data-loading', true);
} else {
element.removeAttr('data-loading');
}
});
$onsen.cleaner.onDestroy(scope, function() {
$onsen.clearComponent({
scope: scope,
attrs: attrs,
element: element
});
scope = element = attrs = null;
});
$onsen.fireComponentEvent(element[0], 'init');
}
};
}]);
})();
/**
* @ngdoc directive
* @id carousel
* @name ons-carousel
* @category carousel
* @description
* [en]Carousel component.[/en]
* [ja]カルーセルを表示できるコンポーネント。[/ja]
* @codepen xbbzOQ
* @guide UsingCarousel
* [en]Learn how to use the carousel component.[/en]
* [ja]carouselコンポーネントの使い方[/ja]
* @example
* <ons-carousel style="width: 100%; height: 200px">
* <ons-carousel-item>
* ...
* </ons-carousel-item>
* <ons-carousel-item>
* ...
* </ons-carousel-item>
* </ons-carousel>
*/
/**
* @ngdoc event
* @name postchange
* @description
* [en]Fired just after the current carousel item has changed.[/en]
* [ja]現在表示しているカルーセルの要素が変わった時に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.carousel
* [en]Carousel object.[/en]
* [ja]イベントが発火したCarouselオブジェクトです。[/ja]
* @param {Number} event.activeIndex
* [en]Current active index.[/en]
* [ja]現在アクティブになっている要素のインデックス。[/ja]
* @param {Number} event.lastActiveIndex
* [en]Previous active index.[/en]
* [ja]以前アクティブだった要素のインデックス。[/ja]
*/
/**
* @ngdoc event
* @name refresh
* @description
* [en]Fired when the carousel has been refreshed.[/en]
* [ja]カルーセルが更新された時に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.carousel
* [en]Carousel object.[/en]
* [ja]イベントが発火したCarouselオブジェクトです。[/ja]
*/
/**
* @ngdoc event
* @name overscroll
* @description
* [en]Fired when the carousel has been overscrolled.[/en]
* [ja]カルーセルがオーバースクロールした時に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.carousel
* [en]Fired when the carousel has been refreshed.[/en]
* [ja]カルーセルが更新された時に発火します。[/ja]
* @param {Number} event.activeIndex
* [en]Current active index.[/en]
* [ja]現在アクティブになっている要素のインデックス。[/ja]
* @param {String} event.direction
* [en]Can be one of either "up", "down", "left" or "right".[/en]
* [ja]オーバースクロールされた方向が得られます。"up", "down", "left", "right"のいずれかの方向が渡されます。[/ja]
* @param {Function} event.waitToReturn
* [en]Takes a <code>Promise</code> object as an argument. The carousel will not scroll back until the promise has been resolved or rejected.[/en]
* [ja]この関数はPromiseオブジェクトを引数として受け取ります。渡したPromiseオブジェクトがresolveされるかrejectされるまで、カルーセルはスクロールバックしません。[/ja]
*/
/**
* @ngdoc attribute
* @name direction
* @type {String}
* @description
* [en]The direction of the carousel. Can be either "horizontal" or "vertical". Default is "horizontal".[/en]
* [ja]カルーセルの方向を指定します。"horizontal"か"vertical"を指定できます。"horizontal"がデフォルト値です。[/ja]
*/
/**
* @ngdoc attribute
* @name fullscreen
* @description
* [en]If this attribute is set the carousel will cover the whole screen.[/en]
* [ja]この属性があると、absoluteポジションを使ってカルーセルが自動的に画面いっぱいに広がります。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this carousel.[/en]
* [ja]このカルーセルを参照するための変数名を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name overscrollable
* @description
* [en]If this attribute is set the carousel will be scrollable over the edge. It will bounce back when released.[/en]
* [ja]この属性がある時、タッチやドラッグで端までスクロールした時に、バウンドするような効果が当たります。[/ja]
*/
/**
* @ngdoc attribute
* @name item-width
* @type {String}
* @description
* [en]ons-carousel-item's width. Only works when the direction is set to "horizontal".[/en]
* [ja]ons-carousel-itemの幅を指定します。この属性は、direction属性に"horizontal"を指定した時のみ有効になります。[/ja]
*/
/**
* @ngdoc attribute
* @name item-height
* @type {String}
* @description
* [en]ons-carousel-item's height. Only works when the direction is set to "vertical".[/en]
* [ja]ons-carousel-itemの高さを指定します。この属性は、direction属性に"vertical"を指定した時のみ有効になります。[/ja]
*/
/**
* @ngdoc attribute
* @name auto-scroll
* @description
* [en]If this attribute is set the carousel will be automatically scrolled to the closest item border when released.[/en]
* [ja]この属性がある時、一番近いcarosel-itemの境界まで自動的にスクロールするようになります。[/ja]
*/
/**
* @ngdoc attribute
* @name auto-scroll-ratio
* @type {Number}
* @description
* [en]A number between 0.0 and 1.0 that specifies how much the user must drag the carousel in order for it to auto scroll to the next item.[/en]
* [ja]0.0から1.0までの値を指定します。カルーセルの要素をどれぐらいの割合までドラッグすると次の要素に自動的にスクロールするかを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name swipeable
* @description
* [en]If this attribute is set the carousel can be scrolled by drag or swipe.[/en]
* [ja]この属性がある時、カルーセルをスワイプやドラッグで移動できるようになります。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]If this attribute is set the carousel is disabled.[/en]
* [ja]この属性がある時、dragやtouchやswipeを受け付けなくなります。[/ja]
*/
/**
* @ngdoc attribute
* @name intial-index
* @type {Number}
* @description
* [en]Specify the index of the ons-carousel-item to show initially. Default is 0.[/en]
* [ja]最初に表示するons-carousel-itemを0始まりのインデックスで指定します。デフォルト値は 0 です。[/ja]
*/
/**
* @ngdoc attribute
* @name auto-refresh
* @description
* [en]When this attribute is set the carousel will automatically refresh when the number of child nodes change.[/en]
* [ja]この属性がある時、子要素の数が変わるとカルーセルは自動的に更新されるようになります。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postchange
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en]
* [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-refresh
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "refresh" event is fired.[/en]
* [ja]"refresh"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-overscroll
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "overscroll" event is fired.[/en]
* [ja]"overscroll"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature next()
* @description
* [en]Show next ons-carousel item.[/en]
* [ja]次のons-carousel-itemを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature prev()
* @description
* [en]Show previous ons-carousel item.[/en]
* [ja]前のons-carousel-itemを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature first()
* @description
* [en]Show first ons-carousel item.[/en]
* [ja]最初のons-carousel-itemを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature last()
* @description
* [en]Show last ons-carousel item.[/en]
* [ja]最後のons-carousel-itemを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature setSwipeable(swipeable)
* @param {Booelan} swipeable
* [en]If value is true the carousel will be swipeable.[/en]
* [ja]swipeableにする場合にはtrueを指定します。[/ja]
* @description
* [en]Set whether the carousel is swipeable or not.[/en]
* [ja]swipeできるかどうかを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isSwipeable()
* @return {Boolean}
* [en]true if the carousel is swipeable.[/en]
* [ja]swipeableであればtrueを返します。[/ja]
* @description
* [en]Returns whether the carousel is swipeable or not.[/en]
* [ja]swiapble属性があるかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setActiveCarouselItemIndex(index)
* @param {Number} index
* [en]The index that the carousel should be set to.[/en]
* [ja]carousel要素のインデックスを指定します。[/ja]
* @description
* [en]Specify the index of the ons-carousel-item to show.[/en]
* [ja]表示するons-carousel-itemをindexで指定します。[/ja]
*/
/**
* @ngdoc method
* @signature getActiveCarouselItemIndex()
* @return {Number}
* [en]The current carousel item index.[/en]
* [ja]現在表示しているカルーセル要素のインデックスが返されます。[/ja]
* @description
* [en]Returns the index of the currently visible ons-carousel-item.[/en]
* [ja]現在表示されているons-carousel-item要素のインデックスを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setAutoScrollEnabled(enabled)
* @param {Boolean} enabled
* [en]If true auto scroll will be enabled.[/en]
* [ja]オートスクロールを有効にする場合にはtrueを渡します。[/ja]
* @description
* [en]Enable or disable "auto-scroll" attribute.[/en]
* [ja]auto-scroll属性があるかどうかを設定します。[/ja]
*/
/**
* @ngdoc method
* @signature isAutoScrollEnabled()
* @return {Boolean}
* [en]true if auto scroll is enabled.[/en]
* [ja]オートスクロールが有効であればtrueを返します。[/ja]
* @description
* [en]Returns whether the "auto-scroll" attribute is set or not.[/en]
* [ja]auto-scroll属性があるかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setAutoScrollRatio(ratio)
* @param {Number} ratio
* [en]The desired ratio.[/en]
* [ja]オートスクロールするのに必要な0.0から1.0までのratio値を指定します。[/ja]
* @description
* [en]Set the auto scroll ratio. Must be a value between 0.0 and 1.0.[/en]
* [ja]オートスクロールするのに必要なratio値を指定します。0.0から1.0を必ず指定しなければならない。[/ja]
*/
/**
* @ngdoc method
* @signature getAutoScrollRatio()
* @return {Number}
* [en]The current auto scroll ratio.[/en]
* [ja]現在のオートスクロールのratio値。[/ja]
* @description
* [en]Returns the current auto scroll ratio.[/en]
* [ja]現在のオートスクロールのratio値を返します。[/ja]
*/
/**
* @ngdoc method
* @signature setOverscrollable(overscrollable)
* @param {Boolean} overscrollable
* [en]If true the carousel will be overscrollable.[/en]
* [ja]overscrollできるかどうかを指定します。[/ja]
* @description
* [en]Set whether the carousel is overscrollable or not.[/en]
* [ja]overscroll属性があるかどうかを設定します。[/ja]
*/
/**
* @ngdoc method
* @signature isOverscrollable()
* @return {Boolean}
* [en]Whether the carousel is overscrollable or not.[/en]
* [ja]overscrollできればtrueを返します。[/ja]
* @description
* [en]Returns whether the carousel is overscrollable or not.[/en]
* [ja]overscroll属性があるかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature refresh()
* @description
* [en]Update the layout of the carousel. Used when adding ons-carousel-items dynamically or to automatically adjust the size.[/en]
* [ja]レイアウトや内部の状態を最新のものに更新します。ons-carousel-itemを動的に増やしたり、ons-carouselの大きさを動的に変える際に利用します。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @return {Boolean}
* [en]Whether the carousel is disabled or not.[/en]
* [ja]disabled状態になっていればtrueを返します。[/ja]
* @description
* [en]Returns whether the dialog is disabled or enabled.[/en]
* [ja]disabled属性があるかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @param {Boolean} disabled
* [en]If true the carousel will be disabled.[/en]
* [ja]disabled状態にする場合にはtrueを指定します。[/ja]
* @description
* [en]Disable or enable the dialog.[/en]
* [ja]disabled属性があるかどうかを設定します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsCarousel', ['$onsen', 'CarouselView', function($onsen, CarouselView) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
scope: false,
transclude: false,
compile: function(element, attrs) {
var templater = $onsen.generateModifierTemplater(attrs);
element.addClass(templater('carousel--*'));
return function(scope, element, attrs) {
var carousel = new CarouselView(scope, element, attrs);
element.data('ons-carousel', carousel);
$onsen.registerEventHandlers(carousel, 'postchange refresh overscroll destroy');
$onsen.declareVarAttribute(attrs, carousel);
scope.$on('$destroy', function() {
carousel._events = undefined;
element.data('ons-carousel', undefined);
element = null;
});
if (element[0].hasAttribute('auto-refresh')) {
// Refresh carousel when items are added or removed.
scope.$watch(
function () {
return element[0].childNodes.length;
},
function () {
setImmediate(function() {
carousel.refresh();
});
}
);
}
setImmediate(function() {
carousel.refresh();
});
$onsen.fireComponentEvent(element[0], 'init');
};
},
};
}]);
module.directive('onsCarouselItem', ['$onsen', function($onsen) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
scope: false,
transclude: false,
compile: function(element, attrs) {
var templater = $onsen.generateModifierTemplater(attrs);
element.addClass(templater('carousel-item--*'));
element.css('width', '100%');
return function(scope, element, attrs) {
};
},
};
}]);
})();
/**
* @ngdoc directive
* @id col
* @name ons-col
* @category grid
* @description
* [en]Represents a column in the grid system. Use with ons-row to layout components.[/en]
* [ja]グリッドシステムにて列を定義します。ons-rowとともに使用し、コンポーネントのレイアウトに利用します。[/ja]
* @note
* [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-column, they may not be displayed correctly. You can use only one align.[/en]
* [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-columnを組み合わせた場合に描画が崩れる場合があります。[/ja]
* @codepen GgujC {wide}
* @guide layouting [en]Layouting guide[/en][ja]レイアウト機能[/ja]
* @seealso ons-row [en]ons-row component[/en][ja]ons-rowコンポーネント[/ja]
* @example
* <ons-row>
* <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col>
* <ons-col>Text</ons-col>
* </ons-row>
*/
/**
* @ngdoc attribute
* @name align
* @type {String}
* @description
* [en]Vertical alignment of the column. Valid values are "top", "center", and "bottom".[/en]
* [ja]縦の配置を指定する。"top", "center", "bottom"のいずれかを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name width
* @type {String}
* @description
* [en]The width of the column. Valid values are css width values ("10%", "50px").[/en]
* [ja]カラムの横幅を指定する。パーセントもしくはピクセルで指定します(10%や50px)。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsCol', ['$timeout', '$onsen', function($timeout, $onsen) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: false,
compile: function(element, attrs, transclude) {
element.addClass('col ons-col-inner');
return function(scope, element, attrs) {
attrs.$observe('align', function(align) {
updateAlign(align);
});
attrs.$observe('width', function(width) {
updateWidth(width);
});
// For BC
attrs.$observe('size', function(size) {
if (!attrs.width) {
updateWidth(size);
}
});
updateAlign(attrs.align);
if (attrs.size && !attrs.width) {
updateWidth(attrs.size);
} else {
updateWidth(attrs.width);
}
$onsen.cleaner.onDestroy(scope, function() {
$onsen.clearComponent({
scope: scope,
element: element,
attrs: attrs
});
element = attrs = scope = null;
});
function updateAlign(align) {
if (align === 'top' || align === 'center' || align === 'bottom') {
element.removeClass('col-top col-center col-bottom');
element.addClass('col-' + align);
} else {
element.removeClass('col-top col-center col-bottom');
}
}
function updateWidth(width) {
if (typeof width === 'string') {
width = ('' + width).trim();
width = width.match(/^\d+$/) ? width + '%' : width;
element.css({
'-webkit-box-flex': '0',
'-webkit-flex': '0 0 ' + width,
'-moz-box-flex': '0',
'-moz-flex': '0 0 ' + width,
'-ms-flex': '0 0 ' + width,
'flex': '0 0 ' + width,
'max-width': width
});
} else {
element.removeAttr('style');
}
}
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id dialog
* @name ons-dialog
* @category dialog
* @description
* [en]Dialog that is displayed on top of current screen.[/en]
* [ja]現在のスクリーンにダイアログを表示します。[/ja]
* @codepen zxxaGa
* @guide UsingDialog
* [en]Learn how to use the dialog component.[/en]
* [ja]ダイアログコンポーネントの使い方[/ja]
* @seealso ons-alert-dialog
* [en]ons-alert-dialog component[/en]
* [ja]ons-alert-dialogコンポーネント[/ja]
* @seealso ons-popover
* [en]ons-popover component[/en]
* [ja]ons-popoverコンポーネント[/ja]
* @example
* <script>
* ons.ready(function() {
* ons.createDialog('dialog.html').then(function(dialog) {
* dialog.show();
* });
* });
* </script>
*
* <script type="text/ons-template" id="dialog.html">
* <ons-dialog cancelable>
* ...
* </ons-dialog>
* </script>
*/
/**
* @ngdoc event
* @name preshow
* @description
* [en]Fired just before the dialog is displayed.[/en]
* [ja]ダイアログが表示される直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.dialog
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Execute this function to stop the dialog from being shown.[/en]
* [ja]この関数を実行すると、ダイアログの表示がキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name postshow
* @description
* [en]Fired just after the dialog is displayed.[/en]
* [ja]ダイアログが表示された直後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.dialog
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
*/
/**
* @ngdoc event
* @name prehide
* @description
* [en]Fired just before the dialog is hidden.[/en]
* [ja]ダイアログが隠れる直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.dialog
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Execute this function to stop the dialog from being hidden.[/en]
* [ja]この関数を実行すると、ダイアログの非表示がキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name posthide
* @description
* [en]Fired just after the dialog is hidden.[/en]
* [ja]ダイアログが隠れた後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.dialog
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this dialog.[/en]
* [ja]このダイアログを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the dialog.[/en]
* [ja]ダイアログの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name cancelable
* @description
* [en]If this attribute is set the dialog can be closed by tapping the background or by pressing the back button.[/en]
* [ja]この属性があると、ダイアログが表示された時に、背景やバックボタンをタップした時にダイアログを閉じます。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]If this attribute is set the dialog is disabled.[/en]
* [ja]この属性がある時、ダイアログはdisabled状態になります。[/ja]
*/
/**
* @ngdoc attribute
* @name animation
* @type {String}
* @default default
* @description
* [en]The animation used when showing and hiding the dialog. Can be either "none" or "default".[/en]
* [ja]ダイアログを表示する際のアニメーション名を指定します。"none"もしくは"default"を指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name mask-color
* @type {String}
* @default rgba(0, 0, 0, 0.2)
* @description
* [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en]
* [ja]背景のマスクの色を指定します。"rgba(0, 0, 0, 0.2)"がデフォルト値です。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-preshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en]
* [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prehide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en]
* [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en]
* [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-posthide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en]
* [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature show([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "none", "fade" and "slide".[/en]
* [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja]
* @param {Function} [options.callback]
* [en]This function is called after the dialog has been revealed.[/en]
* [ja]ダイアログが表示され終わった後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Show the dialog.[/en]
* [ja]ダイアログを開きます。[/ja]
*/
/**
* @ngdoc method
* @signature hide([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "none", "fade" and "slide".[/en]
* [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja]
* @param {Function} [options.callback]
* [en]This functions is called after the dialog has been hidden.[/en]
* [ja]ダイアログが隠れた後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Hide the dialog.[/en]
* [ja]ダイアログを閉じます。[/ja]
*/
/**
* @ngdoc method
* @signature isShown()
* @description
* [en]Returns whether the dialog is visible or not.[/en]
* [ja]ダイアログが表示されているかどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is visible.[/en]
* [ja]ダイアログが表示されている場合にtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature destroy()
* @description
* [en]Destroy the dialog and remove it from the DOM tree.[/en]
* [ja]ダイアログを破棄して、DOMツリーから取り除きます。[/ja]
*/
/**
* @ngdoc method
* @signature getDeviceBackButtonHandler()
* @return {Object}
* [en]Device back button handler.[/en]
* [ja]デバイスのバックボタンハンドラを返します。[/ja]
* @description
* [en]Retrieve the back button handler for overriding the default behavior.[/en]
* [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja]
*/
/**
* @ngdoc method
* @signature setCancelable(cancelable)
* @param {Boolean} cancelable
* [en]If true the dialog will be cancelable.[/en]
* [ja]ダイアログをキャンセル可能にする場合trueを指定します。[/ja]
* @description
* [en]Define whether the dialog can be canceled by the user or not.[/en]
* [ja]ダイアログを表示した際に、ユーザがそのダイアログをキャンセルできるかどうかを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isCancelable()
* @description
* [en]Returns whether the dialog is cancelable or not.[/en]
* [ja]このダイアログがキャンセル可能かどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is cancelable.[/en]
* [ja]ダイアログがキャンセル可能な場合trueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @description
* [en]Disable or enable the dialog.[/en]
* [ja]このダイアログをdisabled状態にするかどうかを設定します。[/ja]
* @param {Boolean} disabled
* [en]If true the dialog will be disabled.[/en]
* [ja]trueを指定するとダイアログをdisabled状態になります。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @description
* [en]Returns whether the dialog is disabled or enabled.[/en]
* [ja]このダイアログがdisabled状態かどうかを返します。[/ja]
* @return {Boolean}
* [en]true if the dialog is disabled.[/en]
* [ja]ダイアログがdisabled状態の場合trueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーが指定されなかった場合には、そのイベントに紐付いているイベントリスナーが全て削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
/**
* Dialog directive.
*/
module.directive('onsDialog', ['$onsen', 'DialogView', function($onsen, DialogView) {
return {
restrict: 'E',
replace: false,
scope: true,
transclude: true,
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/dialog.tpl',
compile: function(element, attrs, transclude) {
element[0].setAttribute('no-status-bar-fill', '');
return {
pre: function(scope, element, attrs) {
transclude(scope, function(clone) {
angular.element(element[0].querySelector('.dialog')).append(clone);
});
var dialog = new DialogView(scope, element, attrs);
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
$onsen.addModifierMethods(dialog, 'dialog--*', angular.element(element[0].querySelector('.dialog')));
$onsen.declareVarAttribute(attrs, dialog);
$onsen.registerEventHandlers(dialog, 'preshow prehide postshow posthide destroy');
element.data('ons-dialog', dialog);
scope.$on('$destroy', function() {
dialog._events = undefined;
$onsen.removeModifierMethods(dialog);
element.data('ons-dialog', undefined);
element = null;
});
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsDummyForInit', ['$rootScope', function($rootScope) {
var isReady = false;
return {
restrict: 'E',
replace: false,
link: {
post: function(scope, element) {
if (!isReady) {
isReady = true;
$rootScope.$broadcast('$ons-ready');
}
element.remove();
}
}
};
}]);
})();
/**
* @ngdoc directive
* @id gestureDetector
* @name ons-gesture-detector
* @category input
* @description
* [en]Component to detect finger gestures within the wrapped element. See the guide for more details.[/en]
* [ja]要素内のジェスチャー操作を検知します。詳しくはガイドを参照してください。[/ja]
* @guide DetectingFingerGestures
* [en]Detecting finger gestures[/en]
* [ja]ジェスチャー操作の検知[/ja]
* @example
* <ons-gesture-detector>
* ...
* </ons-gesture-detector>
*/
(function() {
'use strict';
var EVENTS =
('drag dragleft dragright dragup dragdown hold release swipe swipeleft swiperight ' +
'swipeup swipedown tap doubletap touch transform pinch pinchin pinchout rotate').split(/ +/);
angular.module('onsen').directive('onsGestureDetector', ['$onsen', function($onsen) {
var scopeDef = EVENTS.reduce(function(dict, name) {
dict['ng' + titlize(name)] = '&';
return dict;
}, {});
return {
restrict: 'E',
scope: scopeDef,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
replace: false,
transclude: true,
compile: function(element, attrs) {
return function link(scope, element, attrs, controller, transclude) {
transclude(scope.$parent, function(cloned) {
element.append(cloned);
});
var hammer = new Hammer(element[0]);
hammer.on(EVENTS.join(' '), handleEvent);
$onsen.cleaner.onDestroy(scope, function() {
hammer.off(EVENTS.join(' '), handleEvent);
$onsen.clearComponent({
scope: scope,
element: element,
attrs: attrs
});
hammer.element = scope = element = attrs = null;
});
function handleEvent(event) {
var attr = 'ng' + titlize(event.type);
if (attr in scopeDef) {
scope[attr]({$event: event});
}
}
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
function titlize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}]);
})();
/**
* @ngdoc directive
* @id icon
* @name ons-icon
* @category icon
* @description
* [en]Displays an icon. Font Awesome and Ionicon icons are supported.[/en]
* [ja]アイコンを表示するコンポーネントです。Font AwesomeもしくはIoniconsから選択できます。[/ja]
* @codepen xAhvg
* @guide UsingIcons [en]Using icons[/en][ja]アイコンを使う[/ja]
* @example
* <ons-icon
* icon="fa-twitter"
* size="20px"
* fixed-width="false"
* style="color: red">
* </ons-icon>
*/
/**
* @ngdoc attribute
* @name icon
* @type {String}
* @description
* [en]The icon name. <code>fa-</code> prefix for Font Awesome, <code>ion-</code> prefix for Ionicons icons. See all icons at http://fontawesome.io/icons/ and http://ionicons.com.[/en]
* [ja]アイコン名を指定します。<code>fa-</code>で始まるものはFont Awesomeとして、<code>ion-</code>で始まるものはIoniconsとして扱われます。使用できるアイコンはこちら: http://fontawesome.io/icons/ および http://ionicons.com。[/ja]
*/
/**
* @ngdoc attribute
* @name size
* @type {String}
* @description
* [en]The sizes of the icon. Valid values are lg, 2x, 3x, 4x, 5x, or in pixels.[/en]
* [ja]アイコンのサイズを指定します。値は、lg, 2x, 3x, 4x, 5xもしくはピクセル単位で指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name rotate
* @type {Number}
* @description
* [en]Number of degrees to rotate the icon. Valid values are 90, 180, or 270.[/en]
* [ja]アイコンを回転して表示します。90, 180, 270から指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name flip
* @type {String}
* @description
* [en]Flip the icon. Valid values are "horizontal" and "vertical".[/en]
* [ja]アイコンを反転します。horizontalもしくはverticalを指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name fixed-width
* @type {Boolean}
* @default false
* @description
* [en]When used in the list, you want the icons to have the same width so that they align vertically by setting the value to true. Valid values are true, false. Default is false.[/en]
* [ja]等幅にするかどうかを指定します。trueもしくはfalseを指定できます。デフォルトはfalseです。[/ja]
*/
/**
* @ngdoc attribute
* @name spin
* @type {Boolean}
* @default false
* @description
* [en]Specify whether the icon should be spinning. Valid values are true and false.[/en]
* [ja]アイコンを回転するかどうかを指定します。trueもしくはfalseを指定できます。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
function cleanClassAttribute(element) {
var classList = ('' + element.attr('class')).split(/ +/).filter(function(classString) {
return classString !== 'fa' && classString.substring(0, 3) !== 'fa-' && classString.substring(0, 4) !== 'ion-';
});
element.attr('class', classList.join(' '));
}
function buildClassAndStyle(attrs) {
var classList = ['ons-icon'];
var style = {};
// icon
if (attrs.icon.indexOf('ion-') === 0) {
classList.push(attrs.icon);
classList.push('ons-icon--ion');
} else if (attrs.icon.indexOf('fa-') === 0) {
classList.push(attrs.icon);
classList.push('fa');
} else {
classList.push('fa');
classList.push('fa-' + attrs.icon);
}
// size
var size = '' + attrs.size;
if (size.match(/^[1-5]x|lg$/)) {
classList.push('fa-' + size);
} else if (typeof attrs.size === 'string') {
style['font-size'] = size;
} else {
classList.push('fa-lg');
}
return {
'class': classList.join(' '),
'style': style
};
}
module.directive('onsIcon', ['$onsen', function($onsen) {
return {
restrict: 'E',
replace: false,
transclude: false,
link: function(scope, element, attrs) {
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
var update = function() {
cleanClassAttribute(element);
var builded = buildClassAndStyle(attrs);
element.css(builded.style);
element.addClass(builded['class']);
};
var builded = buildClassAndStyle(attrs);
element.css(builded.style);
element.addClass(builded['class']);
attrs.$observe('icon', update);
attrs.$observe('size', update);
attrs.$observe('fixedWidth', update);
attrs.$observe('rotate', update);
attrs.$observe('flip', update);
attrs.$observe('spin', update);
$onsen.cleaner.onDestroy(scope, function() {
$onsen.clearComponent({
scope: scope,
element: element,
attrs: attrs
});
element = scope = attrs = null;
});
$onsen.fireComponentEvent(element[0], 'init');
}
};
}]);
})();
/**
* @ngdoc directive
* @id if-orientation
* @name ons-if-orientation
* @category util
* @description
* [en]Conditionally display content depending on screen orientation. Valid values are portrait and landscape. Different from other components, this component is used as attribute in any element.[/en]
* [ja]画面の向きに応じてコンテンツの制御を行います。portraitもしくはlandscapeを指定できます。すべての要素の属性に使用できます。[/ja]
* @seealso ons-if-platform [en]ons-if-platform component[/en][ja]ons-if-platformコンポーネント[/ja]
* @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja]
* @example
* <div ons-if-orientation="portrait">
* <p>This will only be visible in portrait mode.</p>
* </div>
*/
/**
* @ngdoc attribute
* @name ons-if-orientation
* @type {String}
* @description
* [en]Either "portrait" or "landscape".[/en]
* [ja]portraitもしくはlandscapeを指定します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsIfOrientation', ['$onsen', '$onsGlobal', function($onsen, $onsGlobal) {
return {
restrict: 'A',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: false,
compile: function(element) {
element.css('display', 'none');
return function(scope, element, attrs) {
element.addClass('ons-if-orientation-inner');
attrs.$observe('onsIfOrientation', update);
$onsGlobal.orientation.on('change', update);
update();
$onsen.cleaner.onDestroy(scope, function() {
$onsGlobal.orientation.off('change', update);
$onsen.clearComponent({
element: element,
scope: scope,
attrs: attrs
});
element = scope = attrs = null;
});
function update() {
var userOrientation = ('' + attrs.onsIfOrientation).toLowerCase();
var orientation = getLandscapeOrPortrait();
if (userOrientation === 'portrait' || userOrientation === 'landscape') {
if (userOrientation === orientation) {
element.css('display', '');
} else {
element.css('display', 'none');
}
}
}
function getLandscapeOrPortrait() {
return $onsGlobal.orientation.isPortrait() ? 'portrait' : 'landscape';
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id if-platform
* @name ons-if-platform
* @category util
* @description
* [en]Conditionally display content depending on the platform / browser. Valid values are "ios", "android", "blackberry", "chrome", "safari", "firefox", and "opera".[/en]
* [ja]プラットフォームやブラウザーに応じてコンテンツの制御をおこないます。ios, android, blackberry, chrome, safari, firefox, operaを指定できます。[/ja]
* @seealso ons-if-orientation [en]ons-if-orientation component[/en][ja]ons-if-orientationコンポーネント[/ja]
* @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja]
* @example
* <div ons-if-platform="android">
* ...
* </div>
*/
/**
* @ngdoc attribute
* @name ons-if-platform
* @type {String}
* @description
* [en]Either "opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios" or "windows".[/en]
* [ja]"opera", "firefox", "safari", "chrome", "ie", "android", "blackberry", "ios", "windows"のいずれかを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsIfPlatform', ['$onsen', function($onsen) {
return {
restrict: 'A',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: false,
compile: function(element) {
element.addClass('ons-if-platform-inner');
element.css('display', 'none');
var platform = getPlatformString();
return function(scope, element, attrs) {
attrs.$observe('onsIfPlatform', function(userPlatform) {
if (userPlatform) {
update();
}
});
update();
$onsen.cleaner.onDestroy(scope, function() {
$onsen.clearComponent({
element: element,
scope: scope,
attrs: attrs
});
element = scope = attrs = null;
});
function update() {
if (attrs.onsIfPlatform.toLowerCase() === platform.toLowerCase()) {
element.css('display', 'block');
} else {
element.css('display', 'none');
}
}
};
function getPlatformString() {
if (navigator.userAgent.match(/Android/i)) {
return 'android';
}
if ((navigator.userAgent.match(/BlackBerry/i)) || (navigator.userAgent.match(/RIM Tablet OS/i)) || (navigator.userAgent.match(/BB10/i))) {
return 'blackberry';
}
if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
return 'ios';
}
if (navigator.userAgent.match(/IEMobile/i)) {
return 'windows';
}
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
if (isOpera) {
return 'opera';
}
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
if (isFirefox) {
return 'firefox';
}
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
if (isSafari) {
return 'safari';
}
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
if (isChrome) {
return 'chrome';
}
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
if (isIE) {
return 'ie';
}
return 'unknown';
}
}
};
}]);
})();
/**
* @ngdoc directive
* @id ons-keyboard-active
* @name ons-keyboard-active
* @category input
* @description
* [en]
* Conditionally display content depending on if the software keyboard is visible or hidden.
* This component requires cordova and that the com.ionic.keyboard plugin is installed.
* [/en]
* [ja]
* ソフトウェアキーボードが表示されているかどうかで、コンテンツを表示するかどうかを切り替えることが出来ます。
* このコンポーネントは、Cordovaやcom.ionic.keyboardプラグインを必要とします。
* [/ja]
* @guide UtilityAPIs
* [en]Other utility APIs[/en]
* [ja]他のユーティリティAPI[/ja]
* @example
* <div ons-keyboard-active>
* This will only be displayed if the software keyboard is open.
* </div>
* <div ons-keyboard-inactive>
* There is also a component that does the opposite.
* </div>
*/
/**
* @ngdoc attribute
* @name ons-keyboard-active
* @description
* [en]The content of tags with this attribute will be visible when the software keyboard is open.[/en]
* [ja]この属性がついた要素は、ソフトウェアキーボードが表示された時に初めて表示されます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-keyboard-inactive
* @description
* [en]The content of tags with this attribute will be visible when the software keyboard is hidden.[/en]
* [ja]この属性がついた要素は、ソフトウェアキーボードが隠れている時のみ表示されます。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
var compileFunction = function(show, $onsen) {
return function(element) {
return function(scope, element, attrs) {
var dispShow = show ? 'block' : 'none',
dispHide = show ? 'none' : 'block';
var onShow = function() {
element.css('display', dispShow);
};
var onHide = function() {
element.css('display', dispHide);
};
var onInit = function(e) {
if (e.visible) {
onShow();
} else {
onHide();
}
};
ons.softwareKeyboard.on('show', onShow);
ons.softwareKeyboard.on('hide', onHide);
ons.softwareKeyboard.on('init', onInit);
if (ons.softwareKeyboard._visible) {
onShow();
} else {
onHide();
}
$onsen.cleaner.onDestroy(scope, function() {
ons.softwareKeyboard.off('show', onShow);
ons.softwareKeyboard.off('hide', onHide);
ons.softwareKeyboard.off('init', onInit);
$onsen.clearComponent({
element: element,
scope: scope,
attrs: attrs
});
element = scope = attrs = null;
});
};
};
};
module.directive('onsKeyboardActive', ['$onsen', function($onsen) {
return {
restrict: 'A',
replace: false,
transclude: false,
scope: false,
compile: compileFunction(true, $onsen)
};
}]);
module.directive('onsKeyboardInactive', ['$onsen', function($onsen) {
return {
restrict: 'A',
replace: false,
transclude: false,
scope: false,
compile: compileFunction(false, $onsen)
};
}]);
})();
/**
* @ngdoc directive
* @id lazy-repeat
* @name ons-lazy-repeat
* @category control
* @description
* [en]
* Using this component a list with millions of items can be rendered without a drop in performance.
* It does that by "lazily" loading elements into the DOM when they come into view and
* removing items from the DOM when they are not visible.
* [/en]
* [ja]
* このコンポーネント内で描画されるアイテムのDOM要素の読み込みは、画面に見えそうになった時まで自動的に遅延され、
* 画面から見えなくなった場合にはその要素は動的にアンロードされます。
* このコンポーネントを使うことで、パフォーマンスを劣化させること無しに巨大な数の要素を描画できます。
* [/ja]
* @codepen QwrGBm
* @guide UsingLazyRepeat
* [en]How to use Lazy Repeat[/en]
* [ja]レイジーリピートの使い方[/ja]
* @example
* <script>
* ons.bootstrap()
*
* .controller('MyController', function($scope) {
* $scope.MyDelegate = {
* countItems: function() {
* // Return number of items.
* return 1000000;
* },
*
* calculateItemHeight: function(index) {
* // Return the height of an item in pixels.
* return 45;
* },
*
* configureItemScope: function(index, itemScope) {
* // Initialize scope
* itemScope.item = 'Item #' + (index + 1);
* },
*
* destroyItemScope: function(index, itemScope) {
* // Optional method that is called when an item is unloaded.
* console.log('Destroyed item with index: ' + index);
* }
* };
* });
* </script>
*
* <ons-list ng-controller="MyController">
* <ons-list-item ons-lazy-repeat="MyDelegate">
* {{ item }}
* </ons-list-item>
* </ons-list>
*/
/**
* @ngdoc attribute
* @name ons-lazy-repeat
* @type {Expression}
* @description
* [en]A delegate object, can be either an object attached to the scope (when using AngularJS) or a normal JavaScript variable.[/en]
* [ja]要素のロード、アンロードなどの処理を委譲するオブジェクトを指定します。AngularJSのスコープの変数名や、通常のJavaScriptの変数名を指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
/**
* Lazy repeat directive.
*/
module.directive('onsLazyRepeat', ['$onsen', 'LazyRepeatView', function($onsen, LazyRepeatView) {
return {
restrict: 'A',
replace: false,
priority: 1000,
transclude: 'element',
compile: function(element, attrs, linker) {
return function(scope, element, attrs) {
var lazyRepeat = new LazyRepeatView(scope, element, attrs, linker);
scope.$on('$destroy', function() {
scope = element = attrs = linker = null;
});
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id list
* @name ons-list
* @category list
* @modifier inset
* [en]Inset list that doesn't cover the whole width of the parent.[/en]
* [ja]親要素の画面いっぱいに広がらないリストを表示します。[/ja]
* @modifier noborder
* [en]A list with no borders at the top and bottom.[/en]
* [ja]リストの上下のボーダーが無いリストを表示します。[/ja]
* @description
* [en]Component to define a list, and the container for ons-list-item(s).[/en]
* [ja]リストを表現するためのコンポーネント。ons-list-itemのコンテナとして使用します。[/ja]
* @seealso ons-list-item
* [en]ons-list-item component[/en]
* [ja]ons-list-itemコンポーネント[/ja]
* @seealso ons-list-header
* [en]ons-list-header component[/en]
* [ja]ons-list-headerコンポーネント[/ja]
* @guide UsingList
* [en]Using lists[/en]
* [ja]リストを使う[/ja]
* @codepen yxcCt
* @example
* <ons-list>
* <ons-list-header>Header Text</ons-list-header>
* <ons-list-item>Item</ons-list-item>
* <ons-list-item>Item</ons-list-item>
* </ons-list>
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the list.[/en]
* [ja]リストの表現を指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsList', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
scope: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
replace: false,
transclude: false,
compile: function(element, attrs) {
return function(scope, element, attrs) {
var list = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, list);
element.data('ons-list', list);
scope.$on('$destroy', function() {
list._events = undefined;
$onsen.removeModifierMethods(list);
element.data('ons-list', undefined);
element = null;
});
var templater = $onsen.generateModifierTemplater(attrs);
element.addClass('list ons-list-inner');
element.addClass(templater('list--*'));
$onsen.addModifierMethods(list, 'list--*', element);
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id list-header
* @name ons-list-header
* @category list
* @description
* [en]Header element for list items. Must be put inside ons-list component.[/en]
* [ja]リスト要素に使用するヘッダー用コンポーネント。ons-listと共に使用します。[/ja]
* @seealso ons-list
* [en]ons-list component[/en]
* [ja]ons-listコンポーネント[/ja]
* @seealso ons-list-item [en]ons-list-item component[/en][ja]ons-list-itemコンポーネント[/ja]
* @guide UsingList [en]Using lists[/en][ja]リストを使う[/ja]
* @codepen yxcCt
* @example
* <ons-list>
* <ons-list-header>Header Text</ons-list-header>
* <ons-list-item>Item</ons-list-item>
* <ons-list-item>Item</ons-list-item>
* </ons-list>
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the list header.[/en]
* [ja]ヘッダーの表現を指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsListHeader', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
replace: false,
transclude: false,
compile: function() {
return function(scope, element, attrs) {
var listHeader = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, listHeader);
element.data('ons-listHeader', listHeader);
scope.$on('$destroy', function() {
listHeader._events = undefined;
$onsen.removeModifierMethods(listHeader);
element.data('ons-listHeader', undefined);
element = null;
});
var templater = $onsen.generateModifierTemplater(attrs);
element.addClass('list__header ons-list-header-inner');
element.addClass(templater('list__header--*'));
$onsen.addModifierMethods(listHeader, 'list__header--*', element);
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id list-item
* @name ons-list-item
* @category list
* @modifier tappable
* [en]Made the list item change appearance when it's tapped.[/en]
* [ja]タップやクリックした時に効果が表示されるようになります。[/ja]
* @modifier chevron
* [en]Display a chevron at the right end of the list item and make it change appearance when tapped.[/en]
* [ja]要素の右側に右矢印が表示されます。また、タップやクリックした時に効果が表示されるようになります。[/ja]
* @description
* [en]Component that represents each item in the list. Must be put inside the ons-list component.[/en]
* [ja]リストの各要素を表現するためのコンポーネントです。ons-listコンポーネントと共に使用します。[/ja]
* @seealso ons-list
* [en]ons-list component[/en]
* [ja]ons-listコンポーネント[/ja]
* @seealso ons-list-header
* [en]ons-list-header component[/en]
* [ja]ons-list-headerコンポーネント[/ja]
* @guide UsingList
* [en]Using lists[/en]
* [ja]リストを使う[/ja]
* @codepen yxcCt
* @example
* <ons-list>
* <ons-list-header>Header Text</ons-list-header>
* <ons-list-item>Item</ons-list-item>
* <ons-list-item>Item</ons-list-item>
* </ons-list>
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the list item.[/en]
* [ja]各要素の表現を指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsListItem', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
replace: false,
transclude: false,
compile: function() {
return function(scope, element, attrs) {
var listItem = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, listItem);
element.data('ons-list-item', listItem);
scope.$on('$destroy', function() {
listItem._events = undefined;
$onsen.removeModifierMethods(listItem);
element.data('ons-list-item', undefined);
element = null;
});
var templater = $onsen.generateModifierTemplater(attrs);
element.addClass('list__item ons-list-item-inner');
element.addClass(templater('list__item--*'));
$onsen.addModifierMethods(listItem, 'list__item--*', element);
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id loading-placeholder
* @name ons-loading-placeholder
* @category util
* @description
* [en]Display a placeholder while the content is loading.[/en]
* [ja]Onsen UIが読み込まれるまでに表示するプレースホルダーを表現します。[/ja]
* @guide UtilityAPIs [en]Other utility APIs[/en][ja]他のユーティリティAPI[/ja]
* @example
* <div ons-loading-placeholder="page.html">
* Loading...
* </div>
*/
/**
* @ngdoc attribute
* @name ons-loading-placeholder
* @type {String}
* @description
* [en]The url of the page to load.[/en]
* [ja]読み込むページのURLを指定します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsLoadingPlaceholder', ['$onsen', '$compile', function($onsen, $compile) {
return {
restrict: 'A',
replace: false,
transclude: false,
scope: false,
link: function(scope, element, attrs) {
if (!attrs.onsLoadingPlaceholder.length) {
throw Error('Must define page to load.');
}
setImmediate(function() {
$onsen.getPageHTMLAsync(attrs.onsLoadingPlaceholder).then(function(html) {
// Remove page tag.
html = html
.trim()
.replace(/^<ons-page>/, '')
.replace(/<\/ons-page>$/, '');
var div = document.createElement('div');
div.innerHTML = html;
var newElement = angular.element(div);
newElement.css('display', 'none');
element.append(newElement);
$compile(newElement)(scope);
for (var i = element[0].childNodes.length - 1; i >= 0; i--){
var e = element[0].childNodes[i];
if (e !== div) {
element[0].removeChild(e);
}
}
newElement.css('display', 'block');
});
});
}
};
}]);
})();
/**
* @ngdoc directive
* @id modal
* @name ons-modal
* @category modal
* @description
* [en]
* Modal component that masks current screen.
* Underlying components are not subject to any events while the modal component is shown.
* [/en]
* [ja]
* 画面全体をマスクするモーダル用コンポーネントです。下側にあるコンポーネントは、
* モーダルが表示されている間はイベント通知が行われません。
* [/ja]
* @guide UsingModal
* [en]Using ons-modal component[/en]
* [ja]モーダルの使い方[/ja]
* @guide CallingComponentAPIsfromJavaScript
* [en]Using navigator from JavaScript[/en]
* [ja]JavaScriptからコンポーネントを呼び出す[/ja]
* @codepen devIg
* @example
* <ons-modal>
* ...
* </ons-modal>
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this modal.[/en]
* [ja]このモーダルを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc method
* @signature toggle()
* @description
* [en]Toggle modal visibility.[/en]
* [ja]モーダルの表示を切り替えます。[/ja]
*/
/**
* @ngdoc method
* @signature show()
* @description
* [en]Show modal.[/en]
* [ja]モーダルを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature hide()
* @description
* [en]Hide modal.[/en]
* [ja]モーダルを非表示にします。[/ja]
*/
/**
* @ngdoc method
* @signature getDeviceBackButtonHandler()
* @return {Object}
* [en]Device back button handler.[/en]
* [ja]デバイスのバックボタンハンドラを返します。[/ja]
* @description
* [en]Retrieve the back button handler.[/en]
* [ja]ons-modalに紐付いているバックボタンハンドラを取得します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
/**
* Modal directive.
*/
module.directive('onsModal', ['$onsen', 'ModalView', function($onsen, ModalView) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclde.
scope: false,
transclude: false,
compile: function(element, attrs) {
compile(element, attrs);
return {
pre: function(scope, element, attrs) {
var page = element.inheritedData('ons-page');
if (page) {
page.registerExtraElement(element);
}
var modal = new ModalView(scope, element);
$onsen.addModifierMethods(modal, 'modal--*', element);
$onsen.addModifierMethods(modal, 'modal--*__content', element.children());
$onsen.declareVarAttribute(attrs, modal);
element.data('ons-modal', modal);
scope.$on('$destroy', function() {
modal._events = undefined;
$onsen.removeModifierMethods(modal);
element.data('ons-modal', undefined);
});
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
function compile(element, attrs) {
var modifierTemplater = $onsen.generateModifierTemplater(attrs);
var html = element[0].innerHTML;
element[0].innerHTML = '';
var wrapper = angular.element('<div></div>');
wrapper.addClass('modal__content');
wrapper.addClass(modifierTemplater('modal--*__content'));
element.css('display', 'none');
element.addClass('modal');
element.addClass(modifierTemplater('modal--*'));
wrapper[0].innerHTML = html;
element.append(wrapper);
}
}]);
})();
/**
* @ngdoc directive
* @id navigator
* @name ons-navigator
* @category navigation
* @description
* [en]A component that provides page stack management and navigation. This component does not have a visible content.[/en]
* [ja]ページスタックの管理とナビゲーション機能を提供するコンポーネント。画面上への出力はありません。[/ja]
* @codepen yrhtv
* @guide PageNavigation
* [en]Guide for page navigation[/en]
* [ja]ページナビゲーションの概要[/ja]
* @guide CallingComponentAPIsfromJavaScript
* [en]Using navigator from JavaScript[/en]
* [ja]JavaScriptからコンポーネントを呼び出す[/ja]
* @guide EventHandling
* [en]Event handling descriptions[/en]
* [ja]イベント処理の使い方[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @seealso ons-toolbar
* [en]ons-toolbar component[/en]
* [ja]ons-toolbarコンポーネント[/ja]
* @seealso ons-back-button
* [en]ons-back-button component[/en]
* [ja]ons-back-buttonコンポーネント[/ja]
* @example
* <ons-navigator animation="slide" var="app.navi">
* <ons-page>
* <ons-toolbar>
* <div class="center">Title</div>
* </ons-toolbar>
*
* <p style="text-align: center">
* <ons-button modifier="light" ng-click="app.navi.pushPage('page.html');">Push</ons-button>
* </p>
* </ons-page>
* </ons-navigator>
*
* <ons-template id="page.html">
* <ons-page>
* <ons-toolbar>
* <div class="center">Title</div>
* </ons-toolbar>
*
* <p style="text-align: center">
* <ons-button modifier="light" ng-click="app.navi.popPage('page.html');">Pop</ons-button>
* </p>
* </ons-page>
* </ons-template>
*/
/**
* @ngdoc event
* @name prepush
* @description
* [en]Fired just before a page is pushed.[/en]
* [ja]pageがpushされる直前に発火されます。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.navigator
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Object} event.currentPage
* [en]Current page object.[/en]
* [ja]現在のpageオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Call this function to cancel the push.[/en]
* [ja]この関数を呼び出すと、push処理がキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name prepop
* @description
* [en]Fired just before a page is popped.[/en]
* [ja]pageがpopされる直前に発火されます。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.navigator
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Object} event.currentPage
* [en]Current page object.[/en]
* [ja]現在のpageオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Call this function to cancel the pop.[/en]
* [ja]この関数を呼び出すと、pageのpopがキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name postpush
* @description
* [en]Fired just after a page is pushed.[/en]
* [ja]pageがpushされてアニメーションが終了してから発火されます。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.navigator
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Object} event.enterPage
* [en]Object of the next page.[/en]
* [ja]pushされたpageオブジェクト。[/ja]
* @param {Object} event.leavePage
* [en]Object of the previous page.[/en]
* [ja]以前のpageオブジェクト。[/ja]
*/
/**
* @ngdoc event
* @name postpop
* @description
* [en]Fired just after a page is popped.[/en]
* [ja]pageがpopされてアニメーションが終わった後に発火されます。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.navigator
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Object} event.enterPage
* [en]Object of the next page.[/en]
* [ja]popされて表示されるページのオブジェクト。[/ja]
* @param {Object} event.leavePage
* [en]Object of the previous page.[/en]
* [ja]popされて消えるページのオブジェクト。[/ja]
*/
/**
* @ngdoc attribute
* @name page
* @type {String}
* @description
* [en]First page to show when navigator is initialized.[/en]
* [ja]ナビゲーターが初期化された時に表示するページを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this navigator.[/en]
* [ja]このナビゲーターを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prepush
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prepush" event is fired.[/en]
* [ja]"prepush"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prepop
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prepop" event is fired.[/en]
* [ja]"prepop"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postpush
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postpush" event is fired.[/en]
* [ja]"postpush"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postpop
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postpop" event is fired.[/en]
* [ja]"postpop"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature pushPage(pageUrl, [options])
* @param {String} pageUrl
* [en]Page URL. Can be either a HTML document or a <code><ons-template></code>.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja]
* @param {Function} [options.onTransitionEnd]
* [en]Function that is called when the transition has ended.[/en]
* [ja]pushPage()による画面遷移が終了した時に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Pushes the specified pageUrl into the page stack.[/en]
* [ja]指定したpageUrlを新しいページスタックに追加します。新しいページが表示されます。[/ja]
*/
/**
* @ngdoc method
* @signature insertPage(index, pageUrl, [options])
* @param {Number} index
* [en]The index where it should be inserted.[/en]
* [ja]スタックに挿入する位置のインデックスを指定します。[/ja]
* @param {String} pageUrl
* [en]Page URL. Can be either a HTML document or a <code><ons-template></code>.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja]
* @description
* [en]Insert the specified pageUrl into the page stack with specified index.[/en]
* [ja]指定したpageUrlをページスタックのindexで指定した位置に追加します。[/ja]
*/
/**
* @ngdoc method
* @signature popPage([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja]
* @param {Function} [options.onTransitionEnd]
* [en]Function that is called when the transition has ended.[/en]
* [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Pops the current page from the page stack. The previous page will be displayed.[/en]
* [ja]現在表示中のページをページスタックから取り除きます。一つ前のページに戻ります。[/ja]
*/
/**
* @ngdoc method
* @signature replacePage(pageUrl, [options])
* @param {String} pageUrl
* [en]Page URL. Can be either a HTML document or an <code><ons-template></code>.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en]
* [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja]
* @param {Function} [options.onTransitionEnd]
* [en]Function that is called when the transition has ended.[/en]
* [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Replaces the current page with the specified one.[/en]
* [ja]現在表示中のページをを指定したページに置き換えます。[/ja]
*/
/**
* @ngdoc method
* @signature resetToPage(pageUrl, [options])
* @param {String} pageUrl
* [en]Page URL. Can be either a HTML document or an <code><ons-template></code>.[/en]
* [ja]pageのURLか、もしくはons-templateで宣言したテンプレートのid属性の値を指定できます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "slide", "simpleslide", "lift", "fade" and "none".[/en]
* [ja]アニメーション名を指定できます。"slide", "simpleslide", "lift", "fade", "none"のいずれかを指定できます。[/ja]
* @param {Function} [options.onTransitionEnd]
* [en]Function that is called when the transition has ended.[/en]
* [ja]このメソッドによる画面遷移が終了した際に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Clears page stack and adds the specified pageUrl to the page stack.[/en]
* [ja]ページスタックをリセットし、指定したページを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature getCurrentPage()
* @return {Object}
* [en]Current page object.[/en]
* [ja]現在のpageオブジェクト。[/ja]
* @description
* [en]Get current page's navigator item. Use this method to access options passed by pushPage() or resetToPage() method.[/en]
* [ja]現在のページを取得します。pushPage()やresetToPage()メソッドの引数を取得できます。[/ja]
*/
/**
* @ngdoc method
* @signature getPages()
* @return {List}
* [en]List of page objects.[/en]
* [ja]pageオブジェクトの配列。[/ja]
* @description
* [en]Retrieve the entire page stack of the navigator.[/en]
* [ja]ナビゲーターの持つページスタックの一覧を取得します。[/ja]
*/
/**
* @ngdoc method
* @signature getDeviceBackButtonHandler()
* @return {Object}
* [en]Device back button handler.[/en]
* [ja]デバイスのバックボタンハンドラを返します。[/ja]
* @description
* [en]Retrieve the back button handler for overriding the default behavior.[/en]
* [ja]バックボタンハンドラを取得します。デフォルトの挙動を変更することができます。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsNavigator', ['$compile', 'NavigatorView', '$onsen', function($compile, NavigatorView, $onsen) {
return {
restrict: 'E',
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: true,
compile: function(element) {
var html = $onsen.normalizePageHTML(element.html());
element.contents().remove();
return {
pre: function(scope, element, attrs, controller) {
var navigator = new NavigatorView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, navigator);
$onsen.registerEventHandlers(navigator, 'prepush prepop postpush postpop destroy');
if (attrs.page) {
navigator.pushPage(attrs.page, {});
} else {
var pageScope = navigator._createPageScope();
var pageElement = angular.element(html);
var linkScope = $compile(pageElement);
var link = function() {
linkScope(pageScope);
};
navigator._pushPageDOM('', pageElement, link, pageScope, {});
pageElement = null;
}
element.data('ons-navigator', navigator);
scope.$on('$destroy', function() {
navigator._events = undefined;
element.data('ons-navigator', undefined);
element = null;
});
},
post: function(scope, element, attrs) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id page
* @name ons-page
* @category base
* @description
* [en]Should be used as root component of each page. The content inside page component is scrollable.[/en]
* [ja]ページ定義のためのコンポーネントです。このコンポーネントの内容はスクロールが許可されます。[/ja]
* @guide ManagingMultiplePages
* [en]Managing multiple pages[/en]
* [ja]複数のページを管理する[/ja]
* @guide Pageinitevent
* [en]Event for page initialization[/en]
* [ja]ページ初期化のイベント[/ja]
* @guide HandlingBackButton
* [en]Handling back button[/en]
* [ja]バックボタンに対応する[/ja]
* @guide OverridingCSSstyles
* [en]Overriding CSS styles[/en]
* [ja]CSSスタイルのオーバーライド[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @example
* <ons-page>
* <ons-toolbar>
* <div class="center">Title</div>
* </ons-toolbar>
*
* ...
* </ons-page>
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this page.[/en]
* [ja]このページを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]Specify modifier name to specify custom styles.[/en]
* [ja]スタイル定義をカスタマイズするための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name on-device-backbutton
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the back button is pressed.[/en]
* [ja]デバイスのバックボタンが押された時の挙動を設定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ng-device-backbutton
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior with an AngularJS expression when the back button is pressed.[/en]
* [ja]デバイスのバックボタンが押された時の挙動を設定できます。AngularJSのexpressionを指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature getDeviceBackButtonHandler()
* @return {Object}
* [en]Device back button handler.[/en]
* [ja]デバイスのバックボタンハンドラを返します。[/ja]
* @description
* [en]Get the associated back button handler. This method may return null if no handler is assigned.[/en]
* [ja]バックボタンハンドラを取得します。このメソッドはnullを返す場合があります。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsPage', ['$onsen', 'PageView', function($onsen, PageView) {
function firePageInitEvent(element) {
// TODO: remove dirty fix
var i = 0;
var f = function() {
if (i++ < 5) {
if (isAttached(element)) {
fillStatusBar(element);
$onsen.fireComponentEvent(element, 'init');
fireActualPageInitEvent(element);
} else {
setImmediate(f);
}
} else {
throw new Error('Fail to fire "pageinit" event. Attach "ons-page" element to the document after initialization.');
}
};
f();
}
function fireActualPageInitEvent(element) {
var event = document.createEvent('HTMLEvents');
event.initEvent('pageinit', true, true);
element.dispatchEvent(event);
}
function fillStatusBar(element) {
if ($onsen.shouldFillStatusBar(element)) {
// Adjustments for IOS7
var fill = angular.element(document.createElement('div'));
fill.addClass('page__status-bar-fill');
fill.css({width: '0px', height: '0px'});
angular.element(element).prepend(fill);
}
}
function isAttached(element) {
if (document.documentElement === element) {
return true;
}
return element.parentNode ? isAttached(element.parentNode) : false;
}
function preLink(scope, element, attrs, controller, transclude) {
var page = new PageView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, page);
element.data('ons-page', page);
var modifierTemplater = $onsen.generateModifierTemplater(attrs),
template = 'page--*';
element.addClass('page ' + modifierTemplater(template));
$onsen.addModifierMethods(page, template, element);
var pageContent = angular.element(element[0].querySelector('.page__content'));
pageContent.addClass(modifierTemplater('page--*__content'));
pageContent = null;
var pageBackground = angular.element(element[0].querySelector('.page__background'));
pageBackground.addClass(modifierTemplater('page--*__background'));
pageBackground = null;
element.data('_scope', scope);
$onsen.cleaner.onDestroy(scope, function() {
element.data('_scope', undefined);
page._events = undefined;
$onsen.removeModifierMethods(page);
element.data('ons-page', undefined);
$onsen.clearComponent({
element: element,
scope: scope,
attrs: attrs
});
scope = element = attrs = null;
});
}
function postLink(scope, element, attrs) {
firePageInitEvent(element[0]);
}
return {
restrict: 'E',
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclde.
transclude: false,
scope: false,
compile: function(element) {
var children = element.children().remove();
var content = angular.element('<div class="page__content ons-page-inner"></div>').append(children);
var background = angular.element('<div class="page__background"></div>');
if (element.attr('style')) {
background.attr('style', element.attr('style'));
element.attr('style', '');
}
element.append(background);
if (Modernizr.csstransforms3d) {
element.append(content);
} else {
content.css('overflow', 'visible');
var wrapper = angular.element('<div></div>');
wrapper.append(children);
content.append(wrapper);
element.append(content);
wrapper = null;
// IScroll for Android2
var scroller = new IScroll(content[0], {
momentum: true,
bounce: true,
hScrollbar: false,
vScrollbar: false,
preventDefault: false
});
var offset = 10;
scroller.on('scrollStart', function(e) {
var scrolled = scroller.y - offset;
if (scrolled < (scroller.maxScrollY + 40)) {
// TODO: find a better way to know when content is upated so we can refresh
scroller.refresh();
}
});
}
content = null;
background = null;
children = null;
return {
pre: preLink,
post: postLink
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id popover
* @name ons-popover
* @category popover
* @modifier android
* [en]Display an Android style popover.[/en]
* [ja]Androidライクなポップオーバーを表示します。[/ja]
* @description
* [en]A component that displays a popover next to an element.[/en]
* [ja]ある要素を対象とするポップオーバーを表示するコンポーネントです。[/ja]
* @codepen ZYYRKo
* @example
* <script>
* ons.ready(function() {
* ons.createPopover('popover.html').then(function(popover) {
* popover.show('#mybutton');
* });
* });
* </script>
*
* <script type="text/ons-template" id="popover.html">
* <ons-popover cancelable>
* <p style="text-align: center; opacity: 0.5;">This popover will choose which side it's displayed on automatically.</p>
* </ons-popover>
* </script>
*/
/**
* @ngdoc event
* @name preshow
* @description
* [en]Fired just before the popover is displayed.[/en]
* [ja]ポップオーバーが表示される直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.popover
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Call this function to stop the popover from being shown.[/en]
* [ja]この関数を呼び出すと、ポップオーバーの表示がキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name postshow
* @description
* [en]Fired just after the popover is displayed.[/en]
* [ja]ポップオーバーが表示された直後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.popover
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
*/
/**
* @ngdoc event
* @name prehide
* @description
* [en]Fired just before the popover is hidden.[/en]
* [ja]ポップオーバーが隠れる直前に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.popover
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Call this function to stop the popover from being hidden.[/en]
* [ja]この関数を呼び出すと、ポップオーバーが隠れる処理をキャンセルします。[/ja]
*/
/**
* @ngdoc event
* @name posthide
* @description
* [en]Fired just after the popover is hidden.[/en]
* [ja]ポップオーバーが隠れた後に発火します。[/ja]
* @param {Object} event [en]Event object.[/en]
* @param {Object} event.popover
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this popover.[/en]
* [ja]このポップオーバーを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the popover.[/en]
* [ja]ポップオーバーの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name direction
* @type {String}
* @description
* [en]
* A space separated list of directions. If more than one direction is specified,
* it will be chosen automatically. Valid directions are "up", "down", "left" and "right".
* [/en]
* [ja]
* ポップオーバーを表示する方向を空白区切りで複数指定できます。
* 指定できる方向は、"up", "down", "left", "right"の4つです。空白区切りで複数指定することもできます。
* 複数指定された場合、対象とする要素に合わせて指定した値から自動的に選択されます。
* [/ja]
*/
/**
* @ngdoc attribute
* @name cancelable
* @description
* [en]If this attribute is set the popover can be closed by tapping the background or by pressing the back button.[/en]
* [ja]この属性があると、ポップオーバーが表示された時に、背景やバックボタンをタップした時にをポップオーバー閉じます。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]If this attribute is set the popover is disabled.[/en]
* [ja]この属性がある時、ポップオーバーはdisabled状態になります。[/ja]
*/
/**
* @ngdoc attribute
* @name animation
* @type {String}
* @description
* [en]The animation used when showing an hiding the popover. Can be either "none" or "fade".[/en]
* [ja]ポップオーバーを表示する際のアニメーション名を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name mask-color
* @type {Color}
* @description
* [en]Color of the background mask. Default is "rgba(0, 0, 0, 0.2)".[/en]
* [ja]背景のマスクの色を指定します。デフォルトは"rgba(0, 0, 0, 0.2)"です。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-preshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "preshow" event is fired.[/en]
* [ja]"preshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prehide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prehide" event is fired.[/en]
* [ja]"prehide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postshow
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postshow" event is fired.[/en]
* [ja]"postshow"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-posthide
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "posthide" event is fired.[/en]
* [ja]"posthide"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature show(target, [options])
* @param {String|Event|HTMLElement} target
* [en]Target element. Can be either a CSS selector, an event object or a DOM element.[/en]
* [ja]ポップオーバーのターゲットとなる要素を指定します。CSSセレクタかeventオブジェクトかDOM要素のいずれかを渡せます。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja]
* @description
* [en]Open the popover and point it at a target. The target can be either an event, a css selector or a DOM element..[/en]
* [ja]対象とする要素にポップオーバーを表示します。target引数には、$eventオブジェクトやDOMエレメントやCSSセレクタを渡すことが出来ます。[/ja]
*/
/**
* @ngdoc method
* @signature hide([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"fade"もしくは"none"を指定できます。[/ja]
* @description
* [en]Close the popover.[/en]
* [ja]ポップオーバーを閉じます。[/ja]
*/
/**
* @ngdoc method
* @signature isShown()
* @return {Boolean}
* [en]true if the popover is visible.[/en]
* [ja]ポップオーバーが表示されている場合にtrueとなります。[/ja]
* @description
* [en]Returns whether the popover is visible or not.[/en]
* [ja]ポップオーバーが表示されているかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature destroy()
* @description
* [en]Destroy the popover and remove it from the DOM tree.[/en]
* [ja]ポップオーバーを破棄して、DOMツリーから取り除きます。[/ja]
*/
/**
* @ngdoc method
* @signature setCancelable(cancelable)
* @param {Boolean} cancelable
* [en]If true the popover will be cancelable.[/en]
* [ja]ポップオーバーがキャンセル可能にしたい場合にtrueを指定します。[/ja]
* @description
* [en]Set whether the popover can be canceled by the user when it is shown.[/en]
* [ja]ポップオーバーを表示した際に、ユーザがそのポップオーバーをキャンセルできるかどうかを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isCancelable()
* @return {Boolean}
* [en]true if the popover is cancelable.[/en]
* [ja]ポップオーバーがキャンセル可能であればtrueとなります。[/ja]
* @description
* [en]Returns whether the popover is cancelable or not.[/en]
* [ja]このポップオーバーがキャンセル可能かどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @param {Boolean} disabled
* [en]If true the popover will be disabled.[/en]
* [ja]ポップオーバーをdisabled状態にしたい場合にはtrueを指定します。[/ja]
* @description
* [en]Disable or enable the popover.[/en]
* [ja]このポップオーバーをdisabled状態にするかどうかを設定します。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @return {Boolean}
* [en]true if the popover is disabled.[/en]
* [ja]ポップオーバーがdisabled状態であればtrueとなります。[/ja]
* @description
* [en]Returns whether the popover is disabled or enabled.[/en]
* [ja]このポップオーバーがdisabled状態かどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsPopover', ['$onsen', 'PopoverView', function($onsen, PopoverView) {
return {
restrict: 'E',
replace: false,
transclude: true,
scope: true,
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/popover.tpl',
compile: function(element, attrs, transclude) {
return {
pre: function(scope, element, attrs) {
transclude(scope, function(clone) {
angular.element(element[0].querySelector('.popover__content')).append(clone);
});
var popover = new PopoverView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, popover);
$onsen.registerEventHandlers(popover, 'preshow prehide postshow posthide destroy');
element.data('ons-popover', popover);
scope.$on('$destroy', function() {
popover._events = undefined;
$onsen.removeModifierMethods(popover);
element.data('ons-popover', undefined);
element = null;
});
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
$onsen.addModifierMethods(popover, 'popover--*', angular.element(element[0].querySelector('.popover')));
$onsen.addModifierMethods(popover, 'popover__content--*', angular.element(element[0].querySelector('.popover__content')));
if ($onsen.isAndroid()) {
setImmediate(function() {
popover.addModifier('android');
});
}
scope.direction = 'up';
scope.arrowPosition = 'bottom';
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id pull-hook
* @name ons-pull-hook
* @category control
* @description
* [en]Component that adds "pull-to-refresh" to an <ons-page> element.[/en]
* [ja]ons-page要素以下でいわゆるpull to refreshを実装するためのコンポーネントです。[/ja]
* @codepen WbJogM
* @guide UsingPullHook
* [en]How to use Pull Hook[/en]
* [ja]プルフックを使う[/ja]
* @example
* <script>
* ons.bootstrap()
*
* .controller('MyController', function($scope, $timeout) {
* $scope.items = [3, 2 ,1];
*
* $scope.load = function($done) {
* $timeout(function() {
* $scope.items.unshift($scope.items.length + 1);
* $done();
* }, 1000);
* };
* });
* </script>
*
* <ons-page ng-controller="MyController">
* <ons-pull-hook var="loaded" ng-action="load($done)">
* <span ng-switch="loader.getCurrentState()">
* <span ng-switch-when="initial">Pull down to refresh</span>
* <span ng-switch-when="preaction">Release to refresh</span>
* <span ng-switch-when="action">Loading data. Please wait...</span>
* </span>
* </ons-pull-hook>
* <ons-list>
* <ons-list-item ng-repeat="item in items">
* Item #{{ item }}
* </ons-list-item>
* </ons-list>
* </ons-page>
*/
/**
* @ngdoc event
* @name changestate
* @description
* [en]Fired when the state is changed. The state can be either "initial", "preaction" or "action".[/en]
* [ja]コンポーネントの状態が変わった場合に発火します。状態は、"initial", "preaction", "action"のいずれかです。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.pullHook
* [en]Component object.[/en]
* [ja]コンポーネントのオブジェクト。[/ja]
* @param {String} event.state
* [en]Current state.[/en]
* [ja]現在の状態名を参照できます。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this component.[/en]
* [ja]このコンポーネントを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]If this attribute is set the "pull-to-refresh" functionality is disabled.[/en]
* [ja]この属性がある時、disabled状態になりアクションが実行されなくなります[/ja]
*/
/**
* @ngdoc attribute
* @name ng-action
* @type {Expression}
* @description
* [en]Use to specify custom behavior when the page is pulled down. A <code>$done</code> function is available to tell the component that the action is completed.[/en]
* [ja]pull downしたときの振る舞いを指定します。アクションが完了した時には<code>$done</code>関数を呼び出します。[/ja]
*/
/**
* @ngdoc attribute
* @name on-action
* @type {Expression}
* @description
* [en]Same as <code>ng-action</code> but can be used without AngularJS. A function called <code>done</code> is available to call when action is complete.[/en]
* [ja]<code>ng-action</code>と同じですが、AngularJS無しで利用する場合に利用できます。アクションが完了した時には<code>done</code>関数を呼び出します。[/ja]
*/
/**
* @ngdoc attribute
* @name height
* @type {String}
* @description
* [en]Specify the height of the component. When pulled down further than this value it will switch to the "preaction" state. The default value is "64px".[/en]
* [ja]コンポーネントの高さを指定します。この高さ以上にpull downすると"preaction"状態に移行します。デフォルトの値は"64px"です。[/ja]
*/
/**
* @ngdoc attribute
* @name threshold-height
* @type {String}
* @description
* [en]Specify the threshold height. The component automatically switches to the "action" state when pulled further than this value. The default value is "96px". A negative value or a value less than the height will disable this property.[/en]
* [ja]閾値となる高さを指定します。この値で指定した高さよりもpull downすると、このコンポーネントは自動的に"action"状態に移行します。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-changestate
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "changestate" event is fired.[/en]
* [ja]"changestate"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature setDisabled(disabled)
* @param {Boolean} disabled
* [en]If true the pull hook will be disabled.[/en]
* [ja]trueを指定すると、プルフックがdisabled状態になります。[/ja]
* @description
* [en]Disable or enable the component.[/en]
* [ja]disabled状態にするかどうかを設定できます。[/ja]
*/
/**
* @ngdoc method
* @signature isDisabled()
* @return {Boolean}
* [en]true if the pull hook is disabled.[/en]
* [ja]プルフックがdisabled状態の場合、trueを返します。[/ja]
* @description
* [en]Returns whether the component is disabled or enabled.[/en]
* [ja]dsiabled状態になっているかを得ることが出来ます。[/ja]
*/
/**
* @ngdoc method
* @signature setHeight(height)
* @param {Number} height
* [en]Desired height.[/en]
* [ja]要素の高さを指定します。[/ja]
* @description
* [en]Specify the height.[/en]
* [ja]高さを指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature setThresholdHeight(thresholdHeight)
* @param {Number} thresholdHeight
* [en]Desired threshold height.[/en]
* [ja]プルフックのアクションを起こす閾値となる高さを指定します。[/ja]
* @description
* [en]Specify the threshold height.[/en]
* [ja]閾値となる高さを指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
/**
* Pull hook directive.
*/
module.directive('onsPullHook', ['$onsen', 'PullHookView', function($onsen, PullHookView) {
return {
restrict: 'E',
replace: false,
scope: true,
compile: function(element, attrs) {
return {
pre: function(scope, element, attrs) {
var pullHook = new PullHookView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, pullHook);
$onsen.registerEventHandlers(pullHook, 'changestate destroy');
element.data('ons-pull-hook', pullHook);
scope.$on('$destroy', function() {
pullHook._events = undefined;
element.data('ons-pull-hook', undefined);
scope = element = attrs = null;
});
},
post: function(scope, element) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id row
* @name ons-row
* @category grid
* @description
* [en]Represents a row in the grid system. Use with ons-col to layout components.[/en]
* [ja]グリッドシステムにて行を定義します。ons-colとともに使用し、コンポーネントの配置に使用します。[/ja]
* @codepen GgujC {wide}
* @guide Layouting
* [en]Layouting guide[/en]
* [ja]レイアウト調整[/ja]
* @seealso ons-col
* [en]ons-col component[/en]
* [ja]ons-colコンポーネント[/ja]
* @note
* [en]For Android 4.3 and earlier, and iOS6 and earlier, when using mixed alignment with ons-row and ons-column, they may not be displayed correctly. You can use only one align.[/en]
* [ja]Android 4.3以前、もしくはiOS 6以前のOSの場合、ons-rowとons-columnを組み合わせた場合に描画が崩れる場合があります。[/ja]
* @example
* <ons-row>
* <ons-col width="50px"><ons-icon icon="fa-twitter"></ons-icon></ons-col>
* <ons-col>Text</ons-col>
* </ons-row>
*/
/**
* @ngdoc attribute
* @name align
* @type {String}
* @description
* [en]Short hand attribute for aligning vertically. Valid values are top, bottom, and center.[/en]
* [ja]縦に整列するために指定します。top、bottom、centerのいずれかを指定できます。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsRow', ['$onsen', '$timeout', function($onsen, $timeout) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: false,
compile: function(element, attrs) {
element.addClass('row ons-row-inner');
return function(scope, element, attrs) {
attrs.$observe('align', function(align) {
update();
});
update();
function update() {
var align = ('' + attrs.align).trim();
if (align === 'top' || align === 'center' || align === 'bottom') {
element.removeClass('row-bottom row-center row-top');
element.addClass('row-' + align);
}
}
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id scroller
* @name ons-scroller
* @category base
* @description
* [en]Makes the content inside this tag scrollable.[/en]
* [ja]要素内をスクロール可能にします。[/ja]
* @example
* <ons-scroller style="height: 200px; width: 100%">
* ...
* </ons-scroller>
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsScroller', ['$onsen', '$timeout', function($onsen, $timeout) {
return {
restrict: 'E',
replace: false,
transclude: true,
scope: {
onScrolled: '&',
infinitScrollEnable: '='
},
compile: function(element, attrs) {
var content = element.addClass('ons-scroller').children().remove();
return function(scope, element, attrs, controller, transclude) {
if (attrs.ngController) {
throw new Error('"ons-scroller" can\'t accept "ng-controller" directive.');
}
var wrapper = angular.element('<div></div>');
wrapper.addClass('ons-scroller__content ons-scroller-inner');
element.append(wrapper);
transclude(scope.$parent, function(cloned) {
wrapper.append(cloned);
wrapper = null;
});
// inifinte scroll
var scrollWrapper;
scrollWrapper = element[0];
var offset = parseInt(attrs.threshold) || 10;
if (scope.onScrolled) {
scrollWrapper.addEventListener('scroll', function() {
if (scope.infinitScrollEnable) {
var scrollTopAndOffsetHeight = scrollWrapper.scrollTop + scrollWrapper.offsetHeight;
var scrollHeightMinusOffset = scrollWrapper.scrollHeight - offset;
if (scrollTopAndOffsetHeight >= scrollHeightMinusOffset) {
scope.onScrolled();
}
}
});
}
// IScroll for Android
if (!Modernizr.csstransforms3d) {
$timeout(function() {
var iScroll = new IScroll(scrollWrapper, {
momentum: true,
bounce: true,
hScrollbar: false,
vScrollbar: false,
preventDefault: false
});
iScroll.on('scrollStart', function(e) {
var scrolled = iScroll.y - offset;
if (scrolled < (iScroll.maxScrollY + 40)) {
// TODO: find a better way to know when content is upated so we can refresh
iScroll.refresh();
}
});
if (scope.onScrolled) {
iScroll.on('scrollEnd', function(e) {
var scrolled = iScroll.y - offset;
if (scrolled < iScroll.maxScrollY) {
// console.log('we are there!');
scope.onScrolled();
}
});
}
}, 500);
}
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id sliding_menu
* @name ons-sliding-menu
* @category navigation
* @description
* [en]Component for sliding UI where one page is overlayed over another page. The above page can be slided aside to reveal the page behind.[/en]
* [ja]スライディングメニューを表現するためのコンポーネントで、片方のページが別のページの上にオーバーレイで表示されます。above-pageで指定されたページは、横からスライドして表示します。[/ja]
* @codepen IDvFJ
* @seealso ons-page
* [en]ons-page component[/en]
* [ja]ons-pageコンポーネント[/ja]
* @guide UsingSlidingMenu
* [en]Using sliding menu[/en]
* [ja]スライディングメニューを使う[/ja]
* @guide EventHandling
* [en]Using events[/en]
* [ja]イベントの利用[/ja]
* @guide CallingComponentAPIsfromJavaScript
* [en]Using navigator from JavaScript[/en]
* [ja]JavaScriptからコンポーネントを呼び出す[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @example
* <ons-sliding-menu var="app.menu" main-page="page.html" menu-page="menu.html" max-slide-distance="200px" type="reveal" side="left">
* </ons-sliding-menu>
*
* <ons-template id="page.html">
* <ons-page>
* <p style="text-align: center">
* <ons-button ng-click="app.menu.toggleMenu()">Toggle</ons-button>
* </p>
* </ons-page>
* </ons-template>
*
* <ons-template id="menu.html">
* <ons-page>
* <!-- menu page's contents -->
* </ons-page>
* </ons-template>
*
*/
/**
* @ngdoc event
* @name preopen
* @description
* [en]Fired just before the sliding menu is opened.[/en]
* [ja]スライディングメニューが開く前に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.slidingMenu
* [en]Sliding menu view object.[/en]
* [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja]
*/
/**
* @ngdoc event
* @name postopen
* @description
* [en]Fired just after the sliding menu is opened.[/en]
* [ja]スライディングメニューが開き終わった後に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.slidingMenu
* [en]Sliding menu view object.[/en]
* [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja]
*/
/**
* @ngdoc event
* @name preclose
* @description
* [en]Fired just before the sliding menu is closed.[/en]
* [ja]スライディングメニューが閉じる前に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.slidingMenu
* [en]Sliding menu view object.[/en]
* [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja]
*/
/**
* @ngdoc event
* @name postclose
* @description
* [en]Fired just after the sliding menu is closed.[/en]
* [ja]スライディングメニューが閉じ終わった後に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.slidingMenu
* [en]Sliding menu view object.[/en]
* [ja]イベントが発火したSlidingMenuオブジェクトです。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this sliding menu.[/en]
* [ja]このスライディングメニューを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name menu-page
* @type {String}
* @description
* [en]The url of the menu page.[/en]
* [ja]左に位置するメニューページのURLを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name main-page
* @type {String}
* @description
* [en]The url of the main page.[/en]
* [ja]右に位置するメインページのURLを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name swipeable
* @type {Boolean}
* @description
* [en]Whether to enable swipe interaction.[/en]
* [ja]スワイプ操作を有効にする場合に指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name swipe-target-width
* @type {String}
* @description
* [en]The width of swipeable area calculated from the left (in pixels). Use this to enable swipe only when the finger touch on the screen edge.[/en]
* [ja]スワイプの判定領域をピクセル単位で指定します。画面の端から指定した距離に達するとページが表示されます。[/ja]
*/
/**
* @ngdoc attribute
* @name max-slide-distance
* @type {String}
* @description
* [en]How far the menu page will slide open. Can specify both in px and %. eg. 90%, 200px[/en]
* [ja]menu-pageで指定されたページの表示幅を指定します。ピクセルもしくは%の両方で指定できます(例: 90%, 200px)[/ja]
*/
/**
* @ngdoc attribute
* @name direction
* @type {String}
* @description
* [en]Specify which side of the screen the menu page is located on. Possible values are "left" and "right".[/en]
* [ja]menu-pageで指定されたページが画面のどちら側から表示されるかを指定します。leftもしくはrightのいずれかを指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name type
* @type {String}
* @description
* [en]Sliding menu animator. Possible values are reveal (default), push and overlay.[/en]
* [ja]スライディングメニューのアニメーションです。"reveal"(デフォルト)、"push"、"overlay"のいずれかを指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-preopen
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "preopen" event is fired.[/en]
* [ja]"preopen"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-preclose
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "preclose" event is fired.[/en]
* [ja]"preclose"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postopen
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postopen" event is fired.[/en]
* [ja]"postopen"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postclose
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postclose" event is fired.[/en]
* [ja]"postclose"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature setMainPage(pageUrl, [options])
* @param {String} pageUrl
* [en]Page URL. Can be either an HTML document or an <code><ons-template></code>.[/en]
* [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Boolean} [options.closeMenu]
* [en]If true the menu will be closed.[/en]
* [ja]trueを指定すると、開いているメニューを閉じます。[/ja]
* @param {Function} [options.callback]
* [en]Function that is executed after the page has been set.[/en]
* [ja]ページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Show the page specified in pageUrl in the main contents pane.[/en]
* [ja]中央部分に表示されるページをpageUrlに指定します。[/ja]
*/
/**
* @ngdoc method
* @signature setMenuPage(pageUrl, [options])
* @param {String} pageUrl
* [en]Page URL. Can be either an HTML document or an <code><ons-template></code>.[/en]
* [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Boolean} [options.closeMenu]
* [en]If true the menu will be closed after the menu page has been set.[/en]
* [ja]trueを指定すると、開いているメニューを閉じます。[/ja]
* @param {Function} [options.callback]
* [en]This function will be executed after the menu page has been set.[/en]
* [ja]メニューページが読み込まれた後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Show the page specified in pageUrl in the side menu pane.[/en]
* [ja]メニュー部分に表示されるページをpageUrlに指定します。[/ja]
*/
/**
* @ngdoc method
* @signature openMenu([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Function} [options.callback]
* [en]This function will be called after the menu has been opened.[/en]
* [ja]メニューが開いた後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Slide the above layer to reveal the layer behind.[/en]
* [ja]メニューページを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature closeMenu([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Function} [options.callback]
* [en]This function will be called after the menu has been closed.[/en]
* [ja]メニューが閉じられた後に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]Slide the above layer to hide the layer behind.[/en]
* [ja]メニューページを非表示にします。[/ja]
*/
/**
* @ngdoc method
* @signature toggleMenu([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Function} [options.callback]
* [en]This function will be called after the menu has been opened or closed.[/en]
* [ja]メニューが開き終わった後か、閉じ終わった後に呼び出される関数オブジェクトです。[/ja]
* @description
* [en]Slide the above layer to reveal the layer behind if it is currently hidden, otherwise, hide the layer behind.[/en]
* [ja]現在の状況に合わせて、メニューページを表示もしくは非表示にします。[/ja]
*/
/**
* @ngdoc method
* @signature isMenuOpened()
* @return {Boolean}
* [en]true if the menu is currently open.[/en]
* [ja]メニューが開いていればtrueとなります。[/ja]
* @description
* [en]Returns true if the menu page is open, otherwise false.[/en]
* [ja]メニューページが開いている場合はtrue、そうでない場合はfalseを返します。[/ja]
*/
/**
* @ngdoc method
* @signature getDeviceBackButtonHandler()
* @return {Object}
* [en]Device back button handler.[/en]
* [ja]デバイスのバックボタンハンドラを返します。[/ja]
* @description
* [en]Retrieve the back-button handler.[/en]
* [ja]ons-sliding-menuに紐付いているバックボタンハンドラを取得します。[/ja]
*/
/**
* @ngdoc method
* @signature setSwipeable(swipeable)
* @param {Boolean} swipeable
* [en]If true the menu will be swipeable.[/en]
* [ja]スワイプで開閉できるようにする場合にはtrueを指定します。[/ja]
* @description
* [en]Specify if the menu should be swipeable or not.[/en]
* [ja]スワイプで開閉するかどうかを設定する。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsSlidingMenu', ['$compile', 'SlidingMenuView', '$onsen', function($compile, SlidingMenuView, $onsen) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclude.
transclude: false,
scope: true,
compile: function(element, attrs) {
var main = element[0].querySelector('.main'),
menu = element[0].querySelector('.menu');
if (main) {
var mainHtml = angular.element(main).remove().html().trim();
}
if (menu) {
var menuHtml = angular.element(menu).remove().html().trim();
}
return function(scope, element, attrs) {
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__menu ons-sliding-menu-inner'));
element.append(angular.element('<div></div>').addClass('onsen-sliding-menu__main ons-sliding-menu-inner'));
var slidingMenu = new SlidingMenuView(scope, element, attrs);
$onsen.registerEventHandlers(slidingMenu, 'preopen preclose postopen postclose destroy');
if (mainHtml && !attrs.mainPage) {
slidingMenu._appendMainPage(null, mainHtml);
}
if (menuHtml && !attrs.menuPage) {
slidingMenu._appendMenuPage(menuHtml);
}
$onsen.declareVarAttribute(attrs, slidingMenu);
element.data('ons-sliding-menu', slidingMenu);
scope.$on('$destroy', function(){
slidingMenu._events = undefined;
element.data('ons-sliding-menu', undefined);
});
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id split-view
* @name ons-split-view
* @category control
* @description
* [en]Divides the screen into a left and right section.[/en]
* [ja]画面を左右に分割するコンポーネントです。[/ja]
* @codepen nKqfv {wide}
* @guide Usingonssplitviewcomponent
* [en]Using ons-split-view.[/en]
* [ja]ons-split-viewコンポーネントを使う[/ja]
* @guide CallingComponentAPIsfromJavaScript
* [en]Using navigator from JavaScript[/en]
* [ja]JavaScriptからコンポーネントを呼び出す[/ja]
* @example
* <ons-split-view
* secondary-page="secondary.html"
* main-page="main.html"
* main-page-width="70%"
* collapse="portrait">
* </ons-split-view>
*/
/**
* @ngdoc event
* @name update
* @description
* [en]Fired when the split view is updated.[/en]
* [ja]split viewの状態が更新された際に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Object} event.splitView
* [en]Split view object.[/en]
* [ja]イベントが発火したSplitViewオブジェクトです。[/ja]
* @param {Boolean} event.shouldCollapse
* [en]True if the view should collapse.[/en]
* [ja]collapse状態の場合にtrueになります。[/ja]
* @param {String} event.currentMode
* [en]Current mode.[/en]
* [ja]現在のモード名を返します。"collapse"か"split"かのいずれかです。[/ja]
* @param {Function} event.split
* [en]Call to force split.[/en]
* [ja]この関数を呼び出すと強制的にsplitモードにします。[/ja]
* @param {Function} event.collapse
* [en]Call to force collapse.[/en]
* [ja]この関数を呼び出すと強制的にcollapseモードにします。[/ja]
* @param {Number} event.width
* [en]Current width.[/en]
* [ja]現在のSplitViewの幅を返します。[/ja]
* @param {String} event.orientation
* [en]Current orientation.[/en]
* [ja]現在の画面のオリエンテーションを返します。"portrait"かもしくは"landscape"です。 [/ja]
*/
/**
* @ngdoc event
* @name presplit
* @description
* [en]Fired just before the view is split.[/en]
* [ja]split状態にる前に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.splitView
* [en]Split view object.[/en]
* [ja]イベントが発火したSplitViewオブジェクトです。[/ja]
* @param {Number} event.width
* [en]Current width.[/en]
* [ja]現在のSplitViewnの幅です。[/ja]
* @param {String} event.orientation
* [en]Current orientation.[/en]
* [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja]
*/
/**
* @ngdoc event
* @name postsplit
* @description
* [en]Fired just after the view is split.[/en]
* [ja]split状態になった後に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.splitView
* [en]Split view object.[/en]
* [ja]イベントが発火したSplitViewオブジェクトです。[/ja]
* @param {Number} event.width
* [en]Current width.[/en]
* [ja]現在のSplitViewnの幅です。[/ja]
* @param {String} event.orientation
* [en]Current orientation.[/en]
* [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja]
*/
/**
* @ngdoc event
* @name precollapse
* @description
* [en]Fired just before the view is collapsed.[/en]
* [ja]collapse状態になる前に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.splitView
* [en]Split view object.[/en]
* [ja]イベントが発火したSplitViewオブジェクトです。[/ja]
* @param {Number} event.width
* [en]Current width.[/en]
* [ja]現在のSplitViewnの幅です。[/ja]
* @param {String} event.orientation
* [en]Current orientation.[/en]
* [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja]
*/
/**
* @ngdoc event
* @name postcollapse
* @description
* [en]Fired just after the view is collapsed.[/en]
* [ja]collapse状態になった後に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.splitView
* [en]Split view object.[/en]
* [ja]イベントが発火したSplitViewオブジェクトです。[/ja]
* @param {Number} event.width
* [en]Current width.[/en]
* [ja]現在のSplitViewnの幅です。[/ja]
* @param {String} event.orientation
* [en]Current orientation.[/en]
* [ja]現在の画面のオリエンテーションを返します。"portrait"もしくは"landscape"です。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this split view.[/en]
* [ja]このスプリットビューコンポーネントを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name main-page
* @type {String}
* @description
* [en]The url of the page on the right.[/en]
* [ja]右側に表示するページのURLを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name main-page-width
* @type {Number}
* @description
* [en]Main page width percentage. The secondary page width will be the remaining percentage.[/en]
* [ja]右側のページの幅をパーセント単位で指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name secondary-page
* @type {String}
* @description
* [en]The url of the page on the left.[/en]
* [ja]左側に表示するページのURLを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name collapse
* @type {String}
* @description
* [en]
* Specify the collapse behavior. Valid values are portrait, landscape, width #px or a media query.
* "portrait" or "landscape" means the view will collapse when device is in landscape or portrait orientation.
* "width #px" means the view will collapse when the window width is smaller than the specified #px.
* If the value is a media query, the view will collapse when the media query is true.
* [/en]
* [ja]
* 左側のページを非表示にする条件を指定します。portrait, landscape、width #pxもしくはメディアクエリの指定が可能です。
* portraitもしくはlandscapeを指定すると、デバイスの画面が縦向きもしくは横向きになった時に適用されます。
* width #pxを指定すると、画面が指定した横幅よりも短い場合に適用されます。
* メディアクエリを指定すると、指定したクエリに適合している場合に適用されます。
* [/ja]
*/
/**
* @ngdoc attribute
* @name ons-update
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "update" event is fired.[/en]
* [ja]"update"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-presplit
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "presplit" event is fired.[/en]
* [ja]"presplit"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-precollapse
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "precollapse" event is fired.[/en]
* [ja]"precollapse"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postsplit
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postsplit" event is fired.[/en]
* [ja]"postsplit"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postcollapse
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postcollapse" event is fired.[/en]
* [ja]"postcollapse"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature setMainPage(pageUrl)
* @param {String} pageUrl
* [en]Page URL. Can be either an HTML document or an <ons-template>.[/en]
* [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja]
* @description
* [en]Show the page specified in pageUrl in the right section[/en]
* [ja]指定したURLをメインページを読み込みます。[/ja]
*/
/**
* @ngdoc method
* @signature setSecondaryPage(pageUrl)
* @param {String} pageUrl
* [en]Page URL. Can be either an HTML document or an <ons-template>.[/en]
* [ja]pageのURLか、ons-templateで宣言したテンプレートのid属性の値を指定します。[/ja]
* @description
* [en]Show the page specified in pageUrl in the left section[/en]
* [ja]指定したURLを左のページの読み込みます。[/ja]
*/
/**
* @ngdoc method
* @signature update()
* @description
* [en]Trigger an 'update' event and try to determine if the split behaviour should be changed.[/en]
* [ja]splitモードを変えるべきかどうかを判断するための'update'イベントを発火します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsSplitView', ['$compile', 'SplitView', '$onsen', function($compile, SplitView, $onsen) {
return {
restrict: 'E',
replace: false,
transclude: false,
scope: true,
compile: function(element, attrs) {
var mainPage = element[0].querySelector('.main-page'),
secondaryPage = element[0].querySelector('.secondary-page');
if (mainPage) {
var mainHtml = angular.element(mainPage).remove().html().trim();
}
if (secondaryPage) {
var secondaryHtml = angular.element(secondaryPage).remove().html().trim();
}
return function(scope, element, attrs) {
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
element.append(angular.element('<div></div>').addClass('onsen-split-view__secondary full-screen ons-split-view-inner'));
element.append(angular.element('<div></div>').addClass('onsen-split-view__main full-screen ons-split-view-inner'));
var splitView = new SplitView(scope, element, attrs);
if (mainHtml && !attrs.mainPage) {
splitView._appendMainPage(mainHtml);
}
if (secondaryHtml && !attrs.secondaryPage) {
splitView._appendSecondPage(secondaryHtml);
}
$onsen.declareVarAttribute(attrs, splitView);
$onsen.registerEventHandlers(splitView, 'update presplit precollapse postsplit postcollapse destroy');
element.data('ons-split-view', splitView);
scope.$on('$destroy', function() {
splitView._events = undefined;
element.data('ons-split-view', undefined);
});
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id switch
* @name ons-switch
* @category form
* @description
* [en]Switch component.[/en]
* [ja]スイッチを表示するコンポーネントです。[/ja]
* @guide UsingFormComponents
* [en]Using form components[/en]
* [ja]フォームを使う[/ja]
* @guide EventHandling
* [en]Event handling descriptions[/en]
* [ja]イベント処理の使い方[/ja]
* @seealso ons-button
* [en]ons-button component[/en]
* [ja]ons-buttonコンポーネント[/ja]
* @example
* <ons-switch checked></ons-switch>
*/
/**
* @ngdoc event
* @name change
* @description
* [en]Fired when the value is changed.[/en]
* [ja]ON/OFFが変わった時に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Object} event.switch
* [en]Switch object.[/en]
* [ja]イベントが発火したSwitchオブジェクトを返します。[/ja]
* @param {Boolean} event.value
* [en]Current value.[/en]
* [ja]現在の値を返します。[/ja]
* @param {Boolean} event.isInteractive
* [en]True if the change was triggered by the user clicking on the switch.[/en]
* [ja]タップやクリックなどのユーザの操作によって変わった場合にはtrueを返します。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this switch.[/en]
* [ja]JavaScriptから参照するための変数名を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the switch.[/en]
* [ja]スイッチの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]Whether the switch should be disabled.[/en]
* [ja]スイッチを無効の状態にする場合に指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name checked
* @description
* [en]Whether the switch is checked.[/en]
* [ja]スイッチがONの状態にするときに指定します。[/ja]
*/
/**
* @ngdoc method
* @signature isChecked()
* @return {Boolean}
* [en]true if the switch is on.[/en]
* [ja]ONになっている場合にはtrueになります。[/ja]
* @description
* [en]Returns true if the switch is ON.[/en]
* [ja]スイッチがONの場合にtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature setChecked(checked)
* @param {Boolean} checked
* [en]If true the switch will be set to on.[/en]
* [ja]ONにしたい場合にはtrueを指定します。[/ja]
* @description
* [en]Set the value of the switch. isChecked can be either true or false.[/en]
* [ja]スイッチの値を指定します。isCheckedにはtrueもしくはfalseを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature getCheckboxElement()
* @return {HTMLElement}
* [en]The underlying checkbox element.[/en]
* [ja]コンポーネント内部のcheckbox要素になります。[/ja]
* @description
* [en]Get inner input[type=checkbox] element.[/en]
* [ja]スイッチが内包する、input[type=checkbox]の要素を取得します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsSwitch', ['$onsen', '$parse', 'SwitchView', function($onsen, $parse, SwitchView) {
return {
restrict: 'E',
replace: false,
transclude: false,
scope: true,
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/switch.tpl',
compile: function(element) {
return function(scope, element, attrs) {
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
var switchView = new SwitchView(element, scope, attrs);
var checkbox = angular.element(element[0].querySelector('input[type=checkbox]'));
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
var label = element.children(),
input = angular.element(label.children()[0]),
toggle = angular.element(label.children()[1]);
$onsen.addModifierMethods(switchView, 'switch--*', label);
$onsen.addModifierMethods(switchView, 'switch--*__input', input);
$onsen.addModifierMethods(switchView, 'switch--*__toggle', toggle);
attrs.$observe('checked', function(checked) {
scope.model = !!element.attr('checked');
});
attrs.$observe('name', function(name) {
if (!!element.attr('name')) {
checkbox.attr('name', name);
}
});
if (attrs.ngModel) {
var set = $parse(attrs.ngModel).assign;
scope.$parent.$watch(attrs.ngModel, function(value) {
scope.model = value;
});
scope.$watch('model', function(to, from) {
set(scope.$parent, to);
if (to !== from) {
scope.$eval(attrs.ngChange);
}
});
}
$onsen.declareVarAttribute(attrs, switchView);
element.data('ons-switch', switchView);
$onsen.cleaner.onDestroy(scope, function() {
switchView._events = undefined;
$onsen.removeModifierMethods(switchView);
element.data('ons-switch', undefined);
$onsen.clearComponent({
element : element,
scope : scope,
attrs : attrs
});
checkbox = element = attrs = scope = null;
});
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id tabbar_item
* @name ons-tab
* @category navigation
* @description
* [en]Represents a tab inside tabbar. Each ons-tab represents a page.[/en]
* [ja]
* タブバーに配置される各アイテムのコンポーネントです。それぞれのons-tabはページを表します。
* ons-tab要素の中には、タブに表示されるコンテンツを直接記述することが出来ます。
* [/ja]
* @codepen pGuDL
* @guide UsingTabBar
* [en]Using tab bar[/en]
* [ja]タブバーを使う[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @seealso ons-tabbar
* [en]ons-tabbar component[/en]
* [ja]ons-tabbarコンポーネント[/ja]
* @seealso ons-page
* [en]ons-page component[/en]
* [ja]ons-pageコンポーネント[/ja]
* @seealso ons-icon
* [en]ons-icon component[/en]
* [ja]ons-iconコンポーネント[/ja]
* @example
* <ons-tabbar>
* <ons-tab page="home.html" active="true">
* <ons-icon icon="ion-home"></ons-icon>
* <span style="font-size: 14px">Home</span>
* </ons-tab>
* <ons-tab page="fav.html" active="true">
* <ons-icon icon="ion-star"></ons-icon>
* <span style="font-size: 14px">Favorites</span>
* </ons-tab>
* <ons-tab page="settings.html" active="true">
* <ons-icon icon="ion-gear-a"></ons-icon>
* <span style="font-size: 14px">Settings</span>
* </ons-tab>
* </ons-tabbar>
*
* <ons-template id="home.html">
* ...
* </ons-template>
*
* <ons-template id="fav.html">
* ...
* </ons-template>
*
* <ons-template id="settings.html">
* ...
* </ons-template>
*/
/**
* @ngdoc attribute
* @name page
* @type {String}
* @description
* [en]The page that this <code><ons-tab></code> points to.[/en]
* [ja]<code><ons-tab></code>が参照するページへのURLを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name icon
* @type {String}
* @description
* [en]
* The icon name for the tab. Can specify the same icon name as <code><ons-icon></code>.
* If you need to use your own icon, create a css class with background-image or any css properties and specify the name of your css class here.
* [/en]
* [ja]
* アイコン名を指定します。<code><ons-icon></code>と同じアイコン名を指定できます。
* 個別にアイコンをカスタマイズする場合は、background-imageなどのCSSスタイルを用いて指定できます。
* [/ja]
*/
/**
* @ngdoc attribute
* @name active-icon
* @type {String}
* @description
* [en]The name of the icon when the tab is active.[/en]
* [ja]アクティブの際のアイコン名を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name label
* @type {String}
* @description
* [en]The label of the tab item.[/en]
* [ja]アイコン下に表示されるラベルを指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name active
* @type {Boolean}
* @default false
* @description
* [en]Set whether this item should be active or not. Valid values are true and false.[/en]
* [ja]このタブアイテムをアクティブ状態にするかどうかを指定します。trueもしくはfalseを指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name no-reload
* @description
* [en]Set if the page shouldn't be reloaded when clicking on the same tab twice.[/en]
* [ja]すでにアクティブになったタブを再びクリックするとページの再読み込みは発生しません。[/ja]
*/
/**
* @ngdoc attribute
* @name persistent
* @description
* [en]
* Set to make the tab content persistent.
* If this attribute it set the DOM will not be destroyed when navigating to another tab.
* [/en]
* [ja]
* このタブで読み込んだページを永続化します。
* この属性があるとき、別のタブのページに切り替えても、
* 読み込んだページのDOM要素は破棄されずに単に非表示になります。
* [/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsTab', tab);
module.directive('onsTabbarItem', tab); // for BC
var defaultInnerTemplate =
'<div ng-if="icon != undefined" class="tab-bar__icon">' +
'<ons-icon icon="{{tabIcon}}" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon>' +
'</div>' +
'<div ng-if="label" class="tab-bar__label">{{label}}</div>';
function tab($onsen, $compile) {
return {
restrict: 'E',
transclude: true,
scope: {
page: '@',
active: '@',
icon: '@',
activeIcon: '@',
label: '@',
noReload: '@',
persistent: '@'
},
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/tab.tpl',
compile: function(element, attrs) {
element.addClass('tab-bar__item');
return function(scope, element, attrs, controller, transclude) {
var tabbarView = element.inheritedData('ons-tabbar');
if (!tabbarView) {
throw new Error('This ons-tab element is must be child of ons-tabbar element.');
}
element.addClass(tabbarView._scope.modifierTemplater('tab-bar--*__item'));
element.addClass(tabbarView._scope.modifierTemplater('tab-bar__item--*'));
transclude(scope.$parent, function(cloned) {
var wrapper = angular.element(element[0].querySelector('.tab-bar-inner'));
if (attrs.icon || attrs.label || !cloned[0]) {
var innerElement = angular.element('<div>' + defaultInnerTemplate + '</div>').children();
wrapper.append(innerElement);
$compile(innerElement)(scope);
} else {
wrapper.append(cloned);
}
});
var radioButton = element[0].querySelector('input');
scope.tabbarModifierTemplater = tabbarView._scope.modifierTemplater;
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
scope.tabbarId = tabbarView._tabbarId;
scope.tabIcon = scope.icon;
tabbarView.addTabItem(scope);
// Make this tab active.
scope.setActive = function() {
element.addClass('active');
radioButton.checked = true;
if (scope.activeIcon) {
scope.tabIcon = scope.activeIcon;
}
angular.element(element[0].querySelectorAll('[ons-tab-inactive]')).css('display', 'none');
angular.element(element[0].querySelectorAll('[ons-tab-active]')).css('display', 'inherit');
};
// Make this tab inactive.
scope.setInactive = function() {
element.removeClass('active');
radioButton.checked = false;
scope.tabIcon = scope.icon;
angular.element(element[0].querySelectorAll('[ons-tab-inactive]')).css('display', 'inherit');
angular.element(element[0].querySelectorAll('[ons-tab-active]')).css('display', 'none');
};
scope.isPersistent = function() {
return typeof scope.persistent != 'undefined';
};
/**
* @return {Boolean}
*/
scope.isActive = function() {
return element.hasClass('active');
};
scope.tryToChange = function() {
tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope));
};
if (scope.active) {
tabbarView.setActiveTab(tabbarView._tabItems.indexOf(scope));
}
$onsen.fireComponentEvent(element[0], 'init');
};
}
};
}
tab.$inject = ['$onsen', '$compile'];
})();
/**
* @ngdoc directive
* @id tabbar
* @name ons-tabbar
* @category navigation
* @description
* [en]A component to display a tab bar on the bottom of a page. Used with ons-tab to manage pages using tabs.[/en]
* [ja]タブバーをページ下部に表示するためのコンポーネントです。ons-tabと組み合わせて使うことで、ページを管理できます。[/ja]
* @codepen pGuDL
* @guide UsingTabBar
* [en]Using tab bar[/en]
* [ja]タブバーを使う[/ja]
* @guide EventHandling
* [en]Event handling descriptions[/en]
* [ja]イベント処理の使い方[/ja]
* @guide CallingComponentAPIsfromJavaScript
* [en]Using navigator from JavaScript[/en]
* [ja]JavaScriptからコンポーネントを呼び出す[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @seealso ons-tab
* [en]ons-tab component[/en]
* [ja]ons-tabコンポーネント[/ja]
* @seealso ons-page
* [en]ons-page component[/en]
* [ja]ons-pageコンポーネント[/ja]
* @example
* <ons-tabbar>
* <ons-tab page="home.html" active="true">
* <ons-icon icon="ion-home"></ons-icon>
* <span style="font-size: 14px">Home</span>
* </ons-tab>
* <ons-tab page="fav.html" active="true">
* <ons-icon icon="ion-star"></ons-icon>
* <span style="font-size: 14px">Favorites</span>
* </ons-tab>
* <ons-tab page="settings.html" active="true">
* <ons-icon icon="ion-gear-a"></ons-icon>
* <span style="font-size: 14px">Settings</span>
* </ons-tab>
* </ons-tabbar>
*
* <ons-template id="home.html">
* ...
* </ons-template>
*
* <ons-template id="fav.html">
* ...
* </ons-template>
*
* <ons-template id="settings.html">
* ...
* </ons-template>
*/
/**
* @ngdoc event
* @name prechange
* @description
* [en]Fires just before the tab is changed.[/en]
* [ja]アクティブなタブが変わる前に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Number} event.index
* [en]Current index.[/en]
* [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja]
* @param {Object} event.tabItem
* [en]Tab item object.[/en]
* [ja]tabItemオブジェクト。[/ja]
* @param {Function} event.cancel
* [en]Call this function to cancel the change event.[/en]
* [ja]この関数を呼び出すと、アクティブなタブの変更がキャンセルされます。[/ja]
*/
/**
* @ngdoc event
* @name postchange
* @description
* [en]Fires just after the tab is changed.[/en]
* [ja]アクティブなタブが変わった後に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Number} event.index
* [en]Current index.[/en]
* [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja]
* @param {Object} event.tabItem
* [en]Tab item object.[/en]
* [ja]tabItemオブジェクト。[/ja]
*/
/**
* @ngdoc event
* @name reactive
* @description
* [en]Fires if the already open tab is tapped again.[/en]
* [ja]すでにアクティブになっているタブがもう一度タップやクリックされた場合に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクト。[/ja]
* @param {Number} event.index
* [en]Current index.[/en]
* [ja]現在アクティブになっているons-tabのインデックスを返します。[/ja]
* @param {Object} event.tabItem
* [en]Tab item object.[/en]
* [ja]tabItemオブジェクト。[/ja]
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this tab bar.[/en]
* [ja]このタブバーを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name hide-tabs
* @type {Boolean}
* @default false
* @description
* [en]Whether to hide the tabs. Valid values are true/false.[/en]
* [ja]タブを非表示にする場合に指定します。trueもしくはfalseを指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name animation
* @type {String}
* @default none
* @description
* [en]Animation name. Preset values are "none" and "fade". Default is "none".[/en]
* [ja]ページ読み込み時のアニメーションを指定します。"none"もしくは"fade"を選択できます。デフォルトは"none"です。[/ja]
*/
/**
* @ngdoc attribute
* @name position
* @type {String}
* @default bottom
* @description
* [en]Tabbar's position. Preset values are "bottom" and "top". Default is "bottom".[/en]
* [ja]タブバーの位置を指定します。"bottom"もしくは"top"を選択できます。デフォルトは"bottom"です。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-reactive
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "reactive" event is fired.[/en]
* [ja]"reactive"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-prechange
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "prechange" event is fired.[/en]
* [ja]"prechange"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-postchange
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "postchange" event is fired.[/en]
* [ja]"postchange"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc attribute
* @name ons-destroy
* @type {Expression}
* @description
* [en]Allows you to specify custom behavior when the "destroy" event is fired.[/en]
* [ja]"destroy"イベントが発火された時の挙動を独自に指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature setActiveTab(index, [options])
* @param {Number} index
* [en]Tab index.[/en]
* [ja]タブのインデックスを指定します。[/ja]
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {Boolean} [options.keepPage]
* [en]If true the page will not be changed.[/en]
* [ja]タブバーが現在表示しているpageを変えない場合にはtrueを指定します。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "fade" and "none".[/en]
* [ja]アニメーション名を指定します。"fade", "none"のいずれかを指定できます。[/ja]
* @return {Boolean}
* [en]true if the change was successful.[/en]
* [ja]変更が成功した場合にtrueを返します。[/ja]
* @description
* [en]Show specified tab page. Animations and other options can be specified by the second parameter.[/en]
* [ja]指定したインデックスのタブを表示します。アニメーションなどのオプションを指定できます。[/ja]
*/
/**
* @ngdoc method
* @signature getActiveTabIndex()
* @return {Number}
* [en]The index of the currently active tab.[/en]
* [ja]現在アクティブになっているタブのインデックスを返します。[/ja]
* @description
* [en]Returns tab index on current active tab. If active tab is not found, returns -1.[/en]
* [ja]現在アクティブになっているタブのインデックスを返します。現在アクティブなタブがない場合には-1を返します。[/ja]
*/
/**
* @ngdoc method
* @signature loadPage(url)
* @param {String} url
* [en]Page URL. Can be either an HTML document or an <code><ons-template></code>.[/en]
* [ja]pageのURLか、もしくは<code><ons-template></code>で宣言したid属性の値を利用できます。[/ja]
* @description
* [en]Displays a new page without changing the active index.[/en]
* [ja]現在のアクティブなインデックスを変更せずに、新しいページを表示します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
module.directive('onsTabbar', ['$onsen', '$compile', 'TabbarView', function($onsen, $compile, TabbarView) {
return {
restrict: 'E',
replace: false,
transclude: true,
scope: true,
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/tab_bar.tpl',
link: function(scope, element, attrs, controller, transclude) {
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
scope.selectedTabItem = {source: ''};
attrs.$observe('hideTabs', function(hide) {
var visible = hide !== 'true';
tabbarView.setTabbarVisibility(visible);
});
var tabbarView = new TabbarView(scope, element, attrs);
$onsen.addModifierMethods(tabbarView, 'tab-bar--*', angular.element(element.children()[1]));
$onsen.registerEventHandlers(tabbarView, 'reactive prechange postchange destroy');
scope.tabbarId = tabbarView._tabbarId;
element.data('ons-tabbar', tabbarView);
$onsen.declareVarAttribute(attrs, tabbarView);
transclude(scope, function(cloned) {
angular.element(element[0].querySelector('.ons-tabbar-inner')).append(cloned);
});
scope.$on('$destroy', function() {
tabbarView._events = undefined;
$onsen.removeModifierMethods(tabbarView);
element.data('ons-tabbar', undefined);
});
$onsen.fireComponentEvent(element[0], 'init');
}
};
}]);
})();
/**
* @ngdoc directive
* @id template
* @name ons-template
* @category util
* @description
* [en]Define a separate HTML fragment and use as a template.[/en]
* [ja]テンプレートとして使用するためのHTMLフラグメントを定義します。この要素でHTMLを宣言すると、id属性に指定した名前をpageのURLとしてons-navigatorなどのコンポーネントから参照できます。[/ja]
* @guide DefiningMultiplePagesinSingleHTML
* [en]Defining multiple pages in single html[/en]
* [ja]複数のページを1つのHTMLに記述する[/ja]
* @example
* <ons-template id="foobar.html">
* ...
* </ons-template>
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsTemplate', ['$onsen', '$templateCache', function($onsen, $templateCache) {
return {
restrict: 'E',
transclude: false,
priority: 1000,
terminal: true,
compile: function(element) {
$templateCache.put(element.attr('id'), element.remove().html());
$onsen.fireComponentEvent(element[0], 'init');
}
};
}]);
})();
/**
* @ngdoc directive
* @id toolbar
* @name ons-toolbar
* @category toolbar
* @modifier transparent
* [en]Transparent toolbar[/en]
* [ja]透明な背景を持つツールバーを表示します。[/ja]
* @modifier android
* [en]Android style toolbar. Title is left-aligned.[/en]
* [ja]Androidライクなツールバーを表示します。タイトルが左に寄ります。[/ja]
* @description
* [en]Toolbar component that can be used with navigation. Left, center and right container can be specified by class names.[/en]
* [ja]ナビゲーションで使用するツールバー用コンポーネントです。クラス名により、左、中央、右のコンテナを指定できます。[/ja]
* @codepen aHmGL
* @guide Addingatoolbar [en]Adding a toolbar[/en][ja]ツールバーの追加[/ja]
* @seealso ons-bottom-toolbar
* [en]ons-bottom-toolbar component[/en]
* [ja]ons-bottom-toolbarコンポーネント[/ja]
* @seealso ons-back-button
* [en]ons-back-button component[/en]
* [ja]ons-back-buttonコンポーネント[/ja]
* @seealso ons-toolbar-button
* [en]ons-toolbar-button component[/en]
* [ja]ons-toolbar-buttonコンポーネント[/ja]
* @example
* <ons-page>
* <ons-toolbar>
* <div class="left"><ons-back-button>Back</ons-back-button></div>
* <div class="center">Title</div>
* <div class="right">Label</div>
* </ons-toolbar>
* </ons-page>
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this toolbar.[/en]
* [ja]このツールバーを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name inline
* @description
* [en]Display the toolbar as an inline element.[/en]
* [ja]ツールバーをインラインに置きます。スクロール領域内にそのまま表示されます。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @description
* [en]The appearance of the toolbar.[/en]
* [ja]ツールバーの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name fixed-style
* @description
* [en]
* By default the center element will be left-aligned on Android and center-aligned on iOS.
* Use this attribute to override this behavior so it's always displayed in the center.
* [/en]
* [ja]
* このコンポーネントは、Androidではタイトルを左寄せ、iOSでは中央配置します。
* この属性を使用すると、要素はAndroidとiOSともに中央配置となります。
* [/ja]
*/
(function() {
'use strict';
var module = angular.module('onsen');
function ensureLeftContainer(element, modifierTemplater) {
var container = element[0].querySelector('.left');
if (!container) {
container = document.createElement('div');
container.setAttribute('class', 'left');
container.innerHTML = ' ';
}
if (container.innerHTML.trim() === '') {
container.innerHTML = ' ';
}
angular.element(container)
.addClass('navigation-bar__left')
.addClass(modifierTemplater('navigation-bar--*__left'));
return container;
}
function ensureCenterContainer(element, modifierTemplater) {
var container = element[0].querySelector('.center');
if (!container) {
container = document.createElement('div');
container.setAttribute('class', 'center');
}
if (container.innerHTML.trim() === '') {
container.innerHTML = ' ';
}
angular.element(container)
.addClass('navigation-bar__title navigation-bar__center')
.addClass(modifierTemplater('navigation-bar--*__center'));
return container;
}
function ensureRightContainer(element, modifierTemplater) {
var container = element[0].querySelector('.right');
if (!container) {
container = document.createElement('div');
container.setAttribute('class', 'right');
container.innerHTML = ' ';
}
if (container.innerHTML.trim() === '') {
container.innerHTML = ' ';
}
angular.element(container)
.addClass('navigation-bar__right')
.addClass(modifierTemplater('navigation-bar--*__right'));
return container;
}
/**
* @param {jqLite} element
* @return {Boolean}
*/
function hasCenterClassElementOnly(element) {
var hasCenter = false;
var hasOther = false;
var child, children = element.contents();
for (var i = 0; i < children.length; i++) {
child = angular.element(children[i]);
if (child.hasClass('center')) {
hasCenter = true;
continue;
}
if (child.hasClass('left') || child.hasClass('right')) {
hasOther = true;
continue;
}
}
return hasCenter && !hasOther;
}
function ensureToolbarItemElements(element, modifierTemplater) {
var center;
if (hasCenterClassElementOnly(element)) {
center = ensureCenterContainer(element, modifierTemplater);
element.contents().remove();
element.append(center);
} else {
center = ensureCenterContainer(element, modifierTemplater);
var left = ensureLeftContainer(element, modifierTemplater);
var right = ensureRightContainer(element, modifierTemplater);
element.contents().remove();
element.append(angular.element([left, center, right]));
}
}
/**
* Toolbar directive.
*/
module.directive('onsToolbar', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
replace: false,
// NOTE: This element must coexists with ng-controller.
// Do not use isolated scope and template's ng-transclde.
scope: false,
transclude: false,
compile: function(element, attrs) {
var shouldAppendAndroidModifier = ons.platform.isAndroid() && !element[0].hasAttribute('fixed-style');
var modifierTemplater = $onsen.generateModifierTemplater(attrs, shouldAppendAndroidModifier ? ['android'] : []),
inline = typeof attrs.inline !== 'undefined';
element.addClass('navigation-bar');
element.addClass(modifierTemplater('navigation-bar--*'));
if (!inline) {
element.css({
'position': 'absolute',
'z-index': '10000',
'left': '0px',
'right': '0px',
'top': '0px'
});
}
ensureToolbarItemElements(element, modifierTemplater);
return {
pre: function(scope, element, attrs) {
var toolbar = new GenericView(scope, element, attrs);
$onsen.declareVarAttribute(attrs, toolbar);
scope.$on('$destroy', function() {
toolbar._events = undefined;
$onsen.removeModifierMethods(toolbar);
element.data('ons-toolbar', undefined);
element = null;
});
$onsen.addModifierMethods(toolbar, 'navigation-bar--*', element);
angular.forEach(['left', 'center', 'right'], function(position) {
var el = element[0].querySelector('.navigation-bar__' + position);
if (el) {
$onsen.addModifierMethods(toolbar, 'navigation-bar--*__' + position, angular.element(el));
}
});
var pageView = element.inheritedData('ons-page');
if (pageView && !inline) {
pageView.registerToolbar(element);
}
element.data('ons-toolbar', toolbar);
},
post: function(scope, element, attrs) {
$onsen.fireComponentEvent(element[0], 'init');
}
};
}
};
}]);
})();
/**
* @ngdoc directive
* @id toolbar_button
* @name ons-toolbar-button
* @category toolbar
* @modifier outline
* [en]A button with an outline.[/en]
* [ja]アウトラインをもったボタンを表示します。[/ja]
* @description
* [en]Button component for ons-toolbar and ons-bottom-toolbar.[/en]
* [ja]ons-toolbarあるいはons-bottom-toolbarに設置できるボタン用コンポーネントです。[/ja]
* @codepen aHmGL
* @guide Addingatoolbar
* [en]Adding a toolbar[/en]
* [ja]ツールバーの追加[/ja]
* @seealso ons-toolbar
* [en]ons-toolbar component[/en]
* [ja]ons-toolbarコンポーネント[/ja]
* @seealso ons-back-button
* [en]ons-back-button component[/en]
* [ja]ons-back-buttonコンポーネント[/ja]
* @seealso ons-toolbar-button
* [en]ons-toolbar-button component[/en]
* [ja]ons-toolbar-buttonコンポーネント[/ja]
* @example
* <ons-toolbar>
* <div class="left"><ons-toolbar-button>Button</ons-toolbar-button></div>
* <div class="center">Title</div>
* <div class="right"><ons-toolbar-button><ons-icon icon="ion-navion" size="28px"></ons-icon></ons-toolbar-button></div>
* </ons-toolbar>
*/
/**
* @ngdoc attribute
* @name var
* @type {String}
* @description
* [en]Variable name to refer this buttom.[/en]
* [ja]このボタンを参照するための名前を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name modifier
* @type {String}
* @description
* [en]The appearance of the button.[/en]
* [ja]ボタンの表現を指定します。[/ja]
*/
/**
* @ngdoc attribute
* @name disabled
* @description
* [en]Specify if button should be disabled.[/en]
* [ja]ボタンを無効化する場合は指定してください。[/ja]
*/
(function(){
'use strict';
var module = angular.module('onsen');
module.directive('onsToolbarButton', ['$onsen', 'GenericView', function($onsen, GenericView) {
return {
restrict: 'E',
transclude: true,
scope: {},
templateUrl: $onsen.DIRECTIVE_TEMPLATE_URL + '/toolbar_button.tpl',
link: {
pre: function(scope, element, attrs) {
var toolbarButton = new GenericView(scope, element, attrs),
innerElement = element[0].querySelector('.toolbar-button');
$onsen.declareVarAttribute(attrs, toolbarButton);
element.data('ons-toolbar-button', toolbarButton);
scope.$on('$destroy', function() {
toolbarButton._events = undefined;
$onsen.removeModifierMethods(toolbarButton);
element.data('ons-toolbar-button', undefined);
element = null;
});
var modifierTemplater = $onsen.generateModifierTemplater(attrs);
if (attrs.ngController) {
throw new Error('This element can\'t accept ng-controller directive.');
}
attrs.$observe('disabled', function(value) {
if (value === false || typeof value === 'undefined') {
innerElement.removeAttribute('disabled');
}
else {
innerElement.setAttribute('disabled', 'disabled');
}
});
scope.modifierTemplater = $onsen.generateModifierTemplater(attrs);
$onsen.addModifierMethods(toolbarButton, 'toolbar-button--*', element.children());
element.children('span').addClass(modifierTemplater('toolbar-button--*'));
$onsen.cleaner.onDestroy(scope, function() {
$onsen.clearComponent({
scope: scope,
attrs: attrs,
element: element,
});
scope = element = attrs = null;
});
},
post: function(scope, element, attrs) {
$onsen.fireComponentEvent(element[0], 'init');
}
}
};
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
var ComponentCleaner = {
/**
* @param {jqLite} element
*/
decomposeNode: function(element) {
var children = element.remove().children();
for (var i = 0; i < children.length; i++) {
ComponentCleaner.decomposeNode(angular.element(children[i]));
}
},
/**
* @param {Attributes} attrs
*/
destroyAttributes: function(attrs) {
attrs.$$element = null;
attrs.$$observers = null;
},
/**
* @param {jqLite} element
*/
destroyElement: function(element) {
element.remove();
},
/**
* @param {Scope} scope
*/
destroyScope: function(scope) {
scope.$$listeners = {};
scope.$$watchers = null;
scope = null;
},
/**
* @param {Scope} scope
* @param {Function} fn
*/
onDestroy: function(scope, fn) {
var clear = scope.$on('$destroy', function() {
clear();
fn.apply(null, arguments);
});
}
};
module.factory('ComponentCleaner', function() {
return ComponentCleaner;
});
// override builtin ng-(eventname) directives
(function() {
var ngEventDirectives = {};
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' ').forEach(
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return {
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
var listener = function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
};
element.on(name, listener);
ComponentCleaner.onDestroy(scope, function() {
element.off(name, listener);
element = null;
ComponentCleaner.destroyScope(scope);
scope = null;
ComponentCleaner.destroyAttributes(attr);
attr = null;
});
};
}
};
}];
function directiveNormalize(name) {
return name.replace(/-([a-z])/g, function(matches) {
return matches[1].toUpperCase();
});
}
}
);
module.config(['$provide', function($provide) {
var shift = function($delegate) {
$delegate.shift();
return $delegate;
};
Object.keys(ngEventDirectives).forEach(function(directiveName) {
$provide.decorator(directiveName + 'Directive', ['$delegate', shift]);
});
}]);
Object.keys(ngEventDirectives).forEach(function(directiveName) {
module.directive(directiveName, ngEventDirectives[directiveName]);
});
})();
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var util = {
init: function() {
this.ready = false;
},
addBackButtonListener: function(fn) {
if (this._ready) {
window.document.addEventListener('backbutton', fn, false);
} else {
window.document.addEventListener('deviceready', function() {
window.document.addEventListener('backbutton', fn, false);
});
}
},
removeBackButtonListener: function(fn) {
if (this._ready) {
window.document.removeEventListener('backbutton', fn, false);
} else {
window.document.addEventListener('deviceready', function() {
window.document.removeEventListener('backbutton', fn, false);
});
}
}
};
util.init();
/**
* Internal service class for framework implementation.
*/
angular.module('onsen').service('DeviceBackButtonHandler', function() {
this._init = function() {
if (window.ons.isWebView()) {
window.document.addEventListener('deviceready', function() {
util._ready = true;
}, false);
} else {
util._ready = true;
}
this._bindedCallback = this._callback.bind(this);
this.enable();
};
this._isEnabled = false;
/**
* Enable to handle 'backbutton' events.
*/
this.enable = function() {
if (!this._isEnabled) {
util.addBackButtonListener(this._bindedCallback);
this._isEnabled = true;
}
};
/**
* Disable to handle 'backbutton' events.
*/
this.disable = function() {
if (this._isEnabled) {
util.removeBackButtonListener(this._bindedCallback);
this._isEnabled = false;
}
};
/**
* Fire a 'backbutton' event manually.
*/
this.fireDeviceBackButtonEvent = function() {
var event = document.createEvent('Event');
event.initEvent('backbutton', true, true);
document.dispatchEvent(event);
};
this._callback = function() {
this._dispatchDeviceBackButtonEvent();
};
/**
* @param {jqLite} element
* @param {Function} callback
*/
this.create = function(element, callback) {
if (!(element instanceof angular.element().constructor)) {
throw new Error('element must be an instance of jqLite');
}
if (!(callback instanceof Function)) {
throw new Error('callback must be an instance of Function');
}
var handler = {
_callback: callback,
_element: element,
disable: function() {
this._element.data('device-backbutton-handler', null);
},
setListener: function(callback) {
this._callback = callback;
},
enable: function() {
this._element.data('device-backbutton-handler', this);
},
isEnabled: function() {
return this._element.data('device-backbutton-handler') === this;
},
destroy: function() {
this._element.data('device-backbutton-handler', null);
this._callback = this._element = null;
}
};
handler.enable();
return handler;
};
/**
* @param {Object} event
*/
this._dispatchDeviceBackButtonEvent = function(event) {
var tree = this._captureTree();
var element = this._findHandlerLeafElement(tree);
//this._dumpTree(tree);
//this._dumpParents(element);
var handler = element.data('device-backbutton-handler');
handler._callback(createEvent(element));
function createEvent(element) {
return {
_element: element,
callParentHandler: function() {
var parent = this._element.parent();
var hander = null;
while (parent[0]) {
handler = parent.data('device-backbutton-handler');
if (handler) {
return handler._callback(createEvent(parent));
}
parent = parent.parent();
}
}
};
}
};
this._dumpParents = function(element) {
while(element[0]) {
console.log(element[0].nodeName.toLowerCase() + '.' + element.attr('class'));
element = element.parent();
}
};
/**
* @return {Object}
*/
this._captureTree = function() {
return createTree(angular.element(document.body));
function createTree(element) {
return {
element: element,
children: Array.prototype.concat.apply([], Array.prototype.map.call(element.children(), function(child) {
child = angular.element(child);
if (child[0].style.display === 'none') {
return [];
}
if (child.children().length === 0 && !child.data('device-backbutton-handler')) {
return [];
}
var result = createTree(child);
if (result.children.length === 0 && !child.data('device-backbutton-handler')) {
return [];
}
return [result];
}))
};
}
};
this._dumpTree = function(node) {
_dump(node, 0);
function _dump(node, level) {
var pad = new Array(level + 1).join(' ');
console.log(pad + node.element[0].nodeName.toLowerCase());
node.children.forEach(function(node) {
_dump(node, level + 1);
});
}
};
/**
* @param {Object} tree
* @return {jqLite}
*/
this._findHandlerLeafElement = function(tree) {
return find(tree);
function find(node) {
if (node.children.length === 0) {
return node.element;
}
if (node.children.length === 1) {
return find(node.children[0]);
}
return node.children.map(function(childNode) {
return childNode.element;
}).reduce(function(left, right) {
if (left === null) {
return right;
}
var leftZ = parseInt(window.getComputedStyle(left[0], '').zIndex, 10);
var rightZ = parseInt(window.getComputedStyle(right[0], '').zIndex, 10);
if (!isNaN(leftZ) && !isNaN(rightZ)) {
return leftZ > rightZ ? left : right;
}
throw new Error('Capturing backbutton-handler is failure.');
}, null);
}
};
this._init();
});
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
var module = angular.module('onsen');
/**
* Internal service class for framework implementation.
*/
module.factory('$onsen', ['$rootScope', '$window', '$cacheFactory', '$document', '$templateCache', '$http', '$q', '$onsGlobal', 'ComponentCleaner', 'DeviceBackButtonHandler', function($rootScope, $window, $cacheFactory, $document, $templateCache, $http, $q, $onsGlobal, ComponentCleaner, DeviceBackButtonHandler) {
var unlockerDict = createUnlockerDict();
var $onsen = createOnsenService();
return $onsen;
function createOnsenService() {
return {
DIRECTIVE_TEMPLATE_URL: 'templates',
cleaner: ComponentCleaner,
DeviceBackButtonHandler: DeviceBackButtonHandler,
_defaultDeviceBackButtonHandler: DeviceBackButtonHandler.create(angular.element(document.body), function() {
navigator.app.exitApp();
}),
getDefaultDeviceBackButtonHandler: function() {
return this._defaultDeviceBackButtonHandler;
},
/**
* @return {Boolean}
*/
isEnabledAutoStatusBarFill: function() {
return !!$onsGlobal._config.autoStatusBarFill;
},
/**
* @param {HTMLElement} element
* @return {Boolean}
*/
shouldFillStatusBar: function(element) {
if (this.isEnabledAutoStatusBarFill() && this.isWebView() && this.isIOS7Above()) {
if (!(element instanceof HTMLElement)) {
throw new Error('element must be an instance of HTMLElement');
}
var debug = element.tagName === 'ONS-TABBAR' ? console.log.bind(console) : angular.noop;
for (;;) {
if (element.hasAttribute('no-status-bar-fill')) {
return false;
}
element = element.parentNode;
debug(element);
if (!element || !element.hasAttribute) {
return true;
}
}
}
return false;
},
/**
* @param {Object} params
* @param {Scope} [params.scope]
* @param {jqLite} [params.element]
* @param {Array} [params.elements]
* @param {Attributes} [params.attrs]
*/
clearComponent: function(params) {
if (params.scope) {
ComponentCleaner.destroyScope(params.scope);
}
if (params.attrs) {
ComponentCleaner.destroyAttributes(params.attrs);
}
if (params.element) {
ComponentCleaner.destroyElement(params.element);
}
if (params.elements) {
params.elements.forEach(function(element) {
ComponentCleaner.destroyElement(element);
});
}
},
/**
* Find first ancestor of el with tagName
* or undefined if not found
*
* @param {jqLite} element
* @param {String} tagName
*/
upTo : function(el, tagName) {
tagName = tagName.toLowerCase();
do {
if (!el) {
return null;
}
el = el.parentNode;
if (el.tagName.toLowerCase() == tagName) {
return el;
}
} while (el.parentNode);
return null;
},
/**
* @param {Array} dependencies
* @param {Function} callback
*/
waitForVariables: function(dependencies, callback) {
unlockerDict.addCallback(dependencies, callback);
},
/**
* @param {jqLite} element
* @param {String} name
*/
findElementeObject: function(element, name) {
return element.inheritedData(name);
},
/**
* @param {String} page
* @return {Promise}
*/
getPageHTMLAsync: function(page) {
var cache = $templateCache.get(page);
if (cache) {
var deferred = $q.defer();
var html = typeof cache === 'string' ? cache : cache[1];
deferred.resolve(this.normalizePageHTML(html));
return deferred.promise;
} else {
return $http({
url: page,
method: 'GET'
}).then(function(response) {
var html = response.data;
return this.normalizePageHTML(html);
}.bind(this));
}
},
/**
* @param {String} html
* @return {String}
*/
normalizePageHTML: function(html) {
html = ('' + html).trim();
if (!html.match(/^<(ons-page|ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/)) {
html = '<ons-page>' + html + '</ons-page>';
}
return html;
},
/**
* Create modifier templater function. The modifier templater generate css classes binded modifier name.
*
* @param {Object} attrs
* @param {Array} [modifiers] an array of appendix modifier
* @return {Function}
*/
generateModifierTemplater: function(attrs, modifiers) {
var attrModifiers = attrs && typeof attrs.modifier === 'string' ? attrs.modifier.trim().split(/ +/) : [];
modifiers = angular.isArray(modifiers) ? attrModifiers.concat(modifiers) : attrModifiers;
/**
* @return {String} template eg. 'ons-button--*', 'ons-button--*__item'
* @return {String}
*/
return function(template) {
return modifiers.map(function(modifier) {
return template.replace('*', modifier);
}).join(' ');
};
},
/**
* Add modifier methods to view object.
*
* @param {Object} view object
* @param {String} template
* @param {jqLite} element
*/
addModifierMethods: function(view, template, element) {
var _tr = function(modifier) {
return template.replace('*', modifier);
};
var fns = {
hasModifier: function(modifier) {
return element.hasClass(_tr(modifier));
},
removeModifier: function(modifier) {
element.removeClass(_tr(modifier));
},
addModifier: function(modifier) {
element.addClass(_tr(modifier));
},
setModifier: function(modifier) {
var classes = element.attr('class').split(/\s+/),
patt = template.replace('*', '.');
for (var i=0; i < classes.length; i++) {
var cls = classes[i];
if (cls.match(patt)) {
element.removeClass(cls);
}
}
element.addClass(_tr(modifier));
},
toggleModifier: function(modifier) {
var cls = _tr(modifier);
if (element.hasClass(cls)) {
element.removeClass(cls);
} else {
element.addClass(cls);
}
}
};
var append = function(oldFn, newFn) {
if (typeof oldFn !== 'undefined') {
return function() {
return oldFn.apply(null, arguments) || newFn.apply(null, arguments);
};
} else {
return newFn;
}
};
view.hasModifier = append(view.hasModifier, fns.hasModifier);
view.removeModifier = append(view.removeModifier, fns.removeModifier);
view.addModifier = append(view.addModifier, fns.addModifier);
view.setModifier = append(view.setModifier, fns.setModifier);
view.toggleModifier = append(view.toggleModifier, fns.toggleModifier);
},
/**
* Remove modifier methods.
*
* @param {Object} view object
*/
removeModifierMethods: function(view) {
view.hasModifier = view.removeModifier =
view.addModifier = view.setModifier =
view.toggleModifier = undefined;
},
/**
* Define a variable to JavaScript global scope and AngularJS scope as 'var' attribute name.
*
* @param {Object} attrs
* @param object
*/
declareVarAttribute: function(attrs, object) {
if (typeof attrs['var'] === 'string') {
var varName = attrs['var'];
this._defineVar(varName, object);
unlockerDict.unlockVarName(varName);
}
},
_registerEventHandler: function(component, eventName) {
var capitalizedEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1);
component.on(eventName, function(event) {
$onsen.fireComponentEvent(component._element[0], eventName, event);
var handler = component._attrs['ons' + capitalizedEventName];
if (handler) {
component._scope.$eval(handler, {$event: event});
component._scope.$evalAsync();
}
});
},
/**
* Register event handlers for attributes.
*
* @param {Object} component
* @param {String} eventNames
*/
registerEventHandlers: function(component, eventNames) {
eventNames = eventNames.trim().split(/\s+/);
for (var i = 0, l = eventNames.length; i < l; i ++) {
var eventName = eventNames[i];
this._registerEventHandler(component, eventName);
}
},
/**
* @return {Boolean}
*/
isAndroid: function() {
return !!window.navigator.userAgent.match(/android/i);
},
/**
* @return {Boolean}
*/
isIOS: function() {
return !!window.navigator.userAgent.match(/(ipad|iphone|ipod touch)/i);
},
/**
* @return {Boolean}
*/
isWebView: function() {
return window.ons.isWebView();
},
/**
* @return {Boolean}
*/
isIOS7Above: (function() {
var ua = window.navigator.userAgent;
var match = ua.match(/(iPad|iPhone|iPod touch);.*CPU.*OS (\d+)_(\d+)/i);
var result = match ? parseFloat(match[2] + '.' + match[3]) >= 7 : false;
return function() {
return result;
};
})(),
/**
* Fire a named event for a component. The view object, if it exists, is attached to event.component.
*
* @param {HTMLElement} [dom]
* @param {String} event name
*/
fireComponentEvent: function(dom, eventName, data) {
data = data || {};
var event = document.createEvent('HTMLEvents');
for (var key in data) {
if (data.hasOwnProperty(key)) {
event[key] = data[key];
}
}
event.component = dom ?
angular.element(dom).data(dom.nodeName.toLowerCase()) || null : null;
event.initEvent(dom.nodeName.toLowerCase() + ':' + eventName, true, true);
dom.dispatchEvent(event);
},
/**
* Define a variable to JavaScript global scope and AngularJS scope.
*
* Util.defineVar('foo', 'foo-value');
* // => window.foo and $scope.foo is now 'foo-value'
*
* Util.defineVar('foo.bar', 'foo-bar-value');
* // => window.foo.bar and $scope.foo.bar is now 'foo-bar-value'
*
* @param {String} name
* @param object
*/
_defineVar: function(name, object) {
var names = name.split(/\./);
function set(container, names, object) {
var name;
for (var i = 0; i < names.length - 1; i++) {
name = names[i];
if (container[name] === undefined || container[name] === null) {
container[name] = {};
}
container = container[name];
}
container[names[names.length - 1]] = object;
if (container[names[names.length -1]] !== object) {
throw new Error('Cannot set var="' + object._attrs.var + '" because it will overwrite a read-only variable.');
}
}
if (ons.componentBase) {
set(ons.componentBase, names, object);
}
set($rootScope, names, object);
}
};
}
function createUnlockerDict() {
return {
_unlockersDict: {},
_unlockedVarDict: {},
/**
* @param {String} name
* @param {Function} unlocker
*/
_addVarLock: function (name, unlocker) {
if (!(unlocker instanceof Function)) {
throw new Error('unlocker argument must be an instance of Function.');
}
if (this._unlockersDict[name]) {
this._unlockersDict[name].push(unlocker);
} else {
this._unlockersDict[name] = [unlocker];
}
},
/**
* @param {String} varName
*/
unlockVarName: function(varName) {
var unlockers = this._unlockersDict[varName];
if (unlockers) {
unlockers.forEach(function(unlock) {
unlock();
});
}
this._unlockedVarDict[varName] = true;
},
/**
* @param {Array} dependencies an array of var name
* @param {Function} callback
*/
addCallback: function(dependencies, callback) {
if (!(callback instanceof Function)) {
throw new Error('callback argument must be an instance of Function.');
}
var doorLock = new DoorLock();
var self = this;
dependencies.forEach(function(varName) {
if (!self._unlockedVarDict[varName]) {
// wait for variable declaration
var unlock = doorLock.lock();
self._addVarLock(varName, unlock);
}
});
if (doorLock.isLocked()) {
doorLock.waitUnlock(callback);
} else {
callback();
}
}
};
}
}]);
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
/**
* Minimal animation library for managing css transition on mobile browsers.
*/
window.animit = (function(){
'use strict';
/**
* @param {HTMLElement} element
*/
var Animit = function(element) {
if (!(this instanceof Animit)) {
return new Animit(element);
}
if (element instanceof HTMLElement) {
this.elements = [element];
} else if (Object.prototype.toString.call(element) === '[object Array]') {
this.elements = element;
} else {
throw new Error('First argument must be an array or an instance of HTMLElement.');
}
this.transitionQueue = [];
this.lastStyleAttributeDict = [];
var self = this;
this.elements.forEach(function(element, index) {
if (!element.hasAttribute('data-animit-orig-style')) {
self.lastStyleAttributeDict[index] = element.getAttribute('style');
element.setAttribute('data-animit-orig-style', self.lastStyleAttributeDict[index] || '');
} else {
self.lastStyleAttributeDict[index] = element.getAttribute('data-animit-orig-style');
}
});
};
Animit.prototype = {
/**
* @property {Array}
*/
transitionQueue: undefined,
/**
* @property {HTMLElement}
*/
element: undefined,
/**
* Start animation sequence with passed animations.
*
* @param {Function} callback
*/
play: function(callback) {
if (typeof callback === 'function') {
this.transitionQueue.push(function(done) {
callback();
done();
});
}
this.startAnimation();
return this;
},
/**
* Queue transition animations or other function.
*
* e.g. animit(elt).queue({color: 'red'})
* e.g. animit(elt).queue({color: 'red'}, {duration: 0.4})
* e.g. animit(elt).queue({css: {color: 'red'}, duration: 0.2})
*
* @param {Object|Animit.Transition|Function} transition
* @param {Object} [options]
*/
queue: function(transition, options) {
var queue = this.transitionQueue;
if (transition && options) {
options.css = transition;
transition = new Animit.Transition(options);
}
if (!(transition instanceof Function || transition instanceof Animit.Transition)) {
if (transition.css) {
transition = new Animit.Transition(transition);
} else {
transition = new Animit.Transition({
css: transition
});
}
}
if (transition instanceof Function) {
queue.push(transition);
} else if (transition instanceof Animit.Transition) {
queue.push(transition.build());
} else {
throw new Error('Invalid arguments');
}
return this;
},
/**
* Queue transition animations.
*
* @param {Float} seconds
*/
wait: function(seconds) {
var self = this;
this.transitionQueue.push(function(done) {
setTimeout(done, 1000 * seconds);
});
return this;
},
/**
* Reset element's style.
*
* @param {Object} [options]
* @param {Float} [options.duration]
* @param {String} [options.timing]
* @param {String} [options.transition]
*/
resetStyle: function(options) {
options = options || {};
var self = this;
if (options.transition && !options.duration) {
throw new Error('"options.duration" is required when "options.transition" is enabled.');
}
if (options.transition || (options.duration && options.duration > 0)) {
var transitionValue = options.transition || ('all ' + options.duration + 's ' + (options.timing || 'linear'));
var transitionStyle = 'transition: ' + transitionValue + '; -' + Animit.prefix + '-transition: ' + transitionValue + ';';
this.transitionQueue.push(function(done) {
var elements = this.elements;
// transition and style settings
elements.forEach(function(element, index) {
element.style[Animit.prefix + 'Transition'] = transitionValue;
element.style.transition = transitionValue;
var styleValue = (self.lastStyleAttributeDict[index] ? self.lastStyleAttributeDict[index] + '; ' : '') + transitionStyle;
element.setAttribute('style', styleValue);
});
// add "transitionend" event handler
var removeListeners = util.addOnTransitionEnd(elements[0], function() {
clearTimeout(timeoutId);
reset();
done();
});
// for fail safe.
var timeoutId = setTimeout(function() {
removeListeners();
reset();
done();
}, options.duration * 1000 * 1.4);
});
} else {
this.transitionQueue.push(function(done) {
reset();
done();
});
}
return this;
function reset() {
// Clear transition animation settings.
self.elements.forEach(function(element, index) {
element.style[Animit.prefix + 'Transition'] = 'none';
element.style.transition = 'none';
if (self.lastStyleAttributeDict[index]) {
element.setAttribute('style', self.lastStyleAttributeDict[index]);
} else {
element.setAttribute('style', '');
element.removeAttribute('style');
}
});
}
},
/**
* Start animation sequence.
*/
startAnimation: function() {
this._dequeueTransition();
return this;
},
_dequeueTransition: function() {
var transition = this.transitionQueue.shift();
if (this._currentTransition) {
throw new Error('Current transition exists.');
}
this._currentTransition = transition;
var self = this;
var called = false;
var done = function() {
if (!called) {
called = true;
self._currentTransition = undefined;
self._dequeueTransition();
} else {
throw new Error('Invalid state: This callback is called twice.');
}
};
if (transition) {
transition.call(this, done);
}
}
};
Animit.cssPropertyDict = (function() {
var styles = window.getComputedStyle(document.documentElement, '');
var dict = {};
var a = 'A'.charCodeAt(0);
var z = 'z'.charCodeAt(0);
for (var key in styles) {
if (styles.hasOwnProperty(key)) {
var char = key.charCodeAt(0);
if (a <= key.charCodeAt(0) && z >= key.charCodeAt(0)) {
if (key !== 'cssText' && key !== 'parentText' && key !== 'length') {
dict[key] = true;
}
}
}
}
return dict;
})();
Animit.hasCssProperty = function(name) {
return !!Animit.cssPropertyDict[name];
};
/**
* Vendor prefix for css property.
*/
Animit.prefix = (function() {
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1];
return pre;
})();
/**
* @param {Animit} arguments
*/
Animit.runAll = function(/* arguments... */) {
for (var i = 0; i < arguments.length; i++) {
arguments[i].play();
}
};
/**
* @param {Object} options
* @param {Float} [options.duration]
* @param {String} [options.property]
* @param {String} [options.timing]
*/
Animit.Transition = function(options) {
this.options = options || {};
this.options.duration = this.options.duration || 0;
this.options.timing = this.options.timing || 'linear';
this.options.css = this.options.css || {};
this.options.property = this.options.property || 'all';
};
Animit.Transition.prototype = {
/**
* @param {HTMLElement} element
* @return {Function}
*/
build: function() {
if (Object.keys(this.options.css).length === 0) {
throw new Error('options.css is required.');
}
var css = createActualCssProps(this.options.css);
if (this.options.duration > 0) {
var transitionValue = util.buildTransitionValue(this.options);
var self = this;
return function(callback) {
var elements = this.elements;
var timeout = self.options.duration * 1000 * 1.4;
var removeListeners = util.addOnTransitionEnd(elements[0], function() {
clearTimeout(timeoutId);
callback();
});
var timeoutId = setTimeout(function() {
removeListeners();
callback();
}, timeout);
elements.forEach(function(element, index) {
element.style[Animit.prefix + 'Transition'] = transitionValue;
element.style.transition = transitionValue;
Object.keys(css).forEach(function(name) {
element.style[name] = css[name];
});
});
};
}
if (this.options.duration <= 0) {
return function(callback) {
var elements = this.elements;
elements.forEach(function(element, index) {
element.style[Animit.prefix + 'Transition'] = 'none';
element.transition = 'none';
Object.keys(css).forEach(function(name) {
element.style[name] = css[name];
});
});
if (elements.length) {
elements[0].offsetHeight;
}
if (window.requestAnimationFrame) {
requestAnimationFrame(callback);
} else {
setTimeout(callback, 1000 / 30);
}
};
}
function createActualCssProps(css) {
var result = {};
Object.keys(css).forEach(function(name) {
var value = css[name];
name = util.normalizeStyleName(name);
var prefixed = Animit.prefix + util.capitalize(name);
if (Animit.cssPropertyDict[name]) {
result[name] = value;
} else if (Animit.cssPropertyDict[prefixed]) {
result[prefixed] = value;
} else {
result[prefixed] = value;
result[name] = value;
}
});
return result;
}
}
};
var util = {
/**
* Normalize style property name.
*/
normalizeStyleName: function(name) {
name = name.replace(/-[a-zA-Z]/g, function(all) {
return all.slice(1).toUpperCase();
});
return name.charAt(0).toLowerCase() + name.slice(1);
},
// capitalize string
capitalize : function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
},
/**
* @param {Object} params
* @param {String} params.property
* @param {Float} params.duration
* @param {String} params.timing
*/
buildTransitionValue: function(params) {
params.property = params.property || 'all';
params.duration = params.duration || 0.4;
params.timing = params.timing || 'linear';
var props = params.property.split(/ +/);
return props.map(function(prop) {
return prop + ' ' + params.duration + 's ' + params.timing;
}).join(', ');
},
/**
* Add an event handler on "transitionend" event.
*/
addOnTransitionEnd: function(element, callback) {
if (!element) {
return function() {};
}
var fn = function(event) {
if (element == event.target) {
event.stopPropagation();
removeListeners();
callback();
}
};
var removeListeners = function() {
util._transitionEndEvents.forEach(function(eventName) {
element.removeEventListener(eventName, fn);
});
};
util._transitionEndEvents.forEach(function(eventName) {
element.addEventListener(eventName, fn, false);
});
return removeListeners;
},
_transitionEndEvents: (function() {
if (Animit.prefix === 'webkit' || Animit.prefix === 'o' || Animit.prefix === 'moz' || Animit.prefix === 'ms') {
return [Animit.prefix + 'TransitionEnd', 'transitionend'];
}
return ['transitionend'];
})()
};
return Animit;
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
/**
* @ngdoc object
* @name ons.notification
* @category dialog
* @codepen Qwwxyp
* @description
* [en]Utility methods to create different kinds of alert dialogs. There are three methods available: alert, confirm and prompt.[/en]
* [ja]いくつかの種類のアラートダイアログを作成するためのユーティリティメソッドを収めたオブジェクトです。[/ja]
* @example
* <script>
* ons.notification.alert({
* message: 'Hello, world!'
* });
*
* ons.notification.confirm({
* message: 'Are you ready?'
* callback: function(answer) {
* // Do something here.
* }
* });
*
* ons.notification.prompt({
* message: 'How old are you?',
* callback: function(age) {
* ons.notification.alert({
* message: 'You are ' + age + ' years old.'
* });
* });
* });
* </script>
*/
/**
* @ngdoc method
* @signature alert(options)
* @param {Object} options
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクトです。[/ja]
* @param {String} [options.message]
* [en]Alert message.[/en]
* [ja]アラートダイアログに表示する文字列を指定します。[/ja]
* @param {String} [options.messageHTML]
* [en]Alert message in HTML.[/en]
* [ja]アラートダイアログに表示するHTMLを指定します。[/ja]
* @param {String} [options.buttonLabel]
* [en]Label for confirmation button. Default is "OK".[/en]
* [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "none", "fade" and "slide".[/en]
* [ja]アラートダイアログを表示する際のアニメーション名を指定します。"none", "fade", "slide"のいずれかを指定できます。[/ja]
* @param {String} [options.title]
* [en]Dialog title. Default is "Alert".[/en]
* [ja]アラートダイアログの上部に表示するタイトルを指定します。"Alert"がデフォルトです。[/ja]
* @param {String} [options.modifier]
* [en]Modifier for the dialog.[/en]
* [ja]アラートダイアログのmodifier属性の値を指定します。[/ja]
* @param {Function} [options.callback]
* [en]Function that executes after dialog has been closed.[/en]
* [ja]アラートダイアログが閉じられた時に呼び出される関数オブジェクトを指定します。[/ja]
* @description
* [en]
* Display an alert dialog to show the user a message.
* The content of the message can be either simple text or HTML.
* Must specify either message or messageHTML.
* [/en]
* [ja]
* ユーザーへメッセージを見せるためのアラートダイアログを表示します。
* 表示するメッセージは、テキストかもしくはHTMLを指定できます。
* このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。
* [/ja]
*/
/**
* @ngdoc method
* @signature confirm(options)
* @param {Object} options
* [en]Parameter object.[/en]
* @param {String} [options.message]
* [en]Confirmation question.[/en]
* [ja]確認ダイアログに表示するメッセージを指定します。[/ja]
* @param {String} [options.messageHTML]
* [en]Dialog content in HTML.[/en]
* [ja]確認ダイアログに表示するHTMLを指定します。[/ja]
* @param {Array} [options.buttonLabels]
* [en]Labels for the buttons. Default is ["Cancel", "OK"].[/en]
* [ja]ボタンのラベルの配列を指定します。["Cancel", "OK"]がデフォルトです。[/ja]
* @param {Number} [options.primaryButtonIndex]
* [en]Index of primary button. Default is 1.[/en]
* [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja]
* @param {Boolean} [options.cancelable]
* [en]Whether the dialog is cancelable or not. Default is false.[/en]
* [ja]ダイアログがキャンセル可能かどうかを指定します。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "none", "fade" and "slide".[/en]
* [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja]
* @param {String} [options.title]
* [en]Dialog title. Default is "Confirm".[/en]
* [ja]ダイアログのタイトルを指定します。"Confirm"がデフォルトです。[/ja]
* @param {String} [options.modifier]
* [en]Modifier for the dialog.[/en]
* [ja]ダイアログのmodifier属性の値を指定します。[/ja]
* @param {Function} [options.callback]
* [en]
* Function that executes after the dialog has been closed.
* Argument for the function is the index of the button that was pressed or -1 if the dialog was canceled.
* [/en]
* [ja]
* ダイアログが閉じられた後に呼び出される関数オブジェクトを指定します。
* この関数の引数として、押されたボタンのインデックス値が渡されます。
* もしダイアログがキャンセルされた場合には-1が渡されます。
* [/ja]
* @description
* [en]
* Display a dialog to ask the user for confirmation.
* The default button labels are "Cancel" and "OK" but they can be customized.
* Must specify either message or messageHTML.
* [/en]
* [ja]
* ユーザに確認を促すダイアログを表示します。
* デオルとのボタンラベルは、"Cancel"と"OK"ですが、これはこのメソッドの引数でカスタマイズできます。
* このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。
* [/ja]
*/
/**
* @ngdoc method
* @signature prompt(options)
* @param {Object} options
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクトです。[/ja]
* @param {String} [options.message]
* [en]Prompt question.[/en]
* [ja]ダイアログに表示するメッセージを指定します。[/ja]
* @param {String} [options.messageHTML]
* [en]Dialog content in HTML.[/en]
* [ja]ダイアログに表示するHTMLを指定します。[/ja]
* @param {String} [options.buttonLabel]
* [en]Label for confirmation button. Default is "OK".[/en]
* [ja]確認ボタンのラベルを指定します。"OK"がデフォルトです。[/ja]
* @param {Number} [options.primaryButtonIndex]
* [en]Index of primary button. Default is 1.[/en]
* [ja]プライマリボタンのインデックスを指定します。デフォルトは 1 です。[/ja]
* @param {Boolean} [options.cancelable]
* [en]Whether the dialog is cancelable or not. Default is false.[/en]
* [ja]ダイアログがキャンセル可能かどうかを指定します。デフォルトは false です。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are "none", "fade" and "slide".[/en]
* [ja]アニメーション名を指定します。"none", "fade", "slide"のいずれかを指定します。[/ja]
* @param {String} [options.title]
* [en]Dialog title. Default is "Alert".[/en]
* [ja]ダイアログのタイトルを指定します。デフォルトは "Alert" です。[/ja]
* @param {String} [options.modifier]
* [en]Modifier for the dialog.[/en]
* [ja]ダイアログのmodifier属性の値を指定します。[/ja]
* @param {Function} [options.callback]
* [en]
* Function that executes after the dialog has been closed.
* Argument for the function is the value of the input field or null if the dialog was canceled.
* [/en]
* [ja]
* ダイアログが閉じられた後に実行される関数オブジェクトを指定します。
* 関数の引数として、インプット要素の中の値が渡されます。ダイアログがキャンセルされた場合には、nullが渡されます。
* [/ja]
* @description
* [en]
* Display a dialog with a prompt to ask the user a question.
* Must specify either message or messageHTML.
* [/en]
* [ja]
* ユーザーに入力を促すダイアログを表示します。
* このメソッドの引数には、options.messageもしくはoptions.messageHTMLのどちらかを必ず指定する必要があります。
* [/ja]
*/
window.ons.notification = (function() {
var createAlertDialog = function(title, message, buttonLabels, primaryButtonIndex, modifier, animation, callback, messageIsHTML, cancelable, promptDialog, autofocus, placeholder) {
var dialogEl = angular.element('<ons-alert-dialog>'),
titleEl = angular.element('<div>').addClass('alert-dialog-title').text(title),
messageEl = angular.element('<div>').addClass('alert-dialog-content'),
footerEl = angular.element('<div>').addClass('alert-dialog-footer'),
inputEl;
if (modifier) {
dialogEl.attr('modifier', modifier);
}
dialogEl.attr('animation', animation);
if (messageIsHTML) {
messageEl.html(message);
} else {
messageEl.text(message);
}
dialogEl.append(titleEl).append(messageEl);
if (promptDialog) {
inputEl = angular.element('<input>')
.addClass('text-input')
.attr('placeholder', placeholder)
.css({width: '100%', marginTop: '10px'});
messageEl.append(inputEl);
}
dialogEl.append(footerEl);
angular.element(document.body).append(dialogEl);
ons.$compile(dialogEl)(dialogEl.injector().get('$rootScope'));
var alertDialog = dialogEl.data('ons-alert-dialog');
if (buttonLabels.length <= 2) {
footerEl.addClass('alert-dialog-footer--one');
}
var createButton = function(i) {
var buttonEl = angular.element('<button>').addClass('alert-dialog-button').text(buttonLabels[i]);
if (i == primaryButtonIndex) {
buttonEl.addClass('alert-dialog-button--primal');
}
if (buttonLabels.length <= 2) {
buttonEl.addClass('alert-dialog-button--one');
}
buttonEl.on('click', function() {
buttonEl.off('click');
alertDialog.hide({
callback: function() {
if (promptDialog) {
callback(inputEl.val());
} else {
callback(i);
}
alertDialog.destroy();
alertDialog = inputEl = buttonEl = null;
}
});
});
footerEl.append(buttonEl);
};
for (var i = 0; i < buttonLabels.length; i++) {
createButton(i);
}
if (cancelable) {
alertDialog.setCancelable(cancelable);
alertDialog.on('cancel', function() {
if(promptDialog) {
callback(null);
} else {
callback(-1);
}
setTimeout(function() {
alertDialog.destroy();
alertDialog = null;
inputEl = null;
});
});
}
alertDialog.show({
callback: function() {
if(promptDialog && autofocus) {
inputEl[0].focus();
}
}
});
dialogEl = titleEl = messageEl = footerEl = null;
};
return {
/**
* @param {Object} options
* @param {String} [options.message]
* @param {String} [options.messageHTML]
* @param {String} [options.buttonLabel]
* @param {String} [options.animation]
* @param {String} [options.title]
* @param {String} [options.modifier]
* @param {Function} [options.callback]
*/
alert: function(options) {
var defaults = {
buttonLabel: 'OK',
animation: 'default',
title: 'Alert',
callback: function() {}
};
options = angular.extend({}, defaults, options);
if (!options.message && !options.messageHTML) {
throw new Error('Alert dialog must contain a message.');
}
createAlertDialog(
options.title,
options.message || options.messageHTML,
[options.buttonLabel],
0,
options.modifier,
options.animation,
options.callback,
!options.message ? true : false,
false, false, false
);
},
/**
* @param {Object} options
* @param {String} [options.message]
* @param {String} [options.messageHTML]
* @param {Array} [options.buttonLabels]
* @param {Number} [options.primaryButtonIndex]
* @param {Boolean} [options.cancelable]
* @param {String} [options.animation]
* @param {String} [options.title]
* @param {String} [options.modifier]
* @param {Function} [options.callback]
*/
confirm: function(options) {
var defaults = {
buttonLabels: ['Cancel', 'OK'],
primaryButtonIndex: 1,
animation: 'default',
title: 'Confirm',
callback: function() {},
cancelable: false
};
options = angular.extend({}, defaults, options);
if (!options.message && !options.messageHTML) {
throw new Error('Confirm dialog must contain a message.');
}
createAlertDialog(
options.title,
options.message || options.messageHTML,
options.buttonLabels,
options.primaryButtonIndex,
options.modifier,
options.animation,
options.callback,
!options.message ? true : false,
options.cancelable,
false, false
);
},
/**
* @param {Object} options
* @param {String} [options.message]
* @param {String} [options.messageHTML]
* @param {String} [options.buttonLabel]
* @param {Boolean} [options.cancelable]
* @param {String} [options.animation]
* @param {String} [options.placeholder]
* @param {String} [options.title]
* @param {String} [options.modifier]
* @param {Function} [options.callback]
* @param {Boolean} [options.autofocus]
*/
prompt: function(options) {
var defaults = {
buttonLabel: 'OK',
animation: 'default',
title: 'Alert',
placeholder: '',
callback: function() {},
cancelable: false,
autofocus: true,
};
options = angular.extend({}, defaults, options);
if (!options.message && !options.messageHTML) {
throw new Error('Prompt dialog must contain a message.');
}
createAlertDialog(
options.title,
options.message || options.messageHTML,
[options.buttonLabel],
0,
options.modifier,
options.animation,
options.callback,
!options.message ? true : false,
options.cancelable,
true,
options.autofocus,
options.placeholder
);
}
};
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
/**
* @ngdoc object
* @name ons.orientation
* @category util
* @description
* [en]Utility methods for orientation detection.[/en]
* [ja]画面のオリエンテーション検知のためのユーティリティメソッドを収めているオブジェクトです。[/ja]
*/
/**
* @ngdoc event
* @name change
* @description
* [en]Fired when the device orientation changes.[/en]
* [ja]デバイスのオリエンテーションが変化した際に発火します。[/ja]
* @param {Object} event
* [en]Event object.[/en]
* [ja]イベントオブジェクトです。[/ja]
* @param {Boolean} event.isPortrait
* [en]Will be true if the current orientation is portrait mode.[/en]
* [ja]現在のオリエンテーションがportraitの場合にtrueを返します。[/ja]
*/
/**
* @ngdoc method
* @signature isPortrait()
* @return {Boolean}
* [en]Will be true if the current orientation is portrait mode.[/en]
* [ja]オリエンテーションがportraitモードの場合にtrueになります。[/ja]
* @description
* [en]Returns whether the current screen orientation is portrait or not.[/en]
* [ja]オリエンテーションがportraitモードかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature isLandscape()
* @return {Boolean}
* [en]Will be true if the current orientation is landscape mode.[/en]
* [ja]オリエンテーションがlandscapeモードの場合にtrueになります。[/ja]
* @description
* [en]Returns whether the current screen orientation is landscape or not.[/en]
* [ja]オリエンテーションがlandscapeモードかどうかを返します。[/ja]
*/
/**
* @ngdoc method
* @signature on(eventName, listener)
* @description
* [en]Add an event listener.[/en]
* [ja]イベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]このイベントが発火された際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature once(eventName, listener)
* @description
* [en]Add an event listener that's only triggered once.[/en]
* [ja]一度だけ呼び出されるイベントリスナーを追加します。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]イベントが発火した際に呼び出される関数オブジェクトを指定します。[/ja]
*/
/**
* @ngdoc method
* @signature off(eventName, [listener])
* @description
* [en]Remove an event listener. If the listener is not specified all listeners for the event type will be removed.[/en]
* [ja]イベントリスナーを削除します。もしイベントリスナーを指定しなかった場合には、そのイベントに紐づく全てのイベントリスナーが削除されます。[/ja]
* @param {String} eventName
* [en]Name of the event.[/en]
* [ja]イベント名を指定します。[/ja]
* @param {Function} listener
* [en]Function to execute when the event is triggered.[/en]
* [ja]削除するイベントリスナーを指定します。[/ja]
*/
window.ons.orientation = (function() {
return create()._init();
function create() {
var obj = {
// actual implementation to detect if whether current screen is portrait or not
_isPortrait: false,
/**
* @return {Boolean}
*/
isPortrait: function() {
return this._isPortrait();
},
/**
* @return {Boolean}
*/
isLandscape: function() {
return !this.isPortrait();
},
_init: function() {
document.addEventListener('DOMContentLoaded', this._onDOMContentLoaded.bind(this), false);
if ('orientation' in window) {
window.addEventListener('orientationchange', this._onOrientationChange.bind(this), false);
} else {
window.addEventListener('resize', this._onResize.bind(this), false);
}
this._isPortrait = function() {
return window.innerHeight > window.innerWidth;
};
return this;
},
_onDOMContentLoaded: function() {
this._installIsPortraitImplementation();
this.emit('change', {isPortrait: this.isPortrait()});
},
_installIsPortraitImplementation: function() {
var isPortrait = window.innerWidth < window.innerHeight;
if (!('orientation' in window)) {
this._isPortrait = function() {
return window.innerHeight > window.innerWidth;
};
} else if (window.orientation % 180 === 0) {
this._isPortrait = function() {
return Math.abs(window.orientation % 180) === 0 ? isPortrait : !isPortrait;
};
} else {
this._isPortrait = function() {
return Math.abs(window.orientation % 180) === 90 ? isPortrait : !isPortrait;
};
}
},
_onOrientationChange: function() {
var isPortrait = this._isPortrait();
// Wait for the dimensions to change because
// of Android inconsistency.
var nIter = 0;
var interval = setInterval(function() {
nIter++;
var w = window.innerWidth,
h = window.innerHeight;
if ((isPortrait && w <= h) ||
(!isPortrait && w >= h)) {
this.emit('change', {isPortrait: isPortrait});
clearInterval(interval);
}
else if (nIter === 50) {
this.emit('change', {isPortrait: isPortrait});
clearInterval(interval);
}
}.bind(this), 20);
},
// Run on not mobile browser.
_onResize: function() {
this.emit('change', {isPortrait: this.isPortrait()});
}
};
MicroEvent.mixin(obj);
return obj;
}
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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.
*/
/**
* @ngdoc object
* @name ons.platform
* @category util
* @description
* [en]Utility methods to detect current platform.[/en]
* [ja]現在実行されているプラットフォームを検知するためのユーティリティメソッドを収めたオブジェクトです。[/ja]
*/
/**
* @ngdoc method
* @signature isWebView()
* @description
* [en]Returns whether app is running in Cordova.[/en]
* [ja]Cordova内で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isIOS()
* @description
* [en]Returns whether the OS is iOS.[/en]
* [ja]iOS上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isAndroid()
* @description
* [en]Returns whether the OS is Android.[/en]
* [ja]Android上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isIPhone()
* @description
* [en]Returns whether the device is iPhone.[/en]
* [ja]iPhone上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isIPad()
* @description
* [en]Returns whether the device is iPad.[/en]
* [ja]iPad上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isBlackBerry()
* @description
* [en]Returns whether the device is BlackBerry.[/en]
* [ja]BlackBerry上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isOpera()
* @description
* [en]Returns whether the browser is Opera.[/en]
* [ja]Opera上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isFirefox()
* @description
* [en]Returns whether the browser is Firefox.[/en]
* [ja]Firefox上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isSafari()
* @description
* [en]Returns whether the browser is Safari.[/en]
* [ja]Safari上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isChrome()
* @description
* [en]Returns whether the browser is Chrome.[/en]
* [ja]Chrome上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isIE()
* @description
* [en]Returns whether the browser is Internet Explorer.[/en]
* [ja]Internet Explorer上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
/**
* @ngdoc method
* @signature isIOS7above()
* @description
* [en]Returns whether the iOS version is 7 or above.[/en]
* [ja]iOS7以上で実行されているかどうかを返します。[/ja]
* @return {Boolean}
*/
(function() {
'use strict';
window.ons.platform = {
/**
* @return {Boolean}
*/
isWebView: function() {
return ons.isWebView();
},
/**
* @return {Boolean}
*/
isIOS: function() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
},
/**
* @return {Boolean}
*/
isAndroid: function() {
return /Android/i.test(navigator.userAgent);
},
/**
* @return {Boolean}
*/
isIPhone: function() {
return /iPhone/i.test(navigator.userAgent);
},
/**
* @return {Boolean}
*/
isIPad: function() {
return /iPad/i.test(navigator.userAgent);
},
/**
* @return {Boolean}
*/
isBlackBerry: function() {
return /BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent);
},
/**
* @return {Boolean}
*/
isOpera: function() {
return (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0);
},
/**
* @return {Boolean}
*/
isFirefox: function() {
return (typeof InstallTrigger !== 'undefined');
},
/**
* @return {Boolean}
*/
isSafari: function() {
return (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0);
},
/**
* @return {Boolean}
*/
isChrome: function() {
return (!!window.chrome && !(!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0));
},
/**
* @return {Boolean}
*/
isIE: function() {
return false || !!document.documentMode;
},
/**
* @return {Boolean}
*/
isIOS7above: function() {
if(/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
var ver = (navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[''])[0].replace(/_/g,'.');
return (parseInt(ver.split('.')[0]) >= 7);
}
return false;
}
};
})();
(function() {
'use strict';
// fastclick
window.addEventListener('load', function() {
FastClick.attach(document.body);
}, false);
// viewport.js
new Viewport().setup();
// modernize
Modernizr.testStyles('#modernizr { -webkit-overflow-scrolling:touch }', function(elem, rule) {
Modernizr.addTest(
'overflowtouch',
window.getComputedStyle && window.getComputedStyle(elem).getPropertyValue('-webkit-overflow-scrolling') == 'touch');
});
// confirm to use jqLite
if (window.jQuery && angular.element === window.jQuery) {
console.warn('Onsen UI require jqLite. Load jQuery after loading AngularJS to fix this error. jQuery may break Onsen UI behavior.');
}
})();
/*
Copyright 2013-2015 ASIAL CORPORATION
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(){
'use strict';
angular.module('onsen').run(['$templateCache', function($templateCache) {
var templates = window.document.querySelectorAll('script[type="text/ons-template"]');
for (var i = 0; i < templates.length; i++) {
var template = angular.element(templates[i]);
var id = template.attr('id');
if (typeof id === 'string') {
$templateCache.put(id, template.text());
}
}
}]);
})();
|
src/index.js | JAstbury/react-simple-game | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
src/svg-icons/av/music-video.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMusicVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
AvMusicVideo = pure(AvMusicVideo);
AvMusicVideo.displayName = 'AvMusicVideo';
AvMusicVideo.muiName = 'SvgIcon';
export default AvMusicVideo;
|
src/svg-icons/image/picture-as-pdf.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePictureAsPdf = (props) => (
<SvgIcon {...props}>
<path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5v1zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5v3zm4-3H19v1h1.5V11H19v2h-1.5V7h3v1.5zM9 9.5h1v-1H9v1zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm10 5.5h1v-3h-1v3z"/>
</SvgIcon>
);
ImagePictureAsPdf = pure(ImagePictureAsPdf);
ImagePictureAsPdf.displayName = 'ImagePictureAsPdf';
ImagePictureAsPdf.muiName = 'SvgIcon';
export default ImagePictureAsPdf;
|
app/PlayerAll.js | yanxyans/dominion | import React from 'react';
import Paper from 'material-ui/Paper';
import AppBar from 'material-ui/AppBar';
import { red700, blue700, green700, yellow700 } from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import IconEmpty from 'material-ui/svg-icons/toggle/star-border';
import IconHalf from 'material-ui/svg-icons/toggle/star-half';
import IconFull from 'material-ui/svg-icons/toggle/star';
import Player from './Player';
const colors = [red700, blue700, green700, yellow700];
export default class PlayerAll extends React.Component {
state = {
view: 1
}
_toggle = () => {
this.setState({view: (this.state.view + 1) % 3});
}
render() {
var players = this.props.players;
var len = players.length;
for (var i = 0; i < len; i++) {
if (players[i].slot === -1) {
players[i].slot = i;
}
}
var index = players.findIndex(function(player) {
return player.isPlayer;
});
if (index !== -1) {
players = this.props.players.slice(index).concat(
this.props.players.slice(0, index));
}
players.sort(function(playerA, playerB) {
return playerA.rank - playerB.rank;
});
var view = this.state.view;
return (
<Paper id='players' zDepth={2}>
<AppBar title='players'
showMenuIconButton={false}
iconElementRight={
(view === 0 &&
<IconButton tooltip='min'><IconEmpty/></IconButton>) ||
(view === 1 &&
<IconButton tooltip='default'><IconHalf/></IconButton>) ||
(view === 2 &&
<IconButton tooltip='full'><IconFull/></IconButton>)}
onRightIconButtonTouchTap={this._toggle}
style={{zIndex:998}}/>
<div className='content'>
{players.map(function(player, index) {
return <Player key={index}
player={player}
tooltip={player.isTurn && this.tooltip}
color={colors[player.slot]}
hideContent={view === 0 && !player.isPlayer}
allCards={view === 2}
_recon={this._recon.bind(null, player.slot)}
_complete={this._complete}
_tap={this._tap}/>;
}, this.props)}
</div>
</Paper>
);
}
} |
src/layouts/LoginLayout/LoginLayout.js | zhangjianguo1500/f01 | import React from 'react'
import '../CoreLayout/CoreLayout.scss'
import '../../styles/core.scss'
export const LoginLayout = ({ children }) => (
<div className='container text-center'>
<div className='core-layout__viewport'>
{children}
</div>
</div>
)
LoginLayout.propTypes = {
children : React.PropTypes.element.isRequired
}
export default LoginLayout
|
files/rxjs/2.4.1/rx.lite.compat.js | Asaf-S/jsdelivr | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
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.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 NotSupportedError(); }
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); }
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();
if (!item.isCancelled()) {
!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; };
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 NotSupportedError();
}
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, 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.schedule(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', 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 (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) {
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, 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) {
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(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);
/*try {
var result = this.selector(x, this.i++, 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(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(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 = new Array(len - 1);
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 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) {
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, {
/**
* 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));
|
docs/app/Examples/collections/Form/index.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import Content from './Content'
import Types from './Types'
import Variations from './Variations'
import Shorthand from './Shorthand'
import FieldVariations from './FieldVariations'
import GroupVariations from './GroupVariations'
import States from './States'
const FormExamples = () => (
<div>
<Types />
<Shorthand />
<Content />
<States />
<Variations />
<FieldVariations />
<GroupVariations />
</div>
)
export default FormExamples
|
examples/huge-apps/routes/Calendar/components/Calendar.js | zipongo/react-router | import React from 'react'
class Calendar extends React.Component {
render() {
const events = [
{ id: 0, title: 'essay due' }
]
return (
<div>
<h2>Calendar</h2>
<ul>
{events.map(event => (
<li key={event.id}>{event.title}</li>
))}
</ul>
</div>
)
}
}
module.exports = Calendar
|
ajax/libs/highcharts/3.0.7/highcharts.src.js | FaiblUG/cdnjs | // ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license Highcharts JS v3.0.7 (2013-10-24)
*
* (c) 2009-2013 Torstein Hønsi
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
(function () {
// encapsulated variables
var UNDEFINED,
doc = document,
win = window,
math = Math,
mathRound = math.round,
mathFloor = math.floor,
mathCeil = math.ceil,
mathMax = math.max,
mathMin = math.min,
mathAbs = math.abs,
mathCos = math.cos,
mathSin = math.sin,
mathPI = math.PI,
deg2rad = mathPI * 2 / 360,
// some variables
userAgent = navigator.userAgent,
isOpera = win.opera,
isIE = /msie/i.test(userAgent) && !isOpera,
docMode8 = doc.documentMode === 8,
isWebKit = /AppleWebKit/.test(userAgent),
isFirefox = /Firefox/.test(userAgent),
isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS = 'http://www.w3.org/2000/svg',
hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
Renderer,
hasTouch = doc.documentElement.ontouchstart !== UNDEFINED,
symbolSizes = {},
idCounter = 0,
garbageBin,
defaultOptions,
dateFormat, // function
globalAnimation,
pathAnim,
timeUnits,
noop = function () {},
charts = [],
PRODUCT = 'Highcharts',
VERSION = '3.0.7',
// some constants for frequently used strings
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
PREFIX = 'highcharts-',
VISIBLE = 'visible',
PX = 'px',
NONE = 'none',
M = 'M',
L = 'L',
/*
* Empirical lowest possible opacities for TRACKER_FILL
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable
//TRACKER_FILL = 'rgba(192,192,192,0.5)',
NORMAL_STATE = '',
HOVER_STATE = 'hover',
SELECT_STATE = 'select',
MILLISECOND = 'millisecond',
SECOND = 'second',
MINUTE = 'minute',
HOUR = 'hour',
DAY = 'day',
WEEK = 'week',
MONTH = 'month',
YEAR = 'year',
// constants for attributes
LINEAR_GRADIENT = 'linearGradient',
STOPS = 'stops',
STROKE_WIDTH = 'stroke-width',
// time methods, changed based on whether or not UTC is used
makeTime,
getMinutes,
getHours,
getDay,
getDate,
getMonth,
getFullYear,
setMinutes,
setHours,
setDate,
setMonth,
setFullYear,
// lookup over the types and the associated classes
seriesTypes = {};
// The Highcharts namespace
win.Highcharts = win.Highcharts ? error(16, true) : {};
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
function extend(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
}
/**
* Deep merge two or more objects and return a third object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
function merge() {
var i,
len = arguments.length,
ret = {},
doCopy = function (copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
&& typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// For each argument, extend the return
for (i = 0; i < len; i++) {
ret = doCopy(ret, arguments[i]);
}
return ret;
}
/**
* Take an array and turn into a hash with even number arguments as keys and odd numbers as
* values. Allows creating constants for commonly used style properties, attributes etc.
* Avoid it in performance critical situations like looping
*/
function hash() {
var i = 0,
args = arguments,
length = args.length,
obj = {};
for (; i < length; i++) {
obj[args[i++]] = args[i];
}
return obj;
}
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
function pInt(s, mag) {
return parseInt(s, mag || 10);
}
/**
* Check for string
* @param {Object} s
*/
function isString(s) {
return typeof s === 'string';
}
/**
* Check for object
* @param {Object} obj
*/
function isObject(obj) {
return typeof obj === 'object';
}
/**
* Check for array
* @param {Object} obj
*/
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* Check for number
* @param {Object} n
*/
function isNumber(n) {
return typeof n === 'number';
}
function log2lin(num) {
return math.log(num) / math.LN10;
}
function lin2log(num) {
return math.pow(10, num);
}
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
function erase(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
}
/**
* Returns true if the object is not null or undefined. Like MooTools' $.defined.
* @param {Object} obj
*/
function defined(obj) {
return obj !== UNDEFINED && obj !== null;
}
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
function attr(elem, prop, value) {
var key,
setAttribute = 'setAttribute',
ret;
// if the prop is a string
if (isString(prop)) {
// set the value
if (defined(value)) {
elem[setAttribute](prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (defined(prop) && isObject(prop)) {
for (key in prop) {
elem[setAttribute](key, prop[key]);
}
}
return ret;
}
/**
* Check if an element is an array, and if not, make it into an array. Like
* MooTools' $.splat.
*/
function splat(obj) {
return isArray(obj) ? obj : [obj];
}
/**
* Return the first value that is defined. Like MooTools' $.pick.
*/
function pick() {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (typeof arg !== 'undefined' && arg !== null) {
return arg;
}
}
}
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
function css(el, styles) {
if (isIE) {
if (styles && styles.opacity !== UNDEFINED) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
extend(el.style, styles);
}
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
function createElement(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) {
extend(el, attribs);
}
if (nopad) {
css(el, {padding: 0, border: NONE, margin: 0});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
}
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
function extendClass(parent, members) {
var object = function () {};
object.prototype = new parent();
extend(object.prototype, members);
return object;
}
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
function numberFormat(number, decimals, decPoint, thousandsSep) {
var lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
}
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
function pad(number, length) {
// Create an array of the remaining length +1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
function wrap(obj, method, func) {
var proceed = obj[method];
obj[method] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
}
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
dateFormat = function (format, timestamp, capitalize) {
if (!defined(timestamp) || isNaN(timestamp)) {
return 'Invalid date';
}
format = pick(format, '%Y-%m-%d %H:%M:%S');
var date = new Date(timestamp),
key, // used in for constuct below
// get the basic time values
hours = date[getHours](),
day = date[getDay](),
dayOfMonth = date[getDate](),
month = date[getMonth](),
fullYear = date[getFullYear](),
lang = defaultOptions.lang,
langWeekdays = lang.weekdays,
// List all format keys. Custom formats can be added from the outside.
replacements = extend({
// Day
'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': dayOfMonth, // Day of the month, 1 through 31
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, Highcharts.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
val = numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
} else {
val = dateFormat(format, val);
}
return val;
}
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
function format(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while ((index = str.indexOf(splitter)) !== -1) {
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
}
/**
* Get the magnitude of a number
*/
function getMagnitude(num) {
return math.pow(10, mathFloor(math.log(num) / math.LN10));
}
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
function normalizeTickInterval(interval, multiples, magnitude, options) {
var normalized, i;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (options && options.allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
interval = multiples[i];
if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
break;
}
}
// multiply back to the correct magnitude
interval *= magnitude;
return interval;
}
/**
* Get a normalized tick interval for dates. Returns a configuration object with
* unit range (interval), count and name. Used to prepare data for getTimeTicks.
* Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
* of segments in stock charts, the normalizing logic was extracted in order to
* prevent it for running over again for each segment having the same interval.
* #662, #697.
*/
function normalizeTimeTickInterval(tickInterval, unitsOption) {
var units = unitsOption || [[
MILLISECOND, // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
SECOND,
[1, 2, 5, 10, 15, 30]
], [
MINUTE,
[1, 2, 5, 10, 15, 30]
], [
HOUR,
[1, 2, 3, 4, 6, 8, 12]
], [
DAY,
[1, 2]
], [
WEEK,
[1, 2]
], [
MONTH,
[1, 2, 3, 4, 6]
], [
YEAR,
null
]],
unit = units[units.length - 1], // default unit is years
interval = timeUnits[unit[0]],
multiples = unit[1],
count,
i;
// loop through the units to find the one that best fits the tickInterval
for (i = 0; i < units.length; i++) {
unit = units[i];
interval = timeUnits[unit[0]];
multiples = unit[1];
if (units[i + 1]) {
// lessThan is in the middle between the highest multiple and the next unit.
var lessThan = (interval * multiples[multiples.length - 1] +
timeUnits[units[i + 1][0]]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) {
break;
}
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
multiples = [1, 2, 5];
}
// get the count
count = normalizeTickInterval(
tickInterval / interval,
multiples,
unit[0] === YEAR ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
);
return {
unitRange: interval,
count: count,
unitName: unit[0]
};
}
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array
* with the time positions. Used in datetime axes as well as for grouping
* data on a datetime axis.
*
* @param {Object} normalizedInterval The interval in axis values (ms) and the count
* @param {Number} min The minimum in axis values
* @param {Number} max The maximum in axis values
* @param {Number} startOfWeek
*/
function getTimeTicks(normalizedInterval, min, max, startOfWeek) {
var tickPositions = [],
i,
higherRanks = {},
useUTC = defaultOptions.global.useUTC,
minYear, // used in months and years as a basis for Date.UTC()
minDate = new Date(min),
interval = normalizedInterval.unitRange,
count = normalizedInterval.count;
if (defined(min)) { // #1300
if (interval >= timeUnits[SECOND]) { // second
minDate.setMilliseconds(0);
minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
count * mathFloor(minDate.getSeconds() / count));
}
if (interval >= timeUnits[MINUTE]) { // minute
minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
count * mathFloor(minDate[getMinutes]() / count));
}
if (interval >= timeUnits[HOUR]) { // hour
minDate[setHours](interval >= timeUnits[DAY] ? 0 :
count * mathFloor(minDate[getHours]() / count));
}
if (interval >= timeUnits[DAY]) { // day
minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
count * mathFloor(minDate[getDate]() / count));
}
if (interval >= timeUnits[MONTH]) { // month
minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
count * mathFloor(minDate[getMonth]() / count));
minYear = minDate[getFullYear]();
}
if (interval >= timeUnits[YEAR]) { // year
minYear -= minYear % count;
minDate[setFullYear](minYear);
}
// week is a special case that runs outside the hierarchy
if (interval === timeUnits[WEEK]) {
// get start of current week, independent of count
minDate[setDate](minDate[getDate]() - minDate[getDay]() +
pick(startOfWeek, 1));
}
// get tick positions
i = 1;
minYear = minDate[getFullYear]();
var time = minDate.getTime(),
minMonth = minDate[getMonth](),
minDateDate = minDate[getDate](),
timezoneOffset = useUTC ?
0 :
(24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
// iterate and add tick positions at appropriate values
while (time < max) {
tickPositions.push(time);
// if the interval is years, use Date.UTC to increase years
if (interval === timeUnits[YEAR]) {
time = makeTime(minYear + i * count, 0);
// if the interval is months, use Date.UTC to increase months
} else if (interval === timeUnits[MONTH]) {
time = makeTime(minYear, minMonth + i * count);
// if we're using global time, the interval is not fixed as it jumps
// one hour at the DST crossover
} else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
time = makeTime(minYear, minMonth, minDateDate +
i * count * (interval === timeUnits[DAY] ? 1 : 7));
// else, the interval is fixed and we use simple addition
} else {
time += interval * count;
}
i++;
}
// push the last time
tickPositions.push(time);
// mark new days if the time is dividible by day (#1649, #1760)
each(grep(tickPositions, function (time) {
return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset;
}), function (time) {
higherRanks[time] = DAY;
});
}
// record information on the chosen unit - for dynamic label formatter
tickPositions.info = extend(normalizedInterval, {
higherRanks: higherRanks,
totalRange: interval * count
});
return tickPositions;
}
/**
* Helper class that contains variuos counters that are local to the chart.
*/
function ChartCounters() {
this.color = 0;
this.symbol = 0;
}
ChartCounters.prototype = {
/**
* Wraps the color counter if it reaches the specified length.
*/
wrapColor: function (length) {
if (this.color >= length) {
this.color = 0;
}
},
/**
* Wraps the symbol counter if it reaches the specified length.
*/
wrapSymbol: function (length) {
if (this.symbol >= length) {
this.symbol = 0;
}
}
};
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
function stableSort(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].ss_i = i; // stable sort index
}
arr.sort(function (a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].ss_i; // stable sort index
}
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMin(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMax(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
function destroyObjectProperties(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
}
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = createElement(DIV);
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
}
/**
* Provide error messages for debugging, with links to online explanation
*/
function error(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw msg;
} else if (win.console) {
console.log(msg);
}
}
/**
* Fix JS round off float errors
* @param {Number} num
*/
function correctFloat(num) {
return parseFloat(
num.toPrecision(14)
);
}
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
function setAnimation(animation, chart) {
globalAnimation = pick(animation, chart.animation);
}
/**
* The time unit lookup
*/
/*jslint white: true*/
timeUnits = hash(
MILLISECOND, 1,
SECOND, 1000,
MINUTE, 60000,
HOUR, 3600000,
DAY, 24 * 3600000,
WEEK, 7 * 24 * 3600000,
MONTH, 31 * 24 * 3600000,
YEAR, 31556952000
);
/*jslint white: false*/
/**
* Path interpolation algorithm used across adapters
*/
pathAnim = {
/**
* Prepare start and end values so that the path can be animated one to one
*/
init: function (elem, fromD, toD) {
fromD = fromD || '';
var shift = elem.shift,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
endLength,
slice,
i,
start = fromD.split(' '),
end = [].concat(toD), // copy
startBaseLine,
endBaseLine,
sixify = function (arr) { // in splines make move points have six parameters like bezier curves
i = arr.length;
while (i--) {
if (arr[i] === M) {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
};
if (bezier) {
sixify(start);
sixify(end);
}
// pull out the base lines before padding
if (elem.isArea) {
startBaseLine = start.splice(start.length - 6, 6);
endBaseLine = end.splice(end.length - 6, 6);
}
// if shifting points, prepend a dummy point to the end path
if (shift <= end.length / numParams && start.length === end.length) {
while (shift--) {
end = [].concat(end).splice(0, numParams).concat(end);
}
}
elem.shift = 0; // reset for following animations
// copy and append last point until the length matches the end length
if (start.length) {
endLength = end.length;
while (start.length < endLength) {
//bezier && sixify(start);
slice = [].concat(start).splice(start.length - numParams, numParams);
if (bezier) { // disable first control point
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
start = start.concat(slice);
}
}
if (startBaseLine) { // append the base lines for areas
start = start.concat(startBaseLine);
end = end.concat(endBaseLine);
}
return [start, end];
},
/**
* Interpolate each value of the path and return the array
*/
step: function (start, end, pos, complete) {
var ret = [],
i = start.length,
startVal;
if (pos === 1) { // land on the final path without adjustment points appended in the ends
ret = complete;
} else if (i === end.length && pos < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
pos * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
return ret;
}
};
(function ($) {
/**
* The default HighchartsAdapter for jQuery
*/
win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
/**
* Initialize the adapter by applying some extensions to jQuery
*/
init: function (pathAnim) {
// extend the animate function to allow SVG animations
var Fx = $.fx,
Step = Fx.step,
dSetter,
Tween = $.Tween,
propHooks = Tween && Tween.propHooks,
opacityHook = $.cssHooks.opacity;
/*jslint unparam: true*//* allow unused param x in this function */
$.extend($.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
});
/*jslint unparam: false*/
// extend some methods to check for elem.attr, which means it is a Highcharts SVG object
$.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
var obj = Step,
base,
elem;
// Handle different parent objects
if (fn === 'cur') {
obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
} else if (fn === '_default' && Tween) { // jQuery 1.8 model
obj = propHooks[fn];
fn = 'set';
}
// Overwrite the method
base = obj[fn];
if (base) { // step.width and step.height don't exist in jQuery < 1.7
// create the extended function replacement
obj[fn] = function (fx) {
// Fx.prototype.cur does not use fx argument
fx = i ? fx : this;
// Don't run animations on textual properties like align (#1821)
if (fx.prop === 'align') {
return;
}
// shortcut
elem = fx.elem;
// Fx.prototype.cur returns the current value. The other ones are setters
// and returning a value has no effect.
return elem.attr ? // is SVG element wrapper
elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
base.apply(this, arguments); // use jQuery's built-in method
};
}
});
// Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
wrap(opacityHook, 'get', function (proceed, elem, computed) {
return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
});
// Define the setter function for d (path definitions)
dSetter = function (fx) {
var elem = fx.elem,
ends;
// Normally start and end should be set in state == 0, but sometimes,
// for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
// in these cases
if (!fx.started) {
ends = pathAnim.init(elem, elem.d, elem.toD);
fx.start = ends[0];
fx.end = ends[1];
fx.started = true;
}
// interpolate each value of the path
elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
};
// jQuery 1.8 style
if (Tween) {
propHooks.d = {
set: dSetter
};
// pre 1.8
} else {
// animate paths
Step.d = dSetter;
}
/**
* Utility for iterating over an array. Parameters are reversed compared to jQuery.
* @param {Array} arr
* @param {Function} fn
*/
this.each = Array.prototype.forEach ?
function (arr, fn) { // modern browsers
return Array.prototype.forEach.call(arr, fn);
} :
function (arr, fn) { // legacy
var i = 0,
len = arr.length;
for (; i < len; i++) {
if (fn.call(arr[i], arr[i], i, arr) === false) {
return i;
}
}
};
/**
* Register Highcharts as a plugin in the respective framework
*/
$.fn.highcharts = function () {
var constr = 'Chart', // default constructor
args = arguments,
options,
ret,
chart;
if (isString(args[0])) {
constr = args[0];
args = Array.prototype.slice.call(args, 1);
}
options = args[0];
// Create the chart
if (options !== UNDEFINED) {
/*jslint unused:false*/
options.chart = options.chart || {};
options.chart.renderTo = this[0];
chart = new Highcharts[constr](options, args[1]);
ret = this;
/*jslint unused:true*/
}
// When called without parameters or with the return argument, get a predefined chart
if (options === UNDEFINED) {
ret = charts[attr(this[0], 'data-highcharts-chart')];
}
return ret;
};
},
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
getScript: $.getScript,
/**
* Return the index of an item in an array, or -1 if not found
*/
inArray: $.inArray,
/**
* A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
* @param {Object} elem The HTML element
* @param {String} method Which method to run on the wrapped element
*/
adapterRun: function (elem, method) {
return $(elem)[method]();
},
/**
* Filter an array
*/
grep: $.grep,
/**
* Map an array
* @param {Array} arr
* @param {Function} fn
*/
map: function (arr, fn) {
//return jQuery.map(arr, fn);
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
},
/**
* Get the position of an element relative to the top left of the page
*/
offset: function (el) {
return $(el).offset();
},
/**
* Add an event listener
* @param {Object} el A HTML element or custom object
* @param {String} event The event type
* @param {Function} fn The event handler
*/
addEvent: function (el, event, fn) {
$(el).bind(event, fn);
},
/**
* Remove event added with addEvent
* @param {Object} el The object
* @param {String} eventType The event type. Leave blank to remove all events.
* @param {Function} handler The function to remove
*/
removeEvent: function (el, eventType, handler) {
// workaround for jQuery issue with unbinding custom events:
// http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
if (doc[func] && el && !el[func]) {
el[func] = function () {};
}
$(el).unbind(eventType, handler);
},
/**
* Fire an event on a custom object
* @param {Object} el
* @param {String} type
* @param {Object} eventArguments
* @param {Function} defaultFunction
*/
fireEvent: function (el, type, eventArguments, defaultFunction) {
var event = $.Event(type),
detachedType = 'detached' + type,
defaultPrevented;
// Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
// never uses these properties, Chrome includes them in the default click event and
// raises the warning when they are copied over in the extend statement below.
//
// To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
// testing if they are there (warning in chrome) the only option is to test if running IE.
if (!isIE && eventArguments) {
delete eventArguments.layerX;
delete eventArguments.layerY;
}
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// Wrap preventDefault and stopPropagation in try/catch blocks in
// order to prevent JS errors when cancelling events on non-DOM
// objects. #615.
/*jslint unparam: true*/
$.each(['preventDefault', 'stopPropagation'], function (i, fn) {
var base = event[fn];
event[fn] = function () {
try {
base.call(event);
} catch (e) {
if (fn === 'preventDefault') {
defaultPrevented = true;
}
}
};
});
/*jslint unparam: false*/
// trigger it
$(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
defaultFunction(event);
}
},
/**
* Extension method needed for MooTools
*/
washMouseEvent: function (e) {
var ret = e.originalEvent || e;
// computed by jQuery, needed by IE8
if (ret.pageX === UNDEFINED) { // #1236
ret.pageX = e.pageX;
ret.pageY = e.pageY;
}
return ret;
},
/**
* Animate a HTML element or SVG element wrapper
* @param {Object} el
* @param {Object} params
* @param {Object} options jQuery-like animation options: duration, easing, callback
*/
animate: function (el, params, options) {
var $el = $(el);
if (!el.style) {
el.style = {}; // #1881
}
if (params.d) {
el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
params.d = 1; // because in jQuery, animating to an array has a different meaning
}
$el.stop();
if (params.opacity !== UNDEFINED && el.attr) {
params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
}
$el.animate(params, options);
},
/**
* Stop running animation
*/
stop: function (el) {
$(el).stop();
}
});
}(win.jQuery));
// check for a custom HighchartsAdapter defined prior to this file
var globalAdapter = win.HighchartsAdapter,
adapter = globalAdapter || {};
// Initialize the adapter
if (globalAdapter) {
globalAdapter.init.call(globalAdapter, pathAnim);
}
// Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
// and all the utility functions will be null. In that case they are populated by the
// default adapters below.
var adapterRun = adapter.adapterRun,
getScript = adapter.getScript,
inArray = adapter.inArray,
each = adapter.each,
grep = adapter.grep,
offset = adapter.offset,
map = adapter.map,
addEvent = adapter.addEvent,
removeEvent = adapter.removeEvent,
fireEvent = adapter.fireEvent,
washMouseEvent = adapter.washMouseEvent,
animate = adapter.animate,
stop = adapter.stop;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
var
defaultLabelOptions = {
enabled: true,
// rotation: 0,
// align: 'center',
x: 0,
y: 15,
/*formatter: function () {
return this.value;
},*/
style: {
color: '#666',
cursor: 'default',
fontSize: '11px',
lineHeight: '14px'
}
};
defaultOptions = {
colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970',
'#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ','
},
global: {
useUTC: true,
canvasToolsURL: 'http://code.highcharts.com/3.0.7/modules/canvas-tools.js',
VMLRadialGradientURL: 'http://code.highcharts.com/3.0.7/gfx/vml-radial-gradient.png'
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderColor: '#4572A7',
//borderWidth: 0,
borderRadius: 5,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
//shadow: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
style: {
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
fontSize: '12px'
},
backgroundColor: '#FFFFFF',
//plotBackgroundColor: null,
plotBorderColor: '#C0C0C0',
//plotBorderWidth: 0,
//plotShadow: false,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#274b6d',//#3E576F',
fontSize: '16px'
}
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#4d759e'
}
},
plotOptions: {
line: { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//connectNulls: false,
//cursor: 'default',
//clip: true,
//dashStyle: null,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
//linecap: 'round',
lineWidth: 2,
//shadow: false,
// stacking: null,
marker: {
enabled: true,
//symbol: null,
lineWidth: 0,
radius: 4,
lineColor: '#FFFFFF',
//fillColor: null,
states: { // states for a single point
hover: {
enabled: true
//radius: base + 2
},
select: {
fillColor: '#FFFFFF',
lineColor: '#000000',
lineWidth: 2
}
}
},
point: {
events: {}
},
dataLabels: merge(defaultLabelOptions, {
align: 'center',
enabled: false,
formatter: function () {
return this.y === null ? '' : numberFormat(this.y, -1);
},
verticalAlign: 'bottom', // above singular point
y: 0
// backgroundColor: undefined,
// borderColor: undefined,
// borderRadius: undefined,
// borderWidth: undefined,
// padding: 3,
// shadow: false
}),
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
states: { // states for the entire series
hover: {
//enabled: false,
//lineWidth: base + 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
}
},
select: {
marker: {}
}
},
stickyTracking: true
//tooltip: {
//pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
// turboThreshold: 1000
// zIndex: null
}
},
labels: {
//items: [],
style: {
//font: defaultFont,
position: ABSOLUTE,
color: '#3E576F'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function () {
return this.name;
},
borderWidth: 1,
borderColor: '#909090',
borderRadius: 5,
navigation: {
// animation: true,
activeColor: '#274b6d',
// arrowSize: 12
inactiveColor: '#CCC'
// style: {} // text styles
},
// margin: 10,
// reversed: false,
shadow: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemStyle: {
cursor: 'pointer',
color: '#274b6d',
fontSize: '12px'
},
itemHoverStyle: {
//cursor: 'pointer', removed as of #601
color: '#000'
},
itemHiddenStyle: {
color: '#CCC'
},
itemCheckboxStyle: {
position: ABSOLUTE,
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null,
style: {
fontWeight: 'bold'
}
}
},
loading: {
// hideDuration: 100,
labelStyle: {
fontWeight: 'bold',
position: RELATIVE,
top: '1em'
},
// showDuration: 0,
style: {
position: ABSOLUTE,
backgroundColor: 'white',
opacity: 0.5,
textAlign: 'center'
}
},
tooltip: {
enabled: true,
animation: hasSVG,
//crosshairs: null,
backgroundColor: 'rgba(255, 255, 255, .85)',
borderWidth: 1,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
//formatter: defaultFormatter,
headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
shadow: true,
//shared: false,
snap: isTouchDevice ? 25 : 10,
style: {
color: '#333333',
cursor: 'default',
fontSize: '12px',
padding: '8px',
whiteSpace: 'nowrap'
}
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
text: 'Highcharts.com',
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
style: {
cursor: 'pointer',
color: '#909090',
fontSize: '9px'
}
}
};
// Series defaults
var defaultPlotOptions = defaultOptions.plotOptions,
defaultSeriesOptions = defaultPlotOptions.line;
// set the default time methods
setTimeMethods();
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var useUTC = defaultOptions.global.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
return new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
};
getMinutes = GET + 'Minutes';
getHours = GET + 'Hours';
getDay = GET + 'Day';
getDate = GET + 'Date';
getMonth = GET + 'Month';
getFullYear = GET + 'FullYear';
setMinutes = SET + 'Minutes';
setHours = SET + 'Hours';
setDate = SET + 'Date';
setMonth = SET + 'Month';
setFullYear = SET + 'FullYear';
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
function setOptions(options) {
// Pull out axis options and apply them to the respective default axis options
/*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis);
defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis);
options.xAxis = options.yAxis = UNDEFINED;*/
// Merge in the default options
defaultOptions = merge(defaultOptions, options);
// Apply UTC
setTimeMethods();
return defaultOptions;
}
/**
* Get the updated default options. Merely exposing defaultOptions for outside modules
* isn't enough because the setOptions method creates a new object.
*/
function getOptions() {
return defaultOptions;
}
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
var Color = function (input) {
// declare variables
var rgba = [], result, stops;
/**
* Parse the input color to rgba array
* @param {String} input
*/
function init(input) {
// Gradients
if (input && input.stops) {
stops = map(input.stops, function (stop) {
return Color(stop[1]);
});
// Solid colors
} else {
// rgba
result = rgbaRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
} else {
// hex
result = hexRegEx.exec(input);
if (result) {
rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
} else {
// rgb
result = rgbRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}
}
}
}
/**
* Return the color a specified format
* @param {String} format
*/
function get(format) {
var ret;
if (stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(stops, function (stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && !isNaN(rgba[0])) {
if (format === 'rgb') {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
}
/**
* Brighten the color
* @param {Number} alpha
*/
function brighten(alpha) {
if (stops) {
each(stops, function (stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
var i;
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
}
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
function setOpacity(alpha) {
rgba[3] = alpha;
return this;
}
// initialize: parse the input
init(input);
// public methods
return {
get: get,
brighten: brighten,
rgba: rgba,
setOpacity: setOpacity
};
};
/**
* A wrapper object for SVG elements
*/
function SVGElement() {}
SVGElement.prototype = {
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(SVG_NS, nodeName);
wrapper.renderer = renderer;
/**
* A collection of attribute setters. These methods, if defined, are called right before a certain
* attribute is set on an element wrapper. Returning false prevents the default attribute
* setter to run. Returning a value causes the default setter to set that value. Used in
* Renderer.label.
*/
wrapper.attrSetters = {};
},
/**
* Default base for animation
*/
opacity: 1,
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options The same options as in jQuery animation
* @param {Function} complete Function to perform at the end of animation
*/
animate: function (params, options, complete) {
var animOptions = pick(options, globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
animOptions = merge(animOptions);
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params);
if (complete) {
complete();
}
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function (hash, val) {
var wrapper = this,
key,
value,
result,
i,
child,
element = wrapper.element,
nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text"
renderer = wrapper.renderer,
skipAttr,
titleNode,
attrSetters = wrapper.attrSetters,
shadows = wrapper.shadows,
hasSetSymbolSize,
doTransform,
ret = wrapper;
// single key-value pair
if (isString(hash) && defined(val)) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (isString(hash)) {
key = hash;
if (nodeName === 'circle') {
key = { x: 'cx', y: 'cy' }[key] || key;
} else if (key === 'strokeWidth') {
key = 'stroke-width';
}
ret = attr(element, key) || wrapper[key] || 0;
if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step
ret = parseFloat(ret);
}
// setter
} else {
for (key in hash) {
skipAttr = false; // reset
value = hash[key];
// check for a specific attribute setter
result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
if (result !== false) {
if (result !== UNDEFINED) {
value = result; // the attribute setter has returned a new value to set
}
// paths
if (key === 'd') {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
//wrapper.d = value; // shortcut for animations
// update child tspans x values
} else if (key === 'x' && nodeName === 'text') {
for (i = 0; i < element.childNodes.length; i++) {
child = element.childNodes[i];
// if the x values are equal, the tspan represents a linebreak
if (attr(child, 'x') === attr(element, 'x')) {
//child.setAttribute('x', value);
attr(child, 'x', value);
}
}
} else if (wrapper.rotation && (key === 'x' || key === 'y')) {
doTransform = true;
// apply gradients
} else if (key === 'fill') {
value = renderer.color(value, element, key);
// circle x and y
} else if (nodeName === 'circle' && (key === 'x' || key === 'y')) {
key = { x: 'cx', y: 'cy' }[key] || key;
// rectangle border radius
} else if (nodeName === 'rect' && key === 'r') {
attr(element, {
rx: value,
ry: value
});
skipAttr = true;
// translation and text rotation
} else if (key === 'translateX' || key === 'translateY' || key === 'rotation' ||
key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') {
doTransform = true;
skipAttr = true;
// apply opacity as subnode (required by legacy WebKit and Batik)
} else if (key === 'stroke') {
value = renderer.color(value, element, key);
// emulate VML's dashstyle implementation
} else if (key === 'dashstyle') {
key = 'stroke-dasharray';
value = value && value.toLowerCase();
if (value === 'solid') {
value = NONE;
} else if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']);
}
value = value.join(',');
}
// IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2
// is unable to cast them. Test again with final IE9.
} else if (key === 'width') {
value = pInt(value);
// Text alignment
} else if (key === 'align') {
key = 'text-anchor';
value = { left: 'start', center: 'middle', right: 'end' }[value];
// Title requires a subnode, #431
} else if (key === 'title') {
titleNode = element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(SVG_NS, 'title');
element.appendChild(titleNode);
}
titleNode.textContent = value;
}
// jQuery animate changes case
if (key === 'strokeWidth') {
key = 'stroke-width';
}
// In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
// width is 0. #1369
if (key === 'stroke-width' || key === 'stroke') {
wrapper[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger than 0
if (wrapper.stroke && wrapper['stroke-width']) {
attr(element, 'stroke', wrapper.stroke);
attr(element, 'stroke-width', wrapper['stroke-width']);
wrapper.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) {
element.removeAttribute('stroke');
wrapper.hasStroke = false;
}
skipAttr = true;
}
// symbols
if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
wrapper.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
// let the shadow follow the main element
if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
i = shadows.length;
while (i--) {
attr(
shadows[i],
key,
key === 'height' ?
mathMax(value - (shadows[i].cutHeight || 0), 0) :
value
);
}
}
// validate heights
if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) {
value = 0;
}
// Record for animation and quick access without polling the DOM
wrapper[key] = value;
if (key === 'text') {
// Delete bBox memo when the text changes
if (value !== wrapper.textStr) {
delete wrapper.bBox;
}
wrapper.textStr = value;
if (wrapper.added) {
renderer.buildText(wrapper);
}
} else if (!skipAttr) {
attr(element, key, value);
}
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (doTransform) {
wrapper.updateTransform();
}
}
return ret;
},
/**
* Add a class name to an element
*/
addClass: function (className) {
var element = this.element,
currentClassName = attr(element, 'class') || '';
if (currentClassName.indexOf(className) === -1) {
attr(element, 'class', currentClassName + ' ' + className);
}
return this;
},
/* hasClass and removeClass are not (yet) needed
hasClass: function (className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function (className) {
attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
return this;
},
*/
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function (hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function (clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function (strokeWidth, x, y, width, height) {
var wrapper = this,
key,
attribs = {},
values = {},
normalizer;
strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
values.x = mathFloor(x || wrapper.x || 0) + normalizer;
values.y = mathFloor(y || wrapper.y || 0) + normalizer;
values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer);
values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer);
values.strokeWidth = strokeWidth;
for (key in values) {
if (wrapper[key] !== values[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = values[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function (styles) {
/*jslint unparam: true*//* allow unused param a in the regexp function below */
var elemWrapper = this,
elem = elemWrapper.element,
textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width),
n,
serializedCss = '',
hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
/*jslint unparam: false*/
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Merge the new styles with the old ones
styles = extend(
elemWrapper.styles,
styles
);
// store object
elemWrapper.styles = styles;
if (textWidth) {
delete styles.width;
}
// serialize and set style attribute
if (isIE && !hasSVG) {
css(elemWrapper.element, styles);
} else {
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// re-build text
if (textWidth && elemWrapper.added) {
elemWrapper.renderer.buildText(elemWrapper);
}
return elemWrapper;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function (coordinates) {
this.element.radialReference = coordinates;
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function () {
var wrapper = this;
wrapper.inverted = true;
wrapper.updateTransform();
return wrapper;
},
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function (styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function () {
var wrapper = this,
element = wrapper.element,
bBox = wrapper.bBox;
// faking getBBox in exported SVG in legacy IE
if (!bBox) {
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = ABSOLUTE;
}
bBox = wrapper.bBox = {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
return bBox;
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function () {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
nonLeft = align && align !== 'left',
shadows = wrapper.shadows;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
if (shadows) { // used in labels/tooltip
each(shadows, function (shadow) {
css(shadow, {
marginLeft: translateX + 1,
marginTop: translateY + 1
});
});
}
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function (child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var width, height,
rotation = wrapper.rotation,
baseline,
radians = 0,
costheta = 1,
sintheta = 0,
quad,
textWidth = pInt(wrapper.textWidth),
xCorr = wrapper.xCorr || 0,
yCorr = wrapper.yCorr || 0,
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
if (defined(rotation)) {
radians = rotation * deg2rad; // deg to rad
costheta = mathCos(radians);
sintheta = mathSin(radians);
wrapper.setSpanRotation(rotation, sintheta, costheta);
}
width = pick(wrapper.elemWidth, elem.offsetWidth);
height = pick(wrapper.elemHeight, elem.offsetHeight);
// update textWidth
if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + PX,
display: 'block',
whiteSpace: 'normal'
});
width = textWidth;
}
// correct x and y
baseline = renderer.fontMetrics(elem.style.fontSize).b;
xCorr = costheta < 0 && -width;
yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(elem, {
textAlign: align
});
}
// record correction
wrapper.xCorr = xCorr;
wrapper.yCorr = yCorr;
}
// apply position with correction
css(elem, {
left: (x + xCorr) + PX,
top: (y + yCorr) + PX
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
height = elem.offsetHeight; // assigned to height for JSLint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function (rotation) {
var rotationStyle = {},
cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
css(this.element, rotationStyle);
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')');
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
attr(wrapper.element, 'transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right' || align === 'center') {
x += (box.width - (alignOptions.width || 0)) /
{ right: 1, center: 2 }[align];
}
attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
// Vertical align
if (vAlign === 'bottom' || vAlign === 'middle') {
y += (box.height - (alignOptions.height || 0)) /
({ bottom: 1, middle: 2 }[vAlign] || 1);
}
attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function () {
var wrapper = this,
bBox = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation = wrapper.rotation,
element = wrapper.element,
styles = wrapper.styles,
rad = rotation * deg2rad;
if (!bBox) {
// SVG elements
if (element.namespaceURI === SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Canvas renderer and legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669)
if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
}
}
wrapper.bBox = bBox;
}
return bBox;
},
/**
* Show the element
*/
show: function () {
return this.attr({ visibility: VISIBLE });
},
/**
* Hide the element
*/
hide: function () {
return this.attr({ visibility: HIDDEN });
},
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
elemWrapper.hide();
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function (parent) {
var renderer = this.renderer,
parentWrapper = parent || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes = parentNode.childNodes,
element = this.element,
zIndex = attr(element, 'zIndex'),
otherElement,
otherZIndex,
i,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// mark the container as having z indexed children
if (zIndex) {
parentWrapper.handleZ = true;
zIndex = pInt(zIndex);
}
// insert according to this and other elements' zIndex
if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
for (i = 0; i < childNodes.length; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// insert before the first element with a higher zIndex
pInt(otherZIndex) > zIndex ||
// if no zIndex given, insert before the first element with a zIndex
(!defined(zIndex) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
break;
}
}
}
// default: append at the end
if (!inserted) {
parentNode.appendChild(element);
}
// mark as added
this.added = true;
// fire an event for internal hooks
fireEvent(this, 'add');
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
shadows = wrapper.shadows,
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// destroy shadows
if (shadows) {
each(shadows, function (shadow) {
wrapper.safeRemoveChild(shadow);
});
}
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393).
while (parentToClean && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
/**
* Add a shadow to the element. Must be done after the element is added to the DOM
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'isShadow': 'true',
'stroke': shadowOptions.color || 'black',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': NONE
});
if (cutOff) {
attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
}
};
/**
* The default SVG renderer
*/
var SVGRenderer = function () {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function (container, width, height, forExport) {
var renderer = this,
loc = location,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
version: '1.1'
});
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
loc.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
renderer.defs = this.createElement('defs').add();
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (mathCeil(rect.left) - rect.left) + PX,
top: (mathCeil(rect.top) - rect.top) + PX
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function () {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for use in canvas renderer
*/
draw: function () {},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
lines = pick(wrapper.textStr, '').toString()
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g),
childNodes = textNode.childNodes,
styleRegex = /style="([^"]+)"/,
hrefRegex = /href="(http[^"]+)"/,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
i = childNodes.length;
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
if (width && !wrapper.added) {
this.box.appendChild(textNode); // attach it to the DOM to read offset width
}
// remove empty line at end
if (lines[lines.length - 1] === '') {
lines.pop();
}
// build the lines
each(lines, function (line, lineNo) {
var spans, spanNo = 0;
line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function (span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(SVG_NS, 'tspan'),
spanStyle; // #390
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, { cursor: 'pointer' });
}
span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
.replace(/</g, '<')
.replace(/>/g, '>');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
attributes.x = parentX;
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!hasSVG && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
textLineHeight || renderer.fontMetrics(
/px$/.test(tspan.style.fontSize) ?
tspan.style.fontSize :
textStyles.fontSize
).h,
// Safari 6.0.2 - too optimized for its own good (#1539)
// TODO: revisit this with future versions of Safari
isWebKit && tspan.offsetHeight
);
}
// Append it
textNode.appendChild(tspan);
spanNo++;
// check width and apply soft breaks
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
tooLong,
actualWidth,
clipHeight = wrapper._clipHeight,
rest = [],
dy = pInt(textLineHeight || 16),
softLineNo = 1,
bBox;
while (words.length || rest.length) {
delete wrapper.bBox; // delete cache
bBox = wrapper.getBBox();
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!hasSVG && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
if (!tooLong || words.length === 1) { // new line needed
words = rest;
rest = [];
if (words.length) {
softLineNo++;
if (clipHeight && softLineNo * dy > clipHeight) {
words = ['...'];
wrapper.attr('title', wrapper.textStr);
} else {
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
}
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
}
}
}
});
});
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0,
stateOptions,
stateStyle,
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle,
STYLE = 'style',
verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
// Normal state - prepare the attributes
normalState = merge({
'stroke-width': 1,
stroke: '#CCCCCC',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FEFEFE'],
[1, '#F6F6F6']
]
},
r: 2,
padding: 5,
style: {
color: 'black'
}
}, normalState);
normalStyle = normalState[STYLE];
delete normalState[STYLE];
// Hover state
hoverState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FFF'],
[1, '#ACF']
]
}
}, hoverState);
hoverStyle = hoverState[STYLE];
delete hoverState[STYLE];
// Pressed state
pressedState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#9BD'],
[1, '#CDF']
]
}
}, pressedState);
pressedStyle = pressedState[STYLE];
delete pressedState[STYLE];
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#CCC'
}
}, disabledState);
disabledStyle = disabledState[STYLE];
delete disabledState[STYLE];
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.attr(hoverState)
.css(hoverStyle);
}
});
addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
stateOptions = [normalState, hoverState, pressedState][curState];
stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
label.attr(stateOptions)
.css(stateStyle);
}
});
label.setState = function (state) {
label.state = curState = state;
if (!state) {
label.attr(normalState)
.css(normalStyle);
} else if (state === 2) {
label.attr(pressedState)
.css(pressedStyle);
} else if (state === 3) {
label.attr(disabledState)
.css(disabledStyle);
}
};
return label
.on('click', function () {
if (curState !== 3) {
callback.call(label);
}
})
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function (points, width) {
// points format: [M, 0, 0, L, 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function (path) {
var attr = {
fill: NONE
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
return this.createElement('path').attr(attr);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function (x, y, r) {
var attr = isObject(x) ?
x :
{
x: x,
y: y,
r: r
};
return this.createElement('circle').attr(attr);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function (x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect').attr({
rx: r,
ry: r,
fill: NONE
});
return wrapper.attr(
isObject(x) ?
x :
// do not crispify when an object is passed in (as in column charts)
wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
width: width,
height: height
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function (name) {
var elem = this.createElement('g');
return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var attribs = {
preserveAspectRatio: NONE
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function (symbol, x, y, width, height, options) {
var obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = symbolFn && symbolFn(
mathRound(x),
mathRound(y),
width,
height,
options
),
imageElement,
imageRegex = /^url\((.*?)\)$/,
imageSrc,
imageSize,
centerImage;
if (path) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
// On image load, set the size and position
centerImage = function (img, size) {
if (img.element) { // it may be destroyed in the meantime (#1390)
img.attr({
width: size[0],
height: size[1]
});
if (!img.alignByTranslate) { // #185
img.translate(
mathRound((width - size[0]) / 2), // #1378
mathRound((height - size[1]) / 2)
);
}
}
};
imageSrc = symbol.match(imageRegex)[1];
imageSize = symbolSizes[imageSrc];
// Ireate the image synchronously, add attribs async
obj = this.image(imageSrc)
.attr({
x: x,
y: y
});
obj.isImg = true;
if (imageSize) {
centerImage(obj, imageSize);
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
//
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
imageElement = createElement('img', {
onload: function () {
centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
},
src: imageSrc
});
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function (x, y, w, h) {
var cpw = 0.166 * w;
return [
M, x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
longArc = options.end - start < mathPI ? 0 : 1;
return [
M,
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? M : L,
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = PREFIX + idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
return wrapper;
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object. Prior to Highstock, an array was used to define
* a linear gradient with pixel positions relative to the SVG. In newer versions
* we change the coordinates to apply relative to the shape, using coordinates
* 0-1 within the shape. To preserve backwards compatibility, linearGradient
* in this definition is an object of x1, y1, x2 and y2.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
gradName,
gradAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [];
// Apply linear or radial gradients
if (color && color.linearGradient) {
gradName = 'linearGradient';
} else if (color && color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
gradAttr = merge(gradAttr, {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2],
gradientUnits: 'userSpaceOnUse'
});
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].id;
} else {
// Set the id and create the element
gradAttr.id = id = PREFIX + idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function (stop) {
var stopObject;
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Return the reference to the gradient object
return 'url(' + renderer.url + '#' + id + ')';
// Webkit and Batik can't show rgba.
} else if (regexRgba.test(color)) {
colorObject = Color(color);
attr(elem, prop + '-opacity', colorObject.get('a'));
return colorObject.get('rgb');
} else {
// Remove the opacity attribute added above. Does not throw if the attribute is not there.
elem.removeAttribute(prop + '-opacity');
return color;
}
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
defaultChartStyle = defaultOptions.chart.style,
fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
wrapper;
if (useHTML && !renderer.forExport) {
return renderer.html(str, x, y);
}
x = mathRound(pick(x, 0));
y = mathRound(pick(y, 0));
wrapper = renderer.createElement('text')
.attr({
x: x,
y: y,
text: str
})
.css({
fontFamily: defaultChartStyle.fontFamily,
fontSize: defaultChartStyle.fontSize
});
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: ABSOLUTE
});
}
wrapper.x = x;
wrapper.y = y;
return wrapper;
},
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function (str, x, y) {
var defaultChartStyle = defaultOptions.chart.style,
wrapper = this.createElement('span'),
attrSetters = wrapper.attrSetters,
element = wrapper.element,
renderer = wrapper.renderer;
// Text setter
attrSetters.text = function (value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = value;
return false;
};
// Various setters which rely on update transform
attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
return false;
};
// Set the default attributes
wrapper.attr({
text: str,
x: mathRound(x),
y: mathRound(y)
})
.css({
position: ABSOLUTE,
whiteSpace: 'nowrap',
fontFamily: defaultChartStyle.fontFamily,
fontSize: defaultChartStyle.fontSize
});
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (renderer.isSVG) {
wrapper.add = function (svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function (parentGroup) {
var htmlGroupStyle;
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
className: attr(parentGroup.element, 'class')
}, {
position: ABSOLUTE,
left: (parentGroup.translateX || 0) + PX,
top: (parentGroup.translateY || 0) + PX
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup.attrSetters, {
translateX: function (value) {
htmlGroupStyle.left = value + PX;
},
translateY: function (value) {
htmlGroupStyle.top = value + PX;
},
visibility: function (value, key) {
htmlGroupStyle[key] = value;
}
});
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function (fontSize) {
fontSize = pInt(fontSize || 11);
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
baseline = mathRound(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className),
text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
//.add(wrapper),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
crispAdjust = 0,
deferredAttr = {},
baselineOffset,
attrSetters = wrapper.attrSetters,
needsBox;
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
function updateBoxSize() {
var boxX,
boxY,
style = text.element.style;
bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) &&
text.getBBox();
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
if (needsBox) {
// create the border box if it is not already present
if (!box) {
boxX = mathRound(-alignFactor * padding);
boxY = baseline ? -baselineOffset : 0;
wrapper.box = box = shape ?
renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
box.add(wrapper);
}
// apply the box attributes
if (!box.isImg) { // #1630
box.attr(merge({
width: wrapper.width,
height: wrapper.height
}, deferredAttr));
}
deferredAttr = null;
}
}
/**
* This function runs after setting text or padding, but only if padding is changed
*/
function updateTextPadding() {
var styles = wrapper.styles,
textAlign = styles && styles.textAlign,
x = paddingLeft + padding * (1 - alignFactor),
y;
// determin y based on the baseline
y = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
}
// update if anything changed
if (x !== text.x || y !== text.y) {
text.attr({
x: x,
y: y
});
}
// record current values
text.x = x;
text.y = y;
}
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
function boxAttr(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
}
function getSizeAfterAdd() {
text.add(wrapper);
wrapper.attr({
text: str, // alignment is available now
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
}
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
addEvent(wrapper, 'add', getSizeAfterAdd);
/*
* Add specific attribute setters.
*/
// only change local variables
attrSetters.width = function (value) {
width = value;
return false;
};
attrSetters.height = function (value) {
height = value;
return false;
};
attrSetters.padding = function (value) {
if (defined(value) && value !== padding) {
padding = value;
updateTextPadding();
}
return false;
};
attrSetters.paddingLeft = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
return false;
};
// change local variable and set attribue as well
attrSetters.align = function (value) {
alignFactor = { left: 0, center: 0.5, right: 1 }[value];
return false; // prevent setting text-anchor on the group
};
// apply these to the box and the text alike
attrSetters.text = function (value, key) {
text.attr(key, value);
updateBoxSize();
updateTextPadding();
return false;
};
// apply these to the box but not to the text
attrSetters[STROKE_WIDTH] = function (value, key) {
needsBox = true;
crispAdjust = value % 2 / 2;
boxAttr(key, value);
return false;
};
attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) {
if (key === 'fill') {
needsBox = true;
}
boxAttr(key, value);
return false;
};
attrSetters.anchorX = function (value, key) {
anchorX = value;
boxAttr(key, value + crispAdjust - wrapperX);
return false;
};
attrSetters.anchorY = function (value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
return false;
};
// rename attributes
attrSetters.x = function (value) {
wrapper.x = value; // for animation getter
value -= alignFactor * ((width || bBox.width) + padding);
wrapperX = mathRound(value);
wrapper.attr('translateX', wrapperX);
return false;
};
attrSetters.y = function (value) {
wrapperY = wrapper.y = mathRound(value);
wrapper.attr('translateY', wrapperY);
return false;
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function (styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
if (styles[prop] !== UNDEFINED) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Apply the shadow to the box
*/
shadow: function (b) {
if (box) {
box.shadow(b);
}
return wrapper;
},
/**
* Destroy and release memory.
*/
destroy: function () {
removeEvent(wrapper, 'add', getSizeAfterAdd);
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null;
}
});
}
}; // end SVGRenderer
// general renderer
Renderer = SVGRenderer;
/* ****************************************************************************
* *
* START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
* For applications and websites that don't need IE support, like platform *
* targeted mobile apps and web apps, this code can be removed. *
* *
*****************************************************************************/
/**
* @constructor
*/
var VMLRenderer, VMLElement;
if (!hasSVG && !useCanVG) {
/**
* The VML element wrapper.
*/
Highcharts.VMLElement = VMLElement = {
/**
* Initialize a new VML element wrapper. It builds the markup as a string
* to minimize DOM traffic.
* @param {Object} renderer
* @param {Object} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this,
markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', ABSOLUTE, ';'],
isDiv = nodeName === DIV;
// divs and shapes need size
if (nodeName === 'shape' || isDiv) {
style.push('left:0;top:0;width:1px;height:1px;');
}
style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
markup.join('')
: renderer.prepVML(markup);
wrapper.element = createElement(markup);
}
wrapper.renderer = renderer;
wrapper.attrSetters = {};
},
/**
* Add the node to the given parent
* @param {Object} parent
*/
add: function (parent) {
var wrapper = this,
renderer = wrapper.renderer,
element = wrapper.element,
box = renderer.box,
inverted = parent && parent.inverted,
// get the parent node
parentNode = parent ?
parent.element || parent :
box;
// if the parent group is inverted, apply inversion on all children
if (inverted) { // only on groups
renderer.invertChild(element, parentNode);
}
// append it
parentNode.appendChild(element);
// align text after adding to be able to read offset
wrapper.added = true;
if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
wrapper.updateTransform();
}
// fire an event for internal hooks
fireEvent(wrapper, 'add');
return wrapper;
},
/**
* VML always uses htmlUpdateTransform
*/
updateTransform: SVGElement.prototype.htmlUpdateTransform,
/**
* Set the rotation of a span with oldIE's filter
*/
setSpanRotation: function (rotation, sintheta, costheta) {
// Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
// but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
// has support for CSS3 transform. The getBBox method also needs to be updated
// to compensate for the rotation, like it currently does for SVG.
// Test case: http://highcharts.com/tests/?file=text-rotation
css(this.element, {
filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
', sizingMethod=\'auto expand\')'].join('') : NONE
});
},
/**
* Converts a subset of an SVG path definition to its VML counterpart. Takes an array
* as the parameter and returns a string.
*/
pathToVML: function (value) {
// convert paths
var i = value.length,
path = [],
clockwise;
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = mathRound(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too close,
// they are rounded to the same value above. In this case, substract 1 from the end X
// position. #760, #1371.
if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
clockwise = value[i] === 'wa' ? 1 : -1; // #1642
if (path[i + 5] === path[i + 7]) {
path[i + 7] -= clockwise;
}
// Start and end Y (#1410)
if (path[i + 6] === path[i + 8]) {
path[i + 8] -= clockwise;
}
}
}
}
// Loop up again to handle path shortcuts (#2132)
/*while (i++ < path.length) {
if (path[i] === 'H') { // horizontal line to
path[i] = 'L';
path.splice(i + 2, 0, path[i - 1]);
} else if (path[i] === 'V') { // vertical line to
path[i] = 'L';
path.splice(i + 1, 0, path[i - 2]);
}
}*/
return path.join(' ') || 'x';
},
/**
* Get or set attributes
*/
attr: function (hash, val) {
var wrapper = this,
key,
value,
i,
result,
element = wrapper.element || {},
elemStyle = element.style,
nodeName = element.nodeName,
renderer = wrapper.renderer,
symbolName = wrapper.symbolName,
hasSetSymbolSize,
shadows = wrapper.shadows,
skipAttr,
attrSetters = wrapper.attrSetters,
ret = wrapper;
// single key-value pair
if (isString(hash) && defined(val)) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter, val is undefined
if (isString(hash)) {
key = hash;
if (key === 'strokeWidth' || key === 'stroke-width') {
ret = wrapper.strokeweight;
} else {
ret = wrapper[key];
}
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
// check for a specific attribute setter
result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
if (result !== false && value !== null) { // #620
if (result !== UNDEFINED) {
value = result; // the attribute setter has returned a new value to set
}
// prepare paths
// symbols
if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) {
// if one of the symbol size affecting parameters are changed,
// check all the others only once for each call to an element's
// .attr() method
if (!hasSetSymbolSize) {
wrapper.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
} else if (key === 'd') {
value = value || [];
wrapper.d = value.join(' '); // used in getter for animation
element.path = value = wrapper.pathToVML(value);
// update shadows
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
}
}
skipAttr = true;
// handle visibility
} else if (key === 'visibility') {
// let the shadow follow the main element
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].style[key] = value;
}
}
// Instead of toggling the visibility CSS property, move the div out of the viewport.
// This works around #61 and #586
if (nodeName === 'DIV') {
value = value === HIDDEN ? '-999em' : 0;
// In order to redraw, IE7 needs the div to be visible when tucked away
// outside the viewport. So the visibility is actually opposite of
// the expected value. This applies to the tooltip only.
if (!docMode8) {
elemStyle[key] = value ? VISIBLE : HIDDEN;
}
key = 'top';
}
elemStyle[key] = value;
skipAttr = true;
// directly mapped to css
} else if (key === 'zIndex') {
if (value) {
elemStyle[key] = value;
}
skipAttr = true;
// x, y, width, height
} else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) {
wrapper[key] = value; // used in getter
if (key === 'x' || key === 'y') {
key = { x: 'left', y: 'top' }[key];
} else {
value = mathMax(0, value); // don't set width or height below zero (#311)
}
// clipping rectangle special
if (wrapper.updateClipping) {
wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
wrapper.updateClipping();
} else {
// normal
elemStyle[key] = value;
}
skipAttr = true;
// class name
} else if (key === 'class' && nodeName === 'DIV') {
// IE8 Standards mode has problems retrieving the className
element.className = value;
// stroke
} else if (key === 'stroke') {
value = renderer.color(value, element, key);
key = 'strokecolor';
// stroke width
} else if (key === 'stroke-width' || key === 'strokeWidth') {
element.stroked = value ? true : false;
key = 'strokeweight';
wrapper[key] = value; // used in getter, issue #113
if (isNumber(value)) {
value += PX;
}
// dashStyle
} else if (key === 'dashstyle') {
var strokeElem = element.getElementsByTagName('stroke')[0] ||
createElement(renderer.prepVML(['<stroke/>']), null, null, element);
strokeElem[key] = value || 'solid';
wrapper.dashstyle = value; /* because changing stroke-width will change the dash length
and cause an epileptic effect */
skipAttr = true;
// fill
} else if (key === 'fill') {
if (nodeName === 'SPAN') { // text color
elemStyle.color = value;
} else if (nodeName !== 'IMG') { // #1336
element.filled = value !== NONE ? true : false;
value = renderer.color(value, element, key, wrapper);
key = 'fillcolor';
}
// opacity: don't bother - animation is too slow and filters introduce artifacts
} else if (key === 'opacity') {
/*css(element, {
opacity: value
});*/
skipAttr = true;
// rotation on VML elements
} else if (nodeName === 'shape' && key === 'rotation') {
wrapper[key] = element.style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
element.style.top = mathRound(mathCos(value * deg2rad)) + PX;
// translation for animation
} else if (key === 'translateX' || key === 'translateY' || key === 'rotation') {
wrapper[key] = value;
wrapper.updateTransform();
skipAttr = true;
// text for rotated and non-rotated elements
} else if (key === 'text') {
this.bBox = null;
element.innerHTML = value;
skipAttr = true;
}
if (!skipAttr) {
if (docMode8) { // IE8 setAttribute bug
element[key] = value;
} else {
attr(element, key, value);
}
}
}
}
}
return ret;
},
/**
* Set the element's clipping to a predefined rectangle
*
* @param {String} id The id of the clip rectangle
*/
clip: function (clipRect) {
var wrapper = this,
clipMembers,
cssRet;
if (clipRect) {
clipMembers = clipRect.members;
erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
clipMembers.push(wrapper);
wrapper.destroyClip = function () {
erase(clipMembers, wrapper);
};
cssRet = clipRect.getCSS(wrapper);
} else {
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
}
return wrapper.css(cssRet);
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: SVGElement.prototype.htmlCss,
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
// discardElement will detach the node from its parent before attaching it
// to the garbage bin. Therefore it is important that the node is attached and have parent.
if (element.parentNode) {
discardElement(element);
}
},
/**
* Extend element.destroy by removing it from the clip members array
*/
destroy: function () {
if (this.destroyClip) {
this.destroyClip();
}
return SVGElement.prototype.destroy.apply(this);
},
/**
* Add an event listener. VML override for normalizing event parameters.
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
},
/**
* In stacked columns, cut off the shadows so that they don't overlap
*/
cutOffPath: function (path, length) {
var len;
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
},
/**
* Apply a drop shadow by copying elements and giving them different strokes
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
element = this.element,
renderer = this.renderer,
shadow,
elemStyle = element.style,
markup,
path = element.path,
strokeWidth,
modifiedPath,
shadowWidth,
shadowElementOpacity;
// some times empty paths are not strings
if (path && typeof path.value !== 'string') {
path = 'x';
}
modifiedPath = path;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
for (i = 1; i <= 3; i++) {
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
// Cut off shadows for stacked column items
if (cutOff) {
modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
}
markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
'" filled="false" path="', modifiedPath,
'" coordsize="10 10" style="', element.style.cssText, '" />'];
shadow = createElement(renderer.prepVML(markup),
null, {
left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
}
);
if (cutOff) {
shadow.cutOff = strokeWidth + 1;
}
// apply the opacity
markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
createElement(renderer.prepVML(markup), null, null, shadow);
// insert it
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
// record it
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
}
};
VMLElement = extendClass(SVGElement, VMLElement);
/**
* The VML renderer
*/
var VMLRendererExtension = { // inherit SVGRenderer
Element: VMLElement,
isIE8: userAgent.indexOf('MSIE 8.0') > -1,
/**
* Initialize the VMLRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
*/
init: function (container, width, height) {
var renderer = this,
boxWrapper,
box,
css;
renderer.alignedObjects = [];
boxWrapper = renderer.createElement(DIV);
box = boxWrapper.element;
box.style.position = RELATIVE; // for freeform drawing using renderer directly
container.appendChild(boxWrapper.element);
// generate the containing box
renderer.isVML = true;
renderer.box = box;
renderer.boxWrapper = boxWrapper;
renderer.setSize(width, height, false);
// The only way to make IE6 and IE7 print is to use a global namespace. However,
// with IE8 the only way to make the dynamic shapes visible in screen and print mode
// seems to be to add the xmlns attribute and the behaviour style inline.
if (!doc.namespaces.hcv) {
doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
// Setup default CSS (#2153, #2368, #2384)
css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
'{ behavior:url(#default#VML); display: inline-block; } ';
try {
doc.createStyleSheet().cssText = css;
} catch (e) {
doc.styleSheets[0].cssText += css;
}
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none
*/
isHidden: function () {
return !this.box.offsetWidth;
},
/**
* Define a clipping rectangle. In VML it is accomplished by storing the values
* for setting the CSS style to all associated members.
*
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
// create a dummy element
var clipRect = this.createElement(),
isObj = isObject(x);
// mimic a rectangle with its style object for automatic updating in attr
return extend(clipRect, {
members: [],
left: (isObj ? x.x : x) + 1,
top: (isObj ? x.y : y) + 1,
width: (isObj ? x.width : width) - 1,
height: (isObj ? x.height : height) - 1,
getCSS: function (wrapper) {
var element = wrapper.element,
nodeName = element.nodeName,
isShape = nodeName === 'shape',
inverted = wrapper.inverted,
rect = this,
top = rect.top - (isShape ? element.offsetTop : 0),
left = rect.left,
right = left + rect.width,
bottom = top + rect.height,
ret = {
clip: 'rect(' +
mathRound(inverted ? left : top) + 'px,' +
mathRound(inverted ? bottom : right) + 'px,' +
mathRound(inverted ? right : bottom) + 'px,' +
mathRound(inverted ? top : left) + 'px)'
};
// issue 74 workaround
if (!inverted && docMode8 && nodeName === 'DIV') {
extend(ret, {
width: right + PX,
height: bottom + PX
});
}
return ret;
},
// used in attr and animation to update the clipping of all members
updateClipping: function () {
each(clipRect.members, function (member) {
member.css(clipRect.getCSS(member));
});
}
});
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object, and apply opacity.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop, wrapper) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
markup,
fillType,
ret = NONE;
// Check for linear or radial gradient
if (color && color.linearGradient) {
fillType = 'gradient';
} else if (color && color.radialGradient) {
fillType = 'pattern';
}
if (fillType) {
var stopColor,
stopOpacity,
gradient = color.linearGradient || color.radialGradient,
x1,
y1,
x2,
y2,
opacity1,
opacity2,
color1,
color2,
fillAttr = '',
stops = color.stops,
firstStop,
lastStop,
colors = [],
addFillNode = function () {
// Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
'" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
createElement(renderer.prepVML(markup), null, null, elem);
};
// Extend from 0 to 1
firstStop = stops[0];
lastStop = stops[stops.length - 1];
if (firstStop[0] > 0) {
stops.unshift([
0,
firstStop[1]
]);
}
if (lastStop[0] < 1) {
stops.push([
1,
lastStop[1]
]);
}
// Compute the stops
each(stops, function (stop, i) {
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
// Build the color attribute
colors.push((stop[0] * 100) + '% ' + stopColor);
// Only start and end opacities are allowed, so we use the first and the last
if (!i) {
opacity1 = stopOpacity;
color2 = stopColor;
} else {
opacity2 = stopOpacity;
color1 = stopColor;
}
});
// Apply the gradient to fills only.
if (prop === 'fill') {
// Handle linear gradient angle
if (fillType === 'gradient') {
x1 = gradient.x1 || gradient[0] || 0;
y1 = gradient.y1 || gradient[1] || 0;
x2 = gradient.x2 || gradient[2] || 0;
y2 = gradient.y2 || gradient[3] || 0;
fillAttr = 'angle="' + (90 - math.atan(
(y2 - y1) / // y vector
(x2 - x1) // x vector
) * 180 / mathPI) + '"';
addFillNode();
// Radial (circular) gradient
} else {
var r = gradient.r,
sizex = r * 2,
sizey = r * 2,
cx = gradient.cx,
cy = gradient.cy,
radialReference = elem.radialReference,
bBox,
applyRadialGradient = function () {
if (radialReference) {
bBox = wrapper.getBBox();
cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
sizex *= radialReference[2] / bBox.width;
sizey *= radialReference[2] / bBox.height;
}
fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
'size="' + sizex + ',' + sizey + '" ' +
'origin="0.5,0.5" ' +
'position="' + cx + ',' + cy + '" ' +
'color2="' + color2 + '" ';
addFillNode();
};
// Apply radial gradient
if (wrapper.added) {
applyRadialGradient();
} else {
// We need to know the bounding box to get the size and position right
addEvent(wrapper, 'add', applyRadialGradient);
}
// The fill element's color attribute is broken in IE8 standards mode, so we
// need to set the parent shape's fillcolor attribute instead.
ret = color1;
}
// Gradients are not supported for VML stroke, return the first color. #722.
} else {
ret = stopColor;
}
// if the color is an rgba color, split it and add a fill node
// to hold the opacity component
} else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
colorObject = Color(color);
markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
createElement(this.prepVML(markup), null, null, elem);
ret = colorObject.get('rgb');
} else {
var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
if (propNodes.length) {
propNodes[0].opacity = 1;
propNodes[0].type = 'solid';
}
ret = color;
}
return ret;
},
/**
* Take a VML string and prepare it for either IE8 or IE6/IE7.
* @param {Array} markup A string array of the VML markup to prepare
*/
prepVML: function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
isIE8 = this.isIE8;
markup = markup.join('');
if (isIE8) { // add xmlns and style inline
markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
if (markup.indexOf('style="') === -1) {
markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else { // add namespace
markup = markup.replace('<', '<hcv:');
}
return markup;
},
/**
* Create rotated and aligned text
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
text: SVGRenderer.prototype.html,
/**
* Create and return a path element
* @param {Array} path
*/
path: function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
},
/**
* Create and return a circle element. In VML circles are implemented as
* shapes, which is faster than v:oval
* @param {Number} x
* @param {Number} y
* @param {Number} r
*/
circle: function (x, y, r) {
var circle = this.symbol('circle');
if (isObject(x)) {
r = x.r;
y = x.y;
x = x.x;
}
circle.isCircle = true; // Causes x and y to mean center (#1682)
circle.r = r;
return circle.attr({ x: x, y: y });
},
/**
* Create a group using an outer div and an inner v:group to allow rotating
* and flipping. A simple v:group would have problems with positioning
* child HTML elements and CSS clip.
*
* @param {String} name The name of the group
*/
g: function (name) {
var wrapper,
attribs;
// set the class name
if (name) {
attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
}
// the div to hold HTML and clipping
wrapper = this.createElement(DIV).attr(attribs);
return wrapper;
},
/**
* VML override to create a regular HTML image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var obj = this.createElement('img')
.attr({ src: src });
if (arguments.length > 1) {
obj.attr({
x: x,
y: y,
width: width,
height: height
});
}
return obj;
},
/**
* VML uses a shape for rect to overcome bugs and rotation problems
*/
rect: function (x, y, width, height, r, strokeWidth) {
var wrapper = this.symbol('rect');
wrapper.r = isObject(x) ? x.r : r;
//return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)));
return wrapper.attr(
isObject(x) ?
x :
// do not crispify when an object is passed in (as in column charts)
wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
);
},
/**
* In the VML renderer, each child of an inverted div (group) is inverted
* @param {Object} element
* @param {Object} parentNode
*/
invertChild: function (element, parentNode) {
var parentStyle = parentNode.style;
css(element, {
flip: 'x',
left: pInt(parentStyle.width) - 1,
top: pInt(parentStyle.height) - 1,
rotation: -90
});
},
/**
* Symbol definitions that override the parent SVG renderer's symbols
*
*/
symbols: {
// VML specific arc function
arc: function (x, y, w, h, options) {
var start = options.start,
end = options.end,
radius = options.r || w || h,
innerRadius = options.innerR,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
ret;
if (end - start === 0) { // no angle, don't show it.
return ['x'];
}
ret = [
'wa', // clockwise arc to
x - radius, // left
y - radius, // top
x + radius, // right
y + radius, // bottom
x + radius * cosStart, // start x
y + radius * sinStart, // start y
x + radius * cosEnd, // end x
y + radius * sinEnd // end y
];
if (options.open && !innerRadius) {
ret.push(
'e',
M,
x,// - innerRadius,
y// - innerRadius
);
}
ret.push(
'at', // anti clockwise arc to
x - innerRadius, // left
y - innerRadius, // top
x + innerRadius, // right
y + innerRadius, // bottom
x + innerRadius * cosEnd, // start x
y + innerRadius * sinEnd, // start y
x + innerRadius * cosStart, // end x
y + innerRadius * sinStart, // end y
'x', // finish path
'e' // close
);
ret.isArc = true;
return ret;
},
// Add circle symbol path. This performs significantly faster than v:oval.
circle: function (x, y, w, h, wrapper) {
if (wrapper) {
w = h = 2 * wrapper.r;
}
// Center correction, #1682
if (wrapper && wrapper.isCircle) {
x -= w / 2;
y -= h / 2;
}
// Return the path
return [
'wa', // clockwisearcto
x, // left
y, // top
x + w, // right
y + h, // bottom
x + w, // start x
y + h / 2, // start y
x + w, // end x
y + h / 2, // end y
//'x', // finish path
'e' // close
];
},
/**
* Add rectangle symbol path which eases rotation and omits arcsize problems
* compared to the built-in VML roundrect shape
*
* @param {Number} left Left position
* @param {Number} top Top position
* @param {Number} r Border radius
* @param {Object} options Width and height
*/
rect: function (left, top, width, height, options) {
var right = left + width,
bottom = top + height,
ret,
r;
// No radius, return the more lightweight square
if (!defined(options) || !options.r) {
ret = SVGRenderer.prototype.symbols.square.apply(0, arguments);
// Has radius add arcs for the corners
} else {
r = mathMin(options.r, width, height);
ret = [
M,
left + r, top,
L,
right - r, top,
'wa',
right - 2 * r, top,
right, top + 2 * r,
right - r, top,
right, top + r,
L,
right, bottom - r,
'wa',
right - 2 * r, bottom - 2 * r,
right, bottom,
right, bottom - r,
right - r, bottom,
L,
left + r, bottom,
'wa',
left, bottom - 2 * r,
left + 2 * r, bottom,
left + r, bottom,
left, bottom - r,
L,
left, top + r,
'wa',
left, top,
left + 2 * r, top + 2 * r,
left, top + r,
left + r, top,
'x',
'e'
];
}
return ret;
}
}
};
Highcharts.VMLRenderer = VMLRenderer = function () {
this.init.apply(this, arguments);
};
VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
// general renderer
Renderer = VMLRenderer;
}
// This method is used with exporting in old IE, when emulating SVG (see #2314)
SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
var measuringSpan = doc.createElement('span'),
textNode = doc.createTextNode(text);
measuringSpan.appendChild(textNode);
css(measuringSpan, styles);
this.box.appendChild(measuringSpan);
return measuringSpan.offsetWidth;
};
/* ****************************************************************************
* *
* END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
*****************************************************************************/
/* ****************************************************************************
* *
* START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
* TARGETING THAT SYSTEM. *
* *
*****************************************************************************/
var CanVGRenderer,
CanVGController;
if (useCanVG) {
/**
* The CanVGRenderer is empty from start to keep the source footprint small.
* When requested, the CanVGController downloads the rest of the source packaged
* together with the canvg library.
*/
Highcharts.CanVGRenderer = CanVGRenderer = function () {
// Override the global SVG namespace to fake SVG/HTML that accepts CSS
SVG_NS = 'http://www.w3.org/1999/xhtml';
};
/**
* Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
* the implementation from SvgRenderer will not be merged in until first render.
*/
CanVGRenderer.prototype.symbols = {};
/**
* Handles on demand download of canvg rendering support.
*/
CanVGController = (function () {
// List of renderering calls
var deferredRenderCalls = [];
/**
* When downloaded, we are ready to draw deferred charts.
*/
function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
}
return {
push: function (func, scriptLocation) {
// Only get the script once
if (deferredRenderCalls.length === 0) {
getScript(scriptLocation, drawDeferred);
}
// Register render call
deferredRenderCalls.push(func);
}
};
}());
Renderer = CanVGRenderer;
} // end CanVGRenderer
/* ****************************************************************************
* *
* END OF ANDROID < 3 SPECIFIC CODE *
* *
*****************************************************************************/
/**
* The Tick class
*/
function Tick(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
}
Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function () {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
horiz = axis.horiz,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
width = (horiz && categories &&
!labelOptions.step && !labelOptions.staggerLines &&
!labelOptions.rotation &&
chart.plotWidth / tickPositions.length) ||
(!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
css,
attr,
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(lin2log(value)) : value
});
// prepare CSS
css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
css = extend(css, labelOptions.style);
// first call
if (!defined(label)) {
attr = {
align: axis.labelAlign
};
if (isNumber(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation;
}
if (width && labelOptions.ellipsis) {
attr._clipHeight = axis.len / tickPositions.length;
}
tick.label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
.attr(attr)
// without position absolute, IE export sometimes is wrong
.css(css)
.add(axis.labelGroup) :
null;
// update
} else if (label) {
label.attr({
text: str
})
.css(css);
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function () {
var label = this.label,
axis = this.axis;
return label ?
((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision
* detection with overflow logic.
*/
getLabelSides: function () {
var bBox = this.labelBBox, // assume getLabelSize has run at this point
axis = this.axis,
options = axis.options,
labelOptions = options.labels,
width = bBox.width,
leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x;
return [-leftSide, width - leftSide];
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function (index, xy) {
var show = true,
axis = this.axis,
chart = axis.chart,
isFirst = this.isFirst,
isLast = this.isLast,
x = xy.x,
reversed = axis.reversed,
tickPositions = axis.tickPositions;
if (isFirst || isLast) {
var sides = this.getLabelSides(),
leftSide = sides[0],
rightSide = sides[1],
plotLeft = chart.plotLeft,
plotRight = plotLeft + axis.len,
neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]],
neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
if ((isFirst && !reversed) || (isLast && reversed)) {
// Is the label spilling out to the left of the plot area?
if (x + leftSide < plotLeft) {
// Align it to plot left
x = plotLeft - leftSide;
// Hide it if it now overlaps the neighbour label
if (neighbour && x + rightSide > neighbourEdge) {
show = false;
}
}
} else {
// Is the label spilling out to the right of the plot area?
if (x + rightSide > plotRight) {
// Align it to plot right
x = plotRight - rightSide;
// Hide it if it now overlaps the neighbour label
if (neighbour && x + leftSide < neighbourEdge) {
show = false;
}
}
}
// Set the modified x position of the label
xy.x = x;
}
return show;
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function (horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b,
rotation = labelOptions.rotation;
x = x + labelOptions.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + labelOptions.y - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for rotation (#1764)
if (rotation && axis.side === 2) {
y -= baseline - baseline * mathCos(rotation * deg2rad);
}
// Vertically centered
if (!defined(labelOptions.y) && !rotation) { // #1951
y += baseline - label.getBBox().height / 2;
}
// Correct for staggered labels
if (staggerLines) {
y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: y
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
M,
x,
y,
L,
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function (index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
gridPrefix = type ? type + 'Grid' : 'grid',
tickPrefix = type ? type + 'Tick' : 'tick',
gridLineWidth = options[gridPrefix + 'LineWidth'],
gridLineColor = options[gridPrefix + 'LineColor'],
dashStyle = options[gridPrefix + 'LineDashStyle'],
tickLength = options[tickPrefix + 'Length'],
tickWidth = options[tickPrefix + 'Width'] || 0,
tickColor = options[tickPrefix + 'Color'],
tickPosition = options[tickPrefix + 'Position'],
gridLinePath,
mark = tick.mark,
markPath,
step = labelOptions.step,
attribs,
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687
staggerLines = axis.staggerLines;
this.isActive = true;
// create the grid line
if (gridLineWidth) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
if (gridLine === UNDEFINED) {
attribs = {
stroke: gridLineColor,
'stroke-width': gridLineWidth
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine =
gridLineWidth ?
renderer.path(gridLinePath)
.attr(attribs).add(axis.gridGroup) :
null;
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine && gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickWidth && tickLength) {
// negate the length
if (tickPosition === 'inside') {
tickLength = -tickLength;
}
if (axis.opposite) {
tickLength = -tickLength;
}
markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
if (mark) { // updating
mark.animate({
d: markPath,
opacity: opacity
});
} else { // first time
tick.mark = renderer.path(
markPath
).attr({
stroke: tickColor,
'stroke-width': tickWidth,
opacity: opacity
}).add(axis.axisGroup);
}
}
// the label is created on init - now move it into place
if (label && !isNaN(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) {
show = false;
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && !isNaN(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
tick.isNew = false;
} else {
label.attr('y', -9999); // #1338
}
}
},
/**
* Destructor for the tick prototype
*/
destroy: function () {
destroyObjectProperties(this, this.axis);
}
};
/**
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
function PlotLineOrBand(axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
}
PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function () {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
halfPointRange = (axis.pointRange || 0) / 2,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
width = options.width,
to = options.to,
from = options.from,
isBand = defined(from) && defined(to),
value = options.value,
dashStyle = options.dashStyle,
svgElem = plotLine.svgElem,
path = [],
addEvent,
eventType,
xs,
ys,
x,
y,
color = options.color,
zIndex = options.zIndex,
events = options.events,
attribs,
renderer = axis.chart.renderer;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// plot line
if (width) {
path = axis.getPlotLinePath(value, width);
attribs = {
stroke: color,
'stroke-width': width
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
} else if (isBand) { // plot band
// keep within plot area
from = mathMax(from, axis.min - halfPointRange);
to = mathMin(to, axis.max + halfPointRange);
path = axis.getPlotBandPath(from, to, options);
attribs = {
fill: color
};
if (options.borderWidth) {
attribs.stroke = options.borderColor;
attribs['stroke-width'] = options.borderWidth;
}
} else {
return;
}
// zIndex
if (defined(zIndex)) {
attribs.zIndex = zIndex;
}
// common for lines and bands
if (svgElem) {
if (path) {
svgElem.animate({
d: path
}, null, svgElem.onGetPath);
} else {
svgElem.hide();
svgElem.onGetPath = function () {
svgElem.show();
};
if (label) {
plotLine.label = label = label.destroy();
}
}
} else if (path && path.length) {
plotLine.svgElem = svgElem = renderer.path(path)
.attr(attribs).add();
// events
if (events) {
addEvent = function (eventType) {
svgElem.on(eventType, function (e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign : !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
// add the SVG element
if (!label) {
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr({
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation,
zIndex: zIndex
})
.css(optionsLabel.style)
.add();
}
// get the bounding box and align the label
xs = [path[1], path[4], pick(path[6], path[1])];
ys = [path[2], path[5], pick(path[7], path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Remove the plot line or band
*/
destroy: function () {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* The class for stack items
*/
function StackItem(axis, options, isNegative, x, stackOption, stacking) {
var inverted = axis.chart.inverted;
this.axis = axis;
// Tells if the stack is negative
this.isNegative = isNegative;
// Save the options to be able to style the label
this.options = options;
// Save the x value to be able to position the label later
this.x = x;
// Initialize total value
this.total = null;
// This will keep each points' extremes stored by series.index
this.points = {};
// Save the stack option on the series configuration object, and whether to treat it as percent
this.stack = stackOption;
this.percent = stacking === 'percent';
// The align options and text align varies on whether the stack is negative and
// if the chart is inverted or not.
// First test the user supplied value, then use the dynamic.
this.alignOptions = {
align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
};
this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
}
StackItem.prototype = {
destroy: function () {
destroyObjectProperties(this, this.axis);
},
/**
* Renders the stack total label and adds it to the stack label group.
*/
render: function (group) {
var options = this.options,
formatOption = options.format,
str = formatOption ?
format(formatOption, this) :
options.formatter.call(this); // format the text in the label
// Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
if (this.label) {
this.label.attr({text: str, visibility: HIDDEN});
// Create new label
} else {
this.label =
this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
.css(options.style) // apply style
.attr({
align: this.textAlign, // fix the text-anchor
rotation: options.rotation, // rotation
visibility: HIDDEN // hidden until setOffset is called
})
.add(group); // add to the labels-group
}
},
/**
* Sets the offset that the stack has from the x value and repositions the label.
*/
setOffset: function (xOffset, xWidth) {
var stackItem = this,
axis = stackItem.axis,
chart = axis.chart,
inverted = chart.inverted,
neg = this.isNegative, // special treatment is needed for negative stacks
y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
yZero = axis.translate(0), // stack origin
h = mathAbs(y - yZero), // stack height
x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
plotHeight = chart.plotHeight,
stackBox = { // this is the box for the complete stack
x: inverted ? (neg ? y : y - h) : x,
y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
width: inverted ? h : xWidth,
height: inverted ? xWidth : h
},
label = this.label,
alignAttr;
if (label) {
label.align(this.alignOptions, null, stackBox); // align the label to the box
// Set visibility (#678)
alignAttr = label.alignAttr;
label.attr({
visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ?
(hasSVG ? 'inherit' : VISIBLE) :
HIDDEN
});
}
}
};
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
function Axis() {
this.init.apply(this, arguments);
}
Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
gridLineColor: '#C0C0C0',
// gridLineDashStyle: 'solid',
// gridLineWidth: 0,
// reversed: false,
labels: defaultLabelOptions,
// { step: null },
lineColor: '#C0D0E0',
lineWidth: 1,
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
minorGridLineColor: '#E0E0E0',
// minorGridLineDashStyle: null,
minorGridLineWidth: 1,
minorTickColor: '#A0A0A0',
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//minorTickWidth: 0,
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
tickColor: '#C0D0E0',
//tickInterval: null,
tickLength: 5,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
tickWidth: 1,
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
style: {
color: '#4d759e',
//font: defaultFont.replace('normal', 'bold')
fontWeight: 'bold'
}
//x: 0,
//y: 0
},
type: 'linear' // linear, logarithmic or datetime
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
gridLineWidth: 1,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8,
y: 3
},
lineWidth: 0,
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
tickWidth: 0,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function () {
return numberFormat(this.total, -1);
},
style: defaultLabelOptions.style
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -8,
y: null
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 8,
y: null
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
x: 0,
y: 14
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultTopAxisOptions: {
labels: {
x: 0,
y: -5
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function (chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.xOrY = isXAxis ? 'x' : 'y';
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
axis.minPixelPadding = 0;
//axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
//axis.ignoreMaxPadding = UNDEFINED;
axis.chart = chart;
axis.reversed = options.reversed;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.categories = options.categories || type === 'category';
axis.names = [];
// Elements
//axis.axisGroup = UNDEFINED;
//axis.gridGroup = UNDEFINED;
//axis.axisTitle = UNDEFINED;
//axis.axisLine = UNDEFINED;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = UNDEFINED;
// Tick positions
//axis.tickPositions = UNDEFINED; // array containing predefined positions
// Tick intervals
//axis.tickInterval = UNDEFINED;
//axis.minorTickInterval = UNDEFINED;
axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
// Major ticks
axis.ticks = {};
// Minor ticks
axis.minorTicks = {};
//axis.tickAmount = UNDEFINED;
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = UNDEFINED;
//axis.top = UNDEFINED;
//axis.width = UNDEFINED;
//axis.height = UNDEFINED;
//axis.bottom = UNDEFINED;
//axis.right = UNDEFINED;
//axis.transA = UNDEFINED;
//axis.transB = UNDEFINED;
//axis.oldTransA = UNDEFINED;
axis.len = 0;
//axis.oldMin = UNDEFINED;
//axis.oldMax = UNDEFINED;
//axis.oldUserMin = UNDEFINED;
//axis.oldUserMax = UNDEFINED;
//axis.oldAxisLength = UNDEFINED;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
// Dictionary for stacks max values
axis.stackExtremes = {};
// Min and max in the data
//axis.dataMin = UNDEFINED,
//axis.dataMax = UNDEFINED,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = UNDEFINED,
//axis.userMax = UNDEFINED,
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
chart.axes.push(axis);
chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = log2lin;
axis.lin2val = lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function (userOptions) {
this.options = merge(
this.defaultOptions,
this.isXAxis ? {} : this.defaultYAxisOptions,
[this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
merge(
defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* Update the axis with a new options structure
*/
update: function (newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306
this.init(chart, extend(newOptions, { events: UNDEFINED }));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function (redraw) {
var chart = this.chart,
key = this.xOrY + 'Axis'; // xAxis or yAxis
// Remove associated series
each(this.series, function (series) {
series.remove(false);
});
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function (axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (value >= 1000) { // add thousands separators
ret = numberFormat(value, 0);
} else { // small numbers
ret = numberFormat(value, -1);
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function () {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// reset dataMin and dataMax in case we're redrawing
axis.dataMin = axis.dataMax = null;
// reset cached stacking extremes
axis.stackExtremes = {};
axis.buildStacks();
// loop through this axis' series
each(axis.series, function (series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
if (axis.dataMin >= threshold) {
axis.dataMin = threshold;
axis.ignoreMinPadding = true;
} else if (axis.dataMax < threshold) {
axis.dataMax = threshold;
axis.ignoreMaxPadding = true;
}
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
axisLength = axis.len,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axisLength;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * axisLength;
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function (value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function (pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function (value, lineWidth, old, force) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
translatedValue = axis.translate(value, null, null, old),
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB;
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
if (x1 < axisLeft || x1 > axisLeft + axis.width) {
skip = true;
}
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
if (y1 < axisTop || y1 > axisTop + axis.height) {
skip = true;
}
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0);
},
/**
* Create the path for a plot band
*/
getPlotBandPath: function (from, to) {
var toPath = this.getPlotLinePath(to),
path = this.getPlotLinePath(from);
if (path && toPath) {
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function (tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
tickPositions = [];
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Set the tick positions of a logarithmic axis
*/
getLogTickPositions: function (interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = mathRound(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = mathFloor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max)) { // #1670
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function () {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
len;
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
getTimeTicks(
normalizeTimeTickInterval(minorTickInterval),
axis.min,
axis.max,
options.startOfWeek
)
);
if (minorTickPositions[0] < axis.min) {
minorTickPositions.shift();
}
} else {
for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function () {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function (series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === UNDEFINED || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
var minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Update translation information
*/
setAxisTranslation: function (saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
transA = axis.transA;
// adjust translation for padding
if (axis.isXAxis) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
each(axis.series, function (series) {
var seriesPointRange = series.pointRange,
pointPlacement = series.options.pointPlacement,
seriesClosestPointRange = series.closestPointRange;
if (seriesPointRange > range) { // #1446
seriesPointRange = 0;
}
pointRange = mathMax(pointRange, seriesPointRange);
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = mathMax(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = mathMax(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
// Set the closestPointRange
if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
closestPointRange = defined(closestPointRange) ?
mathMin(closestPointRange, seriesClosestPointRange) :
seriesClosestPointRange;
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = mathMin(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
axis.closestPointRange = closestPointRange;
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickPositions: function (secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
tickPositioner = axis.options.tickPositioner,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickIntervalOption = options.minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
tickPositions,
keepTwoTicksOnly,
categories = axis.categories;
// linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
} else { // initial min and max from the extreme data values
axis.min = pick(axis.userMin, options.min, axis.dataMin);
axis.max = pick(axis.userMax, options.max, axis.dataMax);
}
if (isLog) {
if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
axis.max = correctFloat(log2lin(axis.max));
}
// handle zoomed range
if (axis.range) {
axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
axis.userMax = axis.max;
if (secondPass) {
axis.range = null; // don't use it when running setExtremes
}
}
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
axis.min -= length * minPadding;
}
if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
axis.max += length * maxPadding;
}
}
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
);
// For squished axes, set only two ticks
if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) {
keepTwoTicksOnly = true;
axis.tickInterval /= 4; // tick extremes closer to the real values
}
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function (series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943)
if (axis.pointRange) {
axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
axis.tickInterval = minTickIntervalOption;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog) { // linear
if (!tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options);
}
}
// get minorTickInterval
axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
axis.tickInterval / 5 : options.minorTickInterval;
// find the tick positions
axis.tickPositions = tickPositions = options.tickPositions ?
[].concat(options.tickPositions) : // Work on a copy (#1565)
(tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
if (!tickPositions) {
// Too many ticks
if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) {
error(19, true);
}
if (isDatetimeAxis) {
tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)(
normalizeTimeTickInterval(axis.tickInterval, options.units),
axis.min,
axis.max,
options.startOfWeek,
axis.ordinalPositions,
axis.closestPointRange,
true
);
} else if (isLog) {
tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
} else {
tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
}
if (keepTwoTicksOnly) {
tickPositions.splice(1, tickPositions.length - 2);
}
axis.tickPositions = tickPositions;
}
if (!isLinked) {
// reset min/max or remove extremes based on start/end on tick
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = axis.minPointOffset || 0,
singlePad;
if (options.startOnTick) {
axis.min = roundedMin;
} else if (axis.min - minPointOffset > roundedMin) {
tickPositions.shift();
}
if (options.endOnTick) {
axis.max = roundedMax;
} else if (axis.max + minPointOffset < roundedMax) {
tickPositions.pop();
}
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (tickPositions.length === 1) {
singlePad = 0.001; // The lowest possible number to avoid extra padding on columns
axis.min -= singlePad;
axis.max += singlePad;
}
}
},
/**
* Set the max ticks of either the x and y axis collection
*/
setMaxTicks: function () {
var chart = this.chart,
maxTicks = chart.maxTicks || {},
tickPositions = this.tickPositions,
key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-');
if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
maxTicks[key] = tickPositions.length;
}
chart.maxTicks = maxTicks;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function () {
var axis = this,
chart = axis.chart,
key = axis._maxTicksKey,
tickPositions = axis.tickPositions,
maxTicks = chart.maxTicks;
if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale
var oldTickAmount = axis.tickAmount,
calculatedTickAmount = tickPositions.length,
tickAmount;
// set the axis-level tickAmount to use below
axis.tickAmount = tickAmount = maxTicks[key];
if (calculatedTickAmount < tickAmount) {
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + axis.tickInterval
));
}
axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
axis.max = tickPositions[tickPositions.length - 1];
}
if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
axis.isDirty = true;
}
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function () {
var axis = this,
stacks = axis.stacks,
type,
i,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function (series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
// reset stacks
if (!axis.isXAxis) {
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].total = null;
stacks[type][i].cum = 0;
}
}
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickPositions();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (!axis.isXAxis) {
if (axis.oldStacks) {
stacks = axis.stacks = axis.oldStacks;
}
// reset stacks
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].cum = stacks[type][i].total;
}
}
}
// Set the maximum tick amount
axis.setMaxTicks();
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
// Mark for running afterSetExtremes
axis.isDirtyExtremes = true;
// redraw
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function (newMin, newMax) {
// Prevent pinch zooming out of range. Check for defined is for #1946.
if (!this.allowZoomOutside) {
if (defined(this.dataMin) && newMin <= this.dataMin) {
newMin = UNDEFINED;
}
if (defined(this.dataMax) && newMax >= this.dataMax) {
newMax = UNDEFINED;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
// Do it
this.setExtremes(
newMin,
newMax,
false,
UNDEFINED,
{ trigger: 'zoom' }
);
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function () {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width,
height,
top,
left;
// Expose basic values to use in Series object and navigator
this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
this.top = top = pick(options.top, chart.plotTop);
this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
this.height = height = pick(options.height, chart.plotHeight);
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function () {
var axis = this,
isLog = axis.isLog;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function (threshold) {
var axis = this,
isLog = axis.isLog;
var realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (realMin > threshold || threshold === null) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
addPlotBand: function (options) {
this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function (options) {
this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function (options, coll) {
var obj = new PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function (rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
directionFactor = [-1, 1, 1, -1][side],
n,
i,
autoStaggerLines = 1,
maxStaggerLines = pick(labelOptions.maxStaggerLines, 5),
sortedPositions,
lastRight,
overlap,
pos,
bBox,
x,
w,
lineNo;
// For reuse in Axis.render
axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({ zIndex: options.gridZIndex || 1 })
.add();
axis.axisGroup = renderer.g('axis')
.attr({ zIndex: options.zIndex || 2 })
.add();
axis.labelGroup = renderer.g('axis-labels')
.attr({ zIndex: labelOptions.zIndex || 7 })
.add();
}
if (hasData || axis.isLinked) {
// Set the explicit or automatic label alignment
axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation));
// Generate ticks
each(tickPositions, function (pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
// Handle automatic stagger lines
if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) {
sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions;
while (autoStaggerLines < maxStaggerLines) {
lastRight = [];
overlap = false;
for (i = 0; i < sortedPositions.length; i++) {
pos = sortedPositions[i];
bBox = ticks[pos].label && ticks[pos].label.getBBox();
w = bBox ? bBox.width : 0;
lineNo = i % autoStaggerLines;
if (w) {
x = axis.translate(pos); // don't handle log
if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) {
overlap = true;
}
lastRight[lineNo] = x + w;
}
}
if (overlap) {
autoStaggerLines++;
} else {
break;
}
}
if (autoStaggerLines > 1) {
axis.staggerLines = autoStaggerLines;
}
}
each(tickPositions, function (pos) {
// left side must be align: right and right side must have align: left for labels
if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
// get the highest offset
labelOffset = mathMax(
ticks[pos].getLabelSize(),
labelOffset
);
}
});
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset;
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align:
axisTitleOptions.textAlign ||
{ low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
})
.css(axisTitleOptions.style)
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
titleOffsetOption = axisTitleOptions.offset;
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide']();
}
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.axisTitleMargin =
pick(titleOffsetOption,
labelOffset + titleMargin +
(side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x'])
);
axisOffset[side] = mathMax(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
);
clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
},
/**
* Get the path for the axis line
*/
getLinePath: function (lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer.crispLine([
M,
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
L,
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Position the title
*/
getTitlePosition: function () {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
fontSize = pInt(axisTitleOptions.style.fontSize || 12),
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis :
offAxis + (opposite ? this.width : 0) + offset +
(axisTitleOptions.x || 0), // x
y: horiz ?
offAxis - (opposite ? this.height : 0) + offset :
alongAxis + (axisTitleOptions.y || 0) // y
};
},
/**
* Render the axis
*/
render: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
stacks = axis.stacks,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
lineWidth = options.lineWidth,
linePath,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
hasData = axis.hasData,
showAxis = axis.showAxis,
from,
to;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function (coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (hasData || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function (pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) {
// Reorganize the indices
i = (i === tickPositions.length - 1) ? 0 : i + 1;
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true);
}
ticks[pos].render(i, false, 1);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && axis.min === 0) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function (pos, i) {
if (i % 2 === 0 && pos < axis.max) {
if (!alternateBands[pos]) {
alternateBands[pos] = new PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function (coll) {
var pos,
i,
forDestruction = [],
delay = globalAnimation ? globalAnimation.duration || 500 : 0,
destroyInactiveItems = function () {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
if (coll === alternateBands || !chart.hasRendered || !delay) {
destroyInactiveItems();
} else if (delay) {
setTimeout(destroyInactiveItems, delay);
}
});
// Static items. As the axis group is cleared on subsequent calls
// to render, these items are added outside the group.
// axis line
if (lineWidth) {
linePath = axis.getLinePath(lineWidth);
if (!axis.axisLine) {
axis.axisLine = renderer.path(linePath)
.attr({
stroke: options.lineColor,
'stroke-width': lineWidth,
zIndex: 7
})
.add(axis.axisGroup);
} else {
axis.axisLine.animate({ d: linePath });
}
// show or hide the line depending on options.showEmpty
axis.axisLine[showAxis ? 'show' : 'hide']();
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
var stackKey, oneStack, stackCategory,
stackTotalGroup = axis.stackTotalGroup;
// Create a separate group for the stack total labels
if (!stackTotalGroup) {
axis.stackTotalGroup = stackTotalGroup =
renderer.g('stack-labels')
.attr({
visibility: VISIBLE,
zIndex: 6
})
.add();
}
// plotLeft/Top will change when y axis gets wider so we need to translate the
// stackTotalGroup at every render call. See bug #506 and #516
stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
// Render each stack total
for (stackKey in stacks) {
oneStack = stacks[stackKey];
for (stackCategory in oneStack) {
oneStack[stackCategory].render(stackTotalGroup);
}
}
}
// End stacked totals
axis.isDirty = false;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function (id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
},
/**
* Update the axis title by options
*/
setTitle: function (newTitleOptions, redraw) {
this.update({ title: newTitleOptions }, redraw);
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function () {
var axis = this,
chart = axis.chart,
pointer = chart.pointer;
// hide tooltip and hover states
if (pointer.reset) {
pointer.reset(true);
}
// render the axis
axis.render();
// move plot lines and bands
each(axis.plotLinesAndBands, function (plotLine) {
plotLine.render();
});
// mark associated series as dirty and ready for redraw
each(axis.series, function (series) {
series.isDirty = true;
});
},
/**
* Build the stacks from top down
*/
buildStacks: function () {
var series = this.series,
i = series.length;
if (!this.isXAxis) {
while (i--) {
series[i].setStackedPoints();
}
// Loop up again to compute percent stack
if (this.usePercentage) {
for (i = 0; i < series.length; i++) {
series[i].setPercentStacks();
}
}
}
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function (categories, redraw) {
this.update({ categories: categories }, redraw);
},
/**
* Destroys an Axis instance.
*/
destroy: function (keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
destroyObjectProperties(coll);
});
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
}
}; // end Axis
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
function Tooltip() {
this.init.apply(this, arguments);
}
Tooltip.prototype = {
init: function (chart, options) {
var borderWidth = options.borderWidth,
style = options.style,
padding = pInt(style.padding);
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = UNDEFINED;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = { x: 0, y: 0 };
// The tooltip is initially hidden
this.isHidden = true;
// create the label
this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
.attr({
padding: padding,
fill: options.backgroundColor,
'stroke-width': borderWidth,
r: options.borderRadius,
zIndex: 8
})
.css(style)
.css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
.add()
.attr({ y: -999 }); // #2301
// When using canVG the shadow shows up as a gray circle
// even if the tooltip is hidden.
if (!useCanVG) {
this.label.shadow(options.shadow);
}
// Public property for getting the shared state.
this.shared = options.shared;
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function () {
each(this.crosshairs, function (crosshair) {
if (crosshair) {
crosshair.destroy();
}
});
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function (x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden;
// get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// move to the intermediate value
tooltip.label.attr(now);
// run on next tick of the mouse tracker
if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
// never allow two timeouts
clearTimeout(this.tooltipTimeout);
// set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function () {
// The interval function may still be running during destroy, so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function () {
var tooltip = this,
hoverPoints;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
if (!this.isHidden) {
hoverPoints = this.chart.hoverPoints;
this.hideTimer = setTimeout(function () {
tooltip.label.fadeOut();
tooltip.isHidden = true;
}, pick(this.options.hideDelay, 500));
// hide previous hoverPoints and set new
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
this.chart.hoverPoints = null;
}
},
/**
* Hide the crosshairs
*/
hideCrosshairs: function () {
each(this.crosshairs, function (crosshair) {
if (crosshair) {
crosshair.hide();
}
});
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotX = 0,
plotY = 0,
yAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
plotX += point.plotX;
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function (boxWidth, boxHeight, point) {
// Set up the variables
var chart = this.chart,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
distance = pick(this.options.distance, 12),
pointX = point.plotX,
pointY = point.plotY,
x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
alignedRight;
// It is too far to the left, adjust it
if (x < 7) {
x = plotLeft + mathMax(pointX, 0) + distance;
}
// Test to see if the tooltip is too far to the right,
// if it is, move it back to be inside and then up to not cover the point.
if ((x + boxWidth) > (plotLeft + plotWidth)) {
x -= (x + boxWidth) - (plotLeft + plotWidth);
y = pointY - boxHeight + plotTop - distance;
alignedRight = true;
}
// If it is now above the plot area, align it to the top of the plot area
if (y < plotTop + 5) {
y = plotTop + 5;
// If the tooltip is still covering the point, move it below instead
if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
y = pointY + plotTop + distance; // below
}
}
// Now if the tooltip is below the chart, move it up. It's better to cover the
// point than to disappear outside the chart. #834.
if (y + boxHeight > plotTop + plotHeight) {
y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
}
return {x: x, y: y};
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*/
defaultFormatter: function (tooltip) {
var items = this.points || splat(this),
series = items[0].series,
s;
// build the header
s = [series.tooltipHeaderFormatter(items[0])];
// build the values
each(items, function (item) {
series = item.series;
s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
});
// footer
s.push(tooltip.options.footerFormat || '');
return s.join('');
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function (point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.label,
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
borderColor,
crosshairsOptions = options.crosshairs,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(point, function (item) {
item.setState(HOVER_STATE);
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr('opacity', 1).show();
}
// update text
label.attr({
text: text
});
// set the stroke color of the box
borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
label.attr({
stroke: borderColor
});
tooltip.updatePosition({ plotX: x, plotY: y });
this.isHidden = false;
}
// crosshairs
if (crosshairsOptions) {
crosshairsOptions = splat(crosshairsOptions); // [x, y]
var path,
i = crosshairsOptions.length,
attribs,
axis,
val,
series;
while (i--) {
series = point.series;
axis = series[i ? 'yAxis' : 'xAxis'];
if (crosshairsOptions[i] && axis) {
val = i ? pick(point.stackY, point.y) : point.x; // #814
if (axis.isLog) { // #1671
val = log2lin(val);
}
if (i === 1 && series.modifyValue) { // #1205, #2316
val = series.modifyValue(val);
}
path = axis.getPlotLinePath(
val,
1
);
if (tooltip.crosshairs[i]) {
tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE });
} else {
attribs = {
'stroke-width': crosshairsOptions[i].width || 1,
stroke: crosshairsOptions[i].color || '#C0C0C0',
zIndex: crosshairsOptions[i].zIndex || 2
};
if (crosshairsOptions[i].dashStyle) {
attribs.dashstyle = crosshairsOptions[i].dashStyle;
}
tooltip.crosshairs[i] = chart.renderer.path(path)
.attr(attribs)
.add();
}
}
}
}
fireEvent(chart, 'tooltipRefresh', {
text: text,
x: x + chart.plotLeft,
y: y + chart.plotTop,
borderColor: borderColor
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
}
};
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
function Pointer(chart, options) {
this.init(chart, options);
}
Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function (chart, options) {
var chartOptions = options.chart,
chartEvents = chartOptions.events,
zoomType = useCanVG ? '' : chartOptions.zoomType,
inverted = chart.inverted,
zoomX,
zoomY;
// Store references
this.options = options;
this.chart = chart;
// Zoom status
this.zoomX = zoomX = /x/.test(zoomType);
this.zoomY = zoomY = /y/.test(zoomType);
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
// Do we need to handle click on a touch device?
this.runChartClick = chartEvents && !!chartEvents.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
}
this.setDOMEvents();
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function (e, chartPosition) {
var chartX,
chartY,
ePos;
// common IE normalizing
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// Framework specific normalizing (#1165)
e = washMouseEvent(e);
// iOS
ePos = e.touches ? e.touches.item(0) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: mathRound(chartX),
chartY: mathRound(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function (e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function (axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* Return the index in the tooltipPoints array, corresponding to pixel position in
* the plot area.
*/
getIndex: function (e) {
var chart = this.chart;
return chart.inverted ?
chart.plotHeight + chart.plotTop - e.chartY :
e.chartX - chart.plotLeft;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function (e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
point,
points,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
j,
distance = chart.chartWidth,
index = pointer.getIndex(e),
anchor;
// shared tooltip
if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
points = [];
// loop over all series and find the ones with points closest to the mouse
i = series.length;
for (j = 0; j < i; j++) {
if (series[j].visible &&
series[j].options.enableMouseTracking !== false &&
!series[j].noSharedTooltip && series[j].tooltipPoints.length) {
point = series[j].tooltipPoints[index];
if (point && point.series) { // not a dummy point, #1544
point._dist = mathAbs(index - point.clientX);
distance = mathMin(distance, point._dist);
points.push(point);
}
}
}
// remove furthest points
i = points.length;
while (i--) {
if (points[i]._dist > distance) {
points.splice(i, 1);
}
}
// refresh the tooltip if necessary
if (points.length && (points[0].clientX !== pointer.hoverX)) {
tooltip.refresh(points, e);
pointer.hoverX = points[0].clientX;
}
}
// separate tooltip and general mouse events
if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker
// get the point
point = hoverSeries.tooltipPoints[index];
// a new point is hovered, refresh the tooltip
if (point && point !== hoverPoint) {
// trigger the events
point.onMouseOver(e);
}
} else if (tooltip && tooltip.followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
}
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function (allowMove) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
// Narrow in allowMove
allowMove = allowMove && tooltip && tooltipPoints;
// Check if the points have moved outside the plot area, #1003
if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
allowMove = false;
}
// Just move the tooltip, #349
if (allowMove) {
tooltip.refresh(tooltipPoints);
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide();
tooltip.hideCrosshairs();
}
pointer.hoverX = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function (attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function (series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Run translation operations
*/
pinchTranslate: function (zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (zoomHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (zoomVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function () {
if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) { // TODO: implement clipping for inverted charts
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function (e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
zoomHor = self.zoomHor || self.pinchHor,
zoomVert = self.zoomVert || self.pinchVert,
hasZoom = zoomHor || zoomVert,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
chart.runTrackerClick) || chart.runChartClick),
clip = {};
// On touch devices, only proceed to trigger click if a handler is defined
if ((hasZoom || followTouchMove) && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function (e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function (e, i) {
pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(axis.dataMin),
max = axis.toPixels(axis.dataMax),
absMin = mathMin(min, max),
absMax = mathMax(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
}
});
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop
}, chart.plotBox);
}
self.pinchTranslate(zoomHor, zoomVert, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
}
}
},
/**
* Start a drag operation
*/
dragStart: function (e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function (e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY;
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
if (!this.selectionMarker) {
this.selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
zIndex: 7
})
.add();
}
}
// adjust the width of the selection marker
if (this.selectionMarker && zoomHor) {
size = chartX - mouseDownX;
this.selectionMarker.attr({
width: mathAbs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (this.selectionMarker && zoomVert) {
size = chartY - mouseDownY;
this.selectionMarker.attr({
height: mathAbs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !this.selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function (e) {
var chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.x,
selectionTop = selectionBox.y,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var horiz = axis.horiz,
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height));
if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
selectionData[axis.xOrY + 'Axis'].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes,
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function (e) {
e = this.normalize(e);
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function (e) {
this.drop(e);
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function (e) {
var chart = this.chart,
chartPosition = this.chartPosition,
hoverSeries = chart.hoverSeries;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function () {
this.reset();
this.chartPosition = null; // also reset the chart position, used in #149 fix
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function (e) {
var chart = this.chart;
// normalize
e = this.normalize(e);
// #295
e.returnValue = false;
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function (element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
} else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function (e) {
var series = this.chart.hoverSeries;
if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) {
series.onMouseOut();
}
},
onContainerClick: function (e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
inverted = chart.inverted,
chartPosition,
plotX,
plotY;
e = this.normalize(e);
e.cancelBubble = true; // IE specific
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
chartPosition = this.chartPosition;
plotX = hoverPoint.plotX;
plotY = hoverPoint.plotY;
// add page position info
extend(hoverPoint, {
pageX: chartPosition.left + plotLeft +
(inverted ? chart.plotWidth - plotY : plotX),
pageY: chartPosition.top + plotTop +
(inverted ? chart.plotHeight - plotX : plotY)
});
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
onContainerTouchStart: function (e) {
var chart = this.chart;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
// Prevent the click pseudo event from firing unless it is set in the options
/*if (!chart.runChartClick) {
e.preventDefault();
}*/
// Run mouse events and display tooltip etc
this.runPointActions(e);
this.pinch(e);
} else {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchMove: function (e) {
if (e.touches.length === 1 || e.touches.length === 2) {
this.pinch(e);
}
},
onDocumentTouchEnd: function (e) {
this.drop(e);
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function () {
var pointer = this,
container = pointer.chart.container,
events;
this._events = events = [
[container, 'onmousedown', 'onContainerMouseDown'],
[container, 'onmousemove', 'onContainerMouseMove'],
[container, 'onclick', 'onContainerClick'],
[container, 'mouseleave', 'onContainerMouseLeave'],
[doc, 'mousemove', 'onDocumentMouseMove'],
[doc, 'mouseup', 'onDocumentMouseUp']
];
if (hasTouch) {
events.push(
[container, 'ontouchstart', 'onContainerTouchStart'],
[container, 'ontouchmove', 'onContainerTouchMove'],
[doc, 'touchend', 'onDocumentTouchEnd']
);
}
each(events, function (eventConfig) {
// First, create the callback function that in turn calls the method on Pointer
pointer['_' + eventConfig[2]] = function (e) {
pointer[eventConfig[2]](e);
};
// Now attach the function, either as a direct property or through addEvent
if (eventConfig[1].indexOf('on') === 0) {
eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]];
} else {
addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
}
});
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function () {
var pointer = this;
// Release all DOM events
each(pointer._events, function (eventConfig) {
if (eventConfig[1].indexOf('on') === 0) {
eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE
} else {
removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
}
});
delete pointer._events;
// memory and CPU leak
clearInterval(pointer.tooltipTimeout);
}
};
/**
* The overview of the chart's series
*/
function Legend(chart, options) {
this.init(chart, options);
}
Legend.prototype = {
/**
* Initialize the legend
*/
init: function (chart, options) {
var legend = this,
itemStyle = options.itemStyle,
padding = pick(options.padding, 8),
itemMarginTop = options.itemMarginTop || 0;
this.options = options;
if (!options.enabled) {
return;
}
legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
legend.itemStyle = itemStyle;
legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
legend.itemMarginTop = itemMarginTop;
legend.padding = padding;
legend.initialItemX = padding;
legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
legend.maxItemWidth = 0;
legend.chart = chart;
legend.itemHeight = 0;
legend.lastLineHeight = 0;
// Render it
legend.render();
// move checkboxes
addEvent(legend.chart, 'endResize', function () {
legend.positionCheckboxes();
});
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function (item, visible) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ? item.color : hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = {
stroke: symbolColor,
fill: symbolColor
},
key,
val;
if (legendItem) {
legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
markerOptions = item.convertAttribs(markerOptions);
for (key in markerOptions) {
val = markerOptions[key];
if (val !== UNDEFINED) {
symbolAttr[key] = val;
}
}
}
legendSymbol.attr(symbolAttr);
}
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox;
if (item.legendGroup) {
item.legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function () {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({ zIndex: 1 })
.css(titleOptions.style)
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = options.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 8) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
series = item.series || item,
itemOptions = series.options,
showCheckbox = itemOptions.showCheckbox,
useHTML = options.useHTML;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline,
useHTML
)
.css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? li : item.legendGroup).on('mouseover', function () {
item.setState(HOVER_STATE);
li.css(legend.options.itemHoverStyle);
})
.on('mouseout', function () {
li.css(item.visible ? itemStyle : itemHiddenStyle);
item.setState();
})
.on('click', function (event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function () {
item.setVisible();
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
// Colorize the items
legend.colorizeItem(item, item.visible);
// add the HTML checkbox on top
if (itemOptions && showCheckbox) {
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, options.itemCheckboxStyle, chart.container);
addEvent(item.checkbox, 'click', function (event) {
var target = event.target;
fireEvent(item, 'checkboxClick', {
checked: target.checked
},
function () {
item.select();
}
);
});
}
}
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.legendItemWidth =
options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance +
(showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = bBox.height;
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || mathMax(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
legendBorderWidth = options.borderWidth,
legendBackgroundColor = options.backgroundColor;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = [];
each(chart.series, function (serie) {
var seriesOptions = serie.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, seriesOptions.linkedTo === UNDEFINED ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
serie.legendItems ||
(seriesOptions.legendType === 'point' ?
serie.data :
serie)
);
});
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
each(allItems, function (item) {
legend.renderItem(item);
});
// Draw the border
legendWidth = options.width || legend.offsetWidth;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
if (legendBorderWidth || legendBackgroundColor) {
legendWidth += padding;
legendHeight += padding;
if (!box) {
legend.box = box = renderer.rect(
0,
0,
legendWidth,
legendHeight,
options.borderRadius,
legendBorderWidth || 0
).attr({
stroke: options.borderColor,
'stroke-width': legendBorderWidth || 0,
fill: legendBackgroundColor || NONE
})
.add(legendGroup)
.shadow(options.shadow);
box.isNew = true;
} else if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp(null, null, null, legendWidth, legendHeight)
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function (item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
pageCount,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav;
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = mathMin(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
if (legendHeight > spaceHeight && !options.useHTML) {
this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight;
this.pageCount = pageCount = mathCeil(legendHeight / clipHeight);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipRect.attr({
height: clipHeight
});
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.css(navOptions.style)
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipRect.attr({
height: chart.chartHeight
});
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function (scrollBy, animation) {
var pageCount = this.pageCount,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + this.pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1;
this.scrollGroup.animate({
translateY: scrollOffset
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview.
// TODO: When IE11 is released, check again for this bug, and remove the fix
// or make a better one.
if (/Trident\/7\.0/.test(userAgent)) {
wrap(Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
runPositionItem = function () {
proceed.call(legend, item);
};
if (legend.chart.renderer.forExport) {
runPositionItem();
} else {
setTimeout(runPositionItem);
}
});
}
/**
* The chart class
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
function Chart() {
this.init.apply(this, arguments);
}
Chart.prototype = {
/**
* Initialize the chart
*/
init: function (userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
var optionsChart = options.chart;
// Create margin & spacing array
this.margin = this.splashArray('margin', optionsChart);
this.spacing = this.splashArray('spacing', optionsChart);
var chartEvents = optionsChart.events;
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = UNDEFINED;
//chartSubtitleOptions = UNDEFINED;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = UNDEFINED;
//this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
//this.inverted = UNDEFINED;
//this.loadingShown = UNDEFINED;
//this.container = UNDEFINED;
//this.chartWidth = UNDEFINED;
//this.chartHeight = UNDEFINED;
//this.marginRight = UNDEFINED;
//this.marginBottom = UNDEFINED;
//this.containerWidth = UNDEFINED;
//this.containerHeight = UNDEFINED;
//this.oldChartWidth = UNDEFINED;
//this.oldChartHeight = UNDEFINED;
//this.renderTo = UNDEFINED;
//this.renderToClone = UNDEFINED;
//this.spacingBox = UNDEFINED
//this.legend = UNDEFINED;
// Elements
//this.chartBackground = UNDEFINED;
//this.plotBackground = UNDEFINED;
//this.plotBGImage = UNDEFINED;
//this.plotBorder = UNDEFINED;
//this.loadingDiv = UNDEFINED;
//this.loadingSpan = UNDEFINED;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
// Set up auto resize
if (optionsChart.reflow !== false) {
addEvent(chart, 'load', function () {
chart.initReflow();
});
}
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
// Expose methods and variables
chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
chart.pointCount = 0;
chart.counters = new ChartCounters();
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function (options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
constr = seriesTypes[type];
// No such series type
if (!constr) {
error(17, true);
}
series = new constr();
series.init(this, options);
return series;
},
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function (options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', { options: options }, function () {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function (options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
axis;
/*jslint unused: false*/
axis = new Axis(this, merge(options, {
index: this[key].length,
isX: isX
}));
/*jslint unused: true*/
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(options);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function (plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Adjust all axes tick amounts
*/
adjustTickAmounts: function () {
if (this.options.chart.alignTicks !== false) {
each(this.axes, function (axis) {
axis.adjustTickAmount();
});
}
this.maxTicks = null;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function (animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// handle updated data in the series
each(series, function (serie) {
if (serie.isDirty) { // prepare the data so axis can read it
if (serie.options.legendType === 'point') {
redrawLegend = true;
}
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (chart.hasCartesianSeries) {
if (!chart.isResizing) {
// reset maxTicks
chart.maxTicks = null;
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
}
chart.adjustTickAmounts();
chart.getMargins();
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function (axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function (axis) {
// Fire 'afterSetExtremes' only if extremes are set
if (axis.isDirtyExtremes) { // #821
axis.isDirtyExtremes = false;
afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function (serie) {
if (serie.isDirty && serie.visible &&
(!serie.isCartesian || serie.xAxis)) { // issue #153
serie.redraw();
}
});
// move tooltip or reset
if (pointer && pointer.reset) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function (callback) {
callback.call();
});
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function (str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv;
var loadingOptions = options.loading;
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement(DIV, {
className: PREFIX + 'loading'
}, extend(loadingOptions.style, {
zIndex: 10,
display: NONE
}), chart.container);
chart.loadingSpan = createElement(
'span',
null,
loadingOptions.labelStyle,
loadingDiv
);
}
// update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
// show it
if (!chart.loadingShown) {
css(loadingDiv, {
opacity: 0,
display: '',
left: chart.plotLeft + PX,
top: chart.plotTop + PX,
width: chart.plotWidth + PX,
height: chart.plotHeight + PX
});
animate(loadingDiv, {
opacity: loadingOptions.style.opacity
}, {
duration: loadingOptions.showDuration || 0
});
chart.loadingShown = true;
}
},
/**
* Hide the loading layer
*/
hideLoading: function () {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration || 100,
complete: function () {
css(loadingDiv, { display: NONE });
}
});
}
this.loadingShown = false;
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function (id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function () {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray,
axis;
// make sure the options are arrays and add some members
each(xAxisOptions, function (axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function (axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function (axisOptions) {
axis = new Axis(chart, axisOptions);
});
chart.adjustTickAmounts();
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function () {
var points = [];
each(this.series, function (serie) {
points = points.concat(grep(serie.points || [], function (point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function () {
return grep(this.series, function (serie) {
return serie.selected;
});
},
/**
* Generate stacks for each series and calculate stacks total values
*/
getStacks: function () {
var chart = this;
// reset stacks for each yAxis
each(chart.yAxis, function (axis) {
if (axis.stacks && axis.hasVisibleSeries) {
axis.oldStacks = axis.stacks;
}
});
each(chart.series, function (series) {
if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
series.stackKey = series.type + pick(series.options.stack, '');
}
});
},
/**
* Display the zoom button
*/
showResetZoom: function () {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function () {
var chart = this;
fireEvent(chart, 'selection', { resetSelection: true }, function () {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function (event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function (axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function (axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function (e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
var mousePos = e[isX ? 'chartX' : 'chartY'],
axis = chart[isX ? 'xAxis' : 'yAxis'][0],
startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange;
if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
doRedraw = true;
}
chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, { cursor: 'move' });
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function (titleOptions, subtitleOptions) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles();
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function () {
var titleOffset = 0,
title = this.title,
subtitle = this.subtitle,
options = this.options,
titleOptions = options.title,
subtitleOptions = options.subtitle,
autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
if (title) {
title
.css({ width: (titleOptions.width || autoWidth) + PX })
.align(extend({ y: 15 }, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = title.getBBox().height;
// Adjust for browser consistency + backwards compat after #776 fix
if (titleOffset >= 18 && titleOffset <= 25) {
titleOffset = 15;
}
}
}
if (subtitle) {
subtitle
.css({ width: (subtitleOptions.width || autoWidth) + PX })
.align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox');
if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
}
}
this.titleOffset = titleOffset; // used in getMargins
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function () {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderToClone || chart.renderTo;
// get inner width and height from jQuery (#824)
chart.containerWidth = adapterRun(renderTo, 'width');
chart.containerHeight = adapterRun(renderTo, 'height');
chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = mathMax(0, pick(optionsChart.height,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function (revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
this.renderTo.appendChild(container);
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: ABSOLUTE,
top: '-9999px',
display: 'block' // #833
});
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function () {
var chart = this,
container,
optionsChart = chart.options.chart,
chartWidth,
chartHeight,
renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
containerId;
chart.renderTo = renderTo = optionsChart.renderTo;
containerId = PREFIX + idCounter++;
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (!isNaN(oldChartIndex) && charts[oldChartIndex]) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly
if (!renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// create the inner container
chart.container = container = createElement(DIV, {
className: PREFIX + 'container' +
(optionsChart.className ? ' ' + optionsChart.className : ''),
id: containerId
}, extend({
position: RELATIVE,
overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
// content overflow in IE
width: chartWidth + PX,
height: chartHeight + PX,
textAlign: 'left',
lineHeight: 'normal', // #427
zIndex: 0, // #1072
'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
}, optionsChart.style),
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
chart.renderer =
optionsChart.forExport ? // force SVG, used for SVG export
new SVGRenderer(container, chartWidth, chartHeight, true) :
new Renderer(container, chartWidth, chartHeight);
if (useCanVG) {
// If we need canvg library, extend and configure the renderer
// to get the tracker for translating mouse events
chart.renderer.create(chart, container, chartWidth, chartHeight);
}
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function () {
var chart = this,
spacing = chart.spacing,
axisOffset,
legend = chart.legend,
margin = chart.margin,
legendOptions = chart.options.legend,
legendMargin = pick(legendOptions.margin, 10),
legendX = legendOptions.x,
legendY = legendOptions.y,
align = legendOptions.align,
verticalAlign = legendOptions.verticalAlign,
titleOffset = chart.titleOffset;
chart.resetMargins();
axisOffset = chart.axisOffset;
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
if (legend.display && !legendOptions.floating) {
if (align === 'right') { // horizontal alignment handled first
if (!defined(margin[1])) {
chart.marginRight = mathMax(
chart.marginRight,
legend.legendWidth - legendX + legendMargin + spacing[1]
);
}
} else if (align === 'left') {
if (!defined(margin[3])) {
chart.plotLeft = mathMax(
chart.plotLeft,
legend.legendWidth + legendX + legendMargin + spacing[3]
);
}
} else if (verticalAlign === 'top') {
if (!defined(margin[0])) {
chart.plotTop = mathMax(
chart.plotTop,
legend.legendHeight + legendY + legendMargin + spacing[0]
);
}
} else if (verticalAlign === 'bottom') {
if (!defined(margin[2])) {
chart.marginBottom = mathMax(
chart.marginBottom,
legend.legendHeight - legendY + legendMargin + spacing[2]
);
}
}
}
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function (axis) {
axis.getOffset();
});
}
if (!defined(margin[3])) {
chart.plotLeft += axisOffset[3];
}
if (!defined(margin[0])) {
chart.plotTop += axisOffset[0];
}
if (!defined(margin[2])) {
chart.marginBottom += axisOffset[2];
}
if (!defined(margin[1])) {
chart.marginRight += axisOffset[1];
}
chart.setChartSize();
},
/**
* Add the event handlers necessary for auto resizing
*
*/
initReflow: function () {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
reflowTimeout;
function reflow(e) {
var width = optionsChart.width || adapterRun(renderTo, 'width'),
height = optionsChart.height || adapterRun(renderTo, 'height'),
target = e ? e.target : win; // #805 - MooTools doesn't supply e
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(reflowTimeout);
chart.reflowTimeout = reflowTimeout = setTimeout(function () {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(width, height, false);
chart.hasUserSize = null;
}
}, 100);
}
chart.containerWidth = width;
chart.containerHeight = height;
}
}
chart.reflow = reflow;
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function () {
removeEvent(win, 'resize', reflow);
});
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
css(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
});
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function (skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
chart.plotTop = plotTop = mathRound(chart.plotTop);
chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
};
if (!skipAxes) {
each(chart.axes, function (axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function () {
var chart = this,
spacing = chart.spacing,
margin = chart.margin;
chart.plotTop = pick(margin[0], spacing[0]);
chart.marginRight = pick(margin[1], spacing[1]);
chart.marginBottom = pick(margin[2], spacing[2]);
chart.plotLeft = pick(margin[3], spacing[3]);
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function () {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
plotBGImage = chart.plotBGImage,
chartBorderWidth = optionsChart.borderWidth || 0,
chartBackgroundColor = optionsChart.backgroundColor,
plotBackgroundColor = optionsChart.plotBackgroundColor,
plotBackgroundImage = optionsChart.plotBackgroundImage,
plotBorderWidth = optionsChart.plotBorderWidth || 0,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox;
// Chart area
mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
if (chartBorderWidth || chartBackgroundColor) {
if (!chartBackground) {
bgAttr = {
fill: chartBackgroundColor || NONE
};
if (chartBorderWidth) { // #980
bgAttr.stroke = optionsChart.borderColor;
bgAttr['stroke-width'] = chartBorderWidth;
}
chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
optionsChart.borderRadius, chartBorderWidth)
.attr(bgAttr)
.add()
.shadow(optionsChart.shadow);
} else { // resize
chartBackground.animate(
chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn)
);
}
}
// Plot background
if (plotBackgroundColor) {
if (!plotBackground) {
chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
.attr({
fill: plotBackgroundColor
})
.add()
.shadow(optionsChart.plotShadow);
} else {
plotBackground.animate(plotBox);
}
}
if (plotBackgroundImage) {
if (!plotBGImage) {
chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
.add();
} else {
plotBGImage.animate(plotBox);
}
}
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
if (plotBorderWidth) {
if (!plotBorder) {
chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
.attr({
stroke: optionsChart.plotBorderColor,
'stroke-width': plotBorderWidth,
zIndex: 1
})
.add();
} else {
plotBorder.animate(
plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight)
);
}
}
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.invert property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function () {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function (key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value = (
chart[key] || // 1. it is set before
optionsChart[key] || // 2. it is set in the options
(klass && klass.prototype[key]) // 3. it's default series class requires it
);
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function () {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function (series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function (series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo) {
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
}
}
});
},
/**
* Render all graphics for the chart
*/
render: function () {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options;
var labels = options.labels,
credits = options.credits,
creditsHref;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
chart.getStacks(); // render stacks
// Get margins by pre-rendering axes
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
chart.getMargins();
chart.maxTicks = null; // reset for second pass
each(axes, function (axis) {
axis.setTickPositions(true); // update to reflect the new margins
axis.setMaxTicks();
});
chart.adjustTickAmounts();
chart.getMargins(); // second pass to check for new labels
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function (axis) {
axis.render();
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({ zIndex: 3 })
.add();
}
each(chart.series, function (serie) {
serie.translate();
serie.setTooltipPoints();
serie.render();
});
// Labels
if (labels.items) {
each(labels.items, function (label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
renderer.text(
label.html,
x,
y
)
.attr({ zIndex: 2 })
.css(style)
.add();
});
}
// Credits
if (credits.enabled && !chart.credits) {
creditsHref = credits.href;
chart.credits = renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (creditsHref) {
location.href = creditsHref;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
// Set flag
chart.hasRendered = true;
},
/**
* Clean up memory usage
*/
destroy: function () {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = UNDEFINED;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function () {
var chart = this;
// Note: in spite of JSLint's complaints, win == win.top is required
/*jslint eqeq: true*/
if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
/*jslint eqeq: false*/
if (useCanVG) {
// Delay rendering until canvg library is downloaded and ready
CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
} else {
doc.attachEvent('onreadystatechange', function () {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
}
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function () {
var chart = this,
options = chart.options,
callback = chart.callback;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function (serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
chart.pointer = new Pointer(chart, options);
chart.render();
// add canvas
chart.renderer.draw();
// run callbacks
if (callback) {
callback.apply(chart, [chart]);
}
each(chart.callbacks, function (fn) {
fn.apply(chart, [chart]);
});
// If the chart was rendered outside the top container, put it back in
chart.cloneRenderTo(true);
fireEvent(chart, 'load');
},
/**
* Creates arrays for spacing and margin from given options.
*/
splashArray: function (target, options) {
var oVar = options[target],
tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
return [pick(options[target + 'Top'], tArray[0]),
pick(options[target + 'Right'], tArray[1]),
pick(options[target + 'Bottom'], tArray[2]),
pick(options[target + 'Left'], tArray[3])];
}
}; // end Chart
// Hook for exporting module
Chart.prototype.callbacks = [];
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
var Point = function () {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function (series, options, x) {
var point = this,
colors;
point.series = series;
point.applyOptions(options, x);
point.pointAttr = {};
if (series.options.colorByPoint) {
colors = series.options.colors || series.chart.options.colors;
point.color = point.color || colors[series.colorCounter++];
// loop back to zero
if (series.colorCounter === colors.length) {
series.colorCounter = 0;
}
}
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function (options, x) {
var point = this,
series = point.series,
pointValKey = series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if (point.x === UNDEFINED && series) {
point.x = x === UNDEFINED ? series.autoIncrement() : x;
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function (options) {
var ret = {},
series = this.series,
pointArrayMap = series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (typeof options === 'number' || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
ret[pointArrayMap[j++]] = options[i++];
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function () {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function () {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function () {
var point = this;
return {
x: point.category,
y: point.y,
key: point.name || point.category,
series: point.series,
point: point,
percentage: point.percentage,
total: point.total || point.stackTotal
};
},
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function (selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the defalut handler
point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && SELECT_STATE);
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function (loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState(NORMAL_STATE);
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*/
onMouseOver: function (e) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
// trigger the event
point.firePointEvent('mouseOver');
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.refresh(point, e);
}
// hover this
point.setState(HOVER_STATE);
chart.hoverPoint = point;
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
this.firePointEvent('mouseOut');
this.setState();
chart.hoverPoint = null;
}
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function (pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function (key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Update the point with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
*/
update: function (options, redraw, animation) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
data = series.data,
chart = series.chart,
seriesOptions = series.options;
redraw = pick(redraw, true);
// fire the event with a default handler of doing the update
point.firePointEvent('update', { options: options }, function () {
point.applyOptions(options);
// update visuals
if (isObject(options)) {
series.getAttribs();
if (graphic) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
} else {
graphic.attr(point.pointAttr[point.state || '']);
}
}
}
// record changes in the parallel arrays
i = inArray(point, data);
series.xData[i] = point.x;
series.yData[i] = series.toYData ? series.toYData(point) : point.y;
series.zData[i] = point.z;
seriesOptions.data[i] = point.options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.legend.destroyItem(point);
}
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var point = this,
series = point.series,
points = series.points,
chart = series.chart,
i,
data = series.data;
setAnimation(animation, chart);
redraw = pick(redraw, true);
// fire the event with a default handler of removing the point
point.firePointEvent('remove', null, function () {
// splice all the parallel arrays
i = inArray(point, data);
if (data.length === points.length) {
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.xData.splice(i, 1);
series.yData.splice(i, 1);
series.zData.splice(i, 1);
point.destroy();
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
});
},
/**
* Fire an event on the Point object. Must not be renamed to fireEvent, as this
* causes a name clash in MooTools
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function (eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function (event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function () {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function (state) {
var point = this,
plotX = point.plotX,
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states,
markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
normalDisabled = markerOptions && !markerOptions.enabled,
markerStateOptions = markerOptions && markerOptions.states[state],
stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
radius,
newSymbol,
pointAttr = point.pointAttr;
state = state || NORMAL_STATE; // empty string
if (
// already has this state
state === point.state ||
// selected points don't respond to hover
(point.selected && state !== SELECT_STATE) ||
// series' state options is disabled
(stateOptions[state] && stateOptions[state].enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
// apply hover styles to the existing point
if (point.graphic) {
radius = markerOptions && point.graphic.symbolName && pointAttr[state].r;
point.graphic.attr(merge(
pointAttr[state],
radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {}
));
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
radius = markerStateOptions.radius;
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr[state])
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
// Move the existing graphic
} else {
stateMarkerGraphic.attr({ // #1054
x: plotX - radius,
y: plotY - radius
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide']();
}
}
point.state = state;
}
};
/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
var Series = function () {};
Series.prototype = {
isCartesian: true,
type: 'line',
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'lineColor',
'stroke-width': 'lineWidth',
fill: 'fillColor',
r: 'radius'
},
colorCounter: 0,
init: function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series;
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// set the data
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123)
stableSort(chartSeries, function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, a._i);
});
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
if (series.isCartesian) {
each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS]) {
error(18, true);
}
});
}
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function () {
var series = this,
options = series.options,
xIncrement = series.xIncrement;
xIncrement = pick(xIncrement, options.pointStart, 0);
series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
series.xIncrement = xIncrement + series.pointInterval;
return xIncrement;
},
/**
* Divide the series data into segments divided by null values.
*/
getSegments: function () {
var series = this,
lastNull = -1,
segments = [],
i,
points = series.points,
pointsLength = points.length;
if (pointsLength) { // no action required for []
// if connect nulls, just remove null points
if (series.options.connectNulls) {
i = pointsLength;
while (i--) {
if (points[i].y === null) {
points.splice(i, 1);
}
}
if (points.length) {
segments = [points];
}
// else, split on null points
} else {
each(points, function (point, i) {
if (point.y === null) {
if (i > lastNull + 1) {
segments.push(points.slice(lastNull + 1, i));
}
lastNull = i;
} else if (i === pointsLength - 1) { // last value
segments.push(points.slice(lastNull + 1, i + 1));
}
});
}
}
// register it
series.segments = segments;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function (itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
typeOptions = plotOptions[this.type],
options;
this.userOptions = itemOptions;
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// the tooltip options are merged between global and series specific options
this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip);
// Delte marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
return options;
},
/**
* Get the series' color
*/
getColor: function () {
var options = this.options,
userOptions = this.userOptions,
defaultColors = this.chart.options.colors,
counters = this.chart.counters,
color,
colorIndex;
color = options.color || defaultPlotOptions[this.type].color;
if (!color && !options.colorByPoint) {
if (defined(userOptions._colorIndex)) { // after Series.update()
colorIndex = userOptions._colorIndex;
} else {
userOptions._colorIndex = counters.color;
colorIndex = counters.color++;
}
color = defaultColors[colorIndex];
}
this.color = color;
counters.wrapColor(defaultColors.length);
},
/**
* Get the series' symbol
*/
getSymbol: function () {
var series = this,
userOptions = series.userOptions,
seriesMarkerOption = series.options.marker,
chart = series.chart,
defaultSymbols = chart.options.symbols,
counters = chart.counters,
symbolIndex;
series.symbol = seriesMarkerOption.symbol;
if (!series.symbol) {
if (defined(userOptions._symbolIndex)) { // after Series.update()
symbolIndex = userOptions._symbolIndex;
} else {
userOptions._symbolIndex = counters.symbol;
symbolIndex = counters.symbol++;
}
series.symbol = defaultSymbols[symbolIndex];
}
// don't substract radius in image symbols (#604)
if (/^url/.test(series.symbol)) {
seriesMarkerOption.radius = 0;
}
counters.wrapSymbol(defaultSymbols.length);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLegendSymbol: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendOptions = legend.options,
legendSymbol,
symbolWidth = legendOptions.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
},
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function (options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
graph = series.graph,
area = series.area,
chart = series.chart,
xData = series.xData,
yData = series.yData,
zData = series.zData,
names = series.xAxis && series.xAxis.names,
currentShift = (graph && graph.shift) || 0,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
x,
i;
setAnimation(animation, chart);
// Make graph animate sideways
if (shift) {
each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
if (shape) {
shape.shift = currentShift + 1;
}
});
}
if (area) {
area.isArea = true; // needed in animation, both with and without shift
}
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = { series: series };
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
xData.splice(i, 0, x);
yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y);
zData.splice(i, 0, point.z);
if (names) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
// todo: consider series.removePoint(i) method
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
xData.shift();
yData.shift();
zData.shift();
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
series.getAttribs(); // #1937
chart.redraw();
}
},
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function (data, redraw) {
var series = this,
oldData = series.points,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
names = xAxis && xAxis.names,
i;
// reset properties
series.xIncrement = null;
series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// parallel arrays
var xData = [],
yData = [],
zData = [],
dataLength = data ? data.length : [],
turboThreshold = pick(options.turboThreshold, 1000),
pt,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length,
hasToYData = !!series.toYData;
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
var x = pick(options.pointStart, 0),
pointInterval = pick(options.pointInterval, 1);
for (i = 0; i < dataLength; i++) {
xData[i] = x;
yData[i] = data[i];
x += pointInterval;
}
series.xIncrement = x;
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== UNDEFINED) { // stray commas in oldIE
pt = { series: series };
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
xData[i] = pt.x;
yData[i] = hasToYData ? series.toYData(pt) : pt.y;
zData[i] = pt.z;
if (names && pt.name) {
names[pt.x] = pt.name; // #2046
}
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = data;
series.xData = xData;
series.yData = yData;
series.zData = zData;
// destroy old points
i = (oldData && oldData.length) || 0;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw(false);
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var series = this,
chart = series.chart;
redraw = pick(redraw, true);
if (!series.isRemoving) { /* prevent triggering native event in jQuery
(calling the remove function from the remove event) */
series.isRemoving = true;
// fire the event with a default handler of removing the point
fireEvent(series, 'remove', null, function () {
// destroy elements
series.destroy();
// redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
series.isRemoving = false;
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
isCartesian = series.isCartesian;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
var min = xAxis.min,
max = xAxis.max;
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function (xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = mathMax(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (; i < dataLength; i++) {
if (xData[i] > max) {
cropEnd = i + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Adds series' points value to corresponding stack
*/
setStackedPoints: function () {
if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
return;
}
var series = this,
xData = series.processedXData,
yData = series.processedYData,
stackedYData = [],
yDataLength = yData.length,
seriesOptions = series.options,
threshold = seriesOptions.threshold,
stackOption = seriesOptions.stack,
stacking = seriesOptions.stacking,
stackKey = series.stackKey,
negKey = '-' + stackKey,
negStacks = series.negStacks,
yAxis = series.yAxis,
stacks = yAxis.stacks,
oldStacks = yAxis.oldStacks,
isNegative,
stack,
other,
key,
i,
x,
y;
// loop over the non-null y values and read them into a local array
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// Read stacked values into a stack based on the x value,
// the sign of y and the stack key. Stacking is also handled for null values (#739)
isNegative = negStacks && y < threshold;
key = isNegative ? negKey : stackKey;
// Create empty object for this stack if it doesn't exist yet
if (!stacks[key]) {
stacks[key] = {};
}
// Initialize StackItem for this x
if (!stacks[key][x]) {
if (oldStacks[key] && oldStacks[key][x]) {
stacks[key][x] = oldStacks[key][x];
stacks[key][x].total = null;
} else {
stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking);
}
}
// If the StackItem doesn't exist, create it first
stack = stacks[key][x];
stack.points[series.index] = [stack.cum || 0];
// Add value to the stack total
if (stacking === 'percent') {
// Percent stacked column, totals are the same for the positive and negative stacks
other = isNegative ? stackKey : negKey;
if (negStacks && stacks[other] && stacks[other][x]) {
other = stacks[other][x];
stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
// Percent stacked areas
} else {
stack.total += mathAbs(y) || 0;
}
} else {
stack.total += y || 0;
}
stack.cum = (stack.cum || 0) + (y || 0);
stack.points[series.index].push(stack.cum);
stackedYData[i] = stack.cum;
}
if (stacking === 'percent') {
yAxis.usePercentage = true;
}
this.stackedYData = stackedYData; // To be used in getExtremes
// Reset old stacks
yAxis.oldStacks = {};
},
/**
* Iterate over all stacks and compute the absolute values to percent
*/
setPercentStacks: function () {
var series = this,
stackKey = series.stackKey,
stacks = series.yAxis.stacks;
each([stackKey, '-' + stackKey], function (key) {
var i = series.xData.length,
x,
stack,
pointExtremes,
totalFactor;
while (i--) {
x = series.xData[i];
stack = stacks[key] && stacks[key][x];
pointExtremes = stack && stack.points[series.index];
if (pointExtremes) {
totalFactor = stack.total ? 100 / stack.total : 0;
pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
series.stackedYData[i] = pointExtremes[1];
}
}
});
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function () {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yData = this.stackedYData || this.processedYData,
yDataLength = yData.length,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
dataMin,
dataMax,
x,
y,
i,
j;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
(xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = pick(dataMin, arrayMin(activeYData));
this.dataMax = pick(dataMax, arrayMax(activeYData));
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function () {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes
if (yAxis.isLog && yValue <= 0) {
point.y = yValue = null;
}
// Get the plotX translation
point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
// Calculate the bottom y value for stacked series
if (stacking && series.visible && stack && stack[xValue]) {
pointStack = stack[xValue];
stackValues = pointStack.points[series.index];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === 0) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = stacking === 'percent' && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
//mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
yAxis.translate(yValue, 0, 1, 0, 1) :
UNDEFINED;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== UNDEFINED ?
categories[point.x] : point.x;
}
// now that we have the cropped data, build the segments
series.getSegments();
},
/**
* Memoize tooltip texts and positions
*/
setTooltipPoints: function (renew) {
var series = this,
points = [],
pointsLength,
low,
high,
xAxis = series.xAxis,
xExtremes = xAxis && xAxis.getExtremes(),
axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
point,
pointX,
nextPoint,
i,
tooltipPoints = []; // a lookup array for each pixel in the x dimension
// don't waste resources if tracker is disabled
if (series.options.enableMouseTracking === false) {
return;
}
// renew
if (renew) {
series.tooltipPoints = null;
}
// concat segments to overcome null values
each(series.segments || series.points, function (segment) {
points = points.concat(segment);
});
// Reverse the points in case the X axis is reversed
if (xAxis && xAxis.reversed) {
points = points.reverse();
}
// Polar needs additional shaping
if (series.orderTooltipPoints) {
series.orderTooltipPoints(points);
}
// Assign each pixel position to the nearest point
pointsLength = points.length;
for (i = 0; i < pointsLength; i++) {
point = points[i];
pointX = point.x;
if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149
nextPoint = points[i + 1];
// Set this range's low to the last range's high plus one
low = high === UNDEFINED ? 0 : high + 1;
// Now find the new high
high = points[i + 1] ?
mathMin(mathMax(0, mathFloor( // #2070
(point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2
)), axisLength) :
axisLength;
while (low >= 0 && low <= high) {
tooltipPoints[low++] = point;
}
}
}
series.tooltipPoints = tooltipPoints;
},
/**
* Format the header of the tooltip
*/
tooltipHeaderFormatter: function (point) {
var series = this,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime',
headerFormat = tooltipOptions.headerFormat,
closestPointRange = xAxis && xAxis.closestPointRange,
n;
// Guess the best date format based on the closest point distance (#568)
if (isDateTime && !xDateFormat) {
if (closestPointRange) {
for (n in timeUnits) {
if (timeUnits[n] >= closestPointRange) {
xDateFormat = dateTimeLabelFormats[n];
break;
}
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
}
// Insert the header date format if any
if (isDateTime && xDateFormat && isNumber(point.key)) {
headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(headerFormat, {
point: point,
series: series
});
},
/**
* Series mouse over handler
*/
onMouseOver: function () {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState(HOVER_STATE);
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function () {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
chart.hoverSeries = null;
},
/**
* Animate in the series
*/
animate: function (init) {
var series = this,
chart = series.chart,
renderer = chart.renderer,
clipRect,
markerClipRect,
animation = series.options.animation,
clipBox = chart.clipBox,
inverted = chart.inverted,
sharedClipKey;
// Animation option is set to true
if (animation && !isObject(animation)) {
animation = defaultPlotOptions[series.type].animation;
}
sharedClipKey = '_sharedClip' + animation.duration + animation.easing;
// Initialize the animation. Set up the clipping rectangle.
if (init) {
// If a clipping rectangle with the same properties is currently present in the chart, use that.
clipRect = chart[sharedClipKey];
markerClipRect = chart[sharedClipKey + 'm'];
if (!clipRect) {
chart[sharedClipKey] = clipRect = renderer.clipRect(
extend(clipBox, { width: 0 })
);
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
series.group.clip(clipRect);
series.markerGroup.clip(markerClipRect);
series.sharedClipKey = sharedClipKey;
// Run the animation
} else {
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
series.animationTimeout = setTimeout(function () {
series.afterAnimate();
}, animation.duration);
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function () {
var chart = this.chart,
sharedClipKey = this.sharedClipKey,
group = this.group;
if (group && this.options.clip !== false) {
group.clip(chart.clipRect);
this.markerGroup.clip(); // no clip
}
// Remove the shared clipping rectancgle when all series are shown
setTimeout(function () {
if (sharedClipKey && chart[sharedClipKey]) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}, 100);
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
plotX,
plotY,
i,
point,
radius,
symbol,
isImage,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
pointMarkerOptions,
enabled,
isInside,
markerGroup = series.markerGroup;
if (seriesMarkerOptions.enabled || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotX = mathFloor(point.plotX); // #1843
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858
// only draw the point if y is defined
if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
radius = pointAttr.r;
symbol = pick(pointMarkerOptions.symbol, series.symbol);
isImage = symbol.indexOf('url') === 0;
if (graphic) { // update
graphic
.attr({ // Since the marker group isn't clipped, each individual marker must be toggled
visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN
})
.animate(extend({
x: plotX - radius,
y: plotY - radius
}, graphic.symbolName ? { // don't apply to image symbols #507
width: 2 * radius,
height: 2 * radius
} : {}));
} else if (isInside && (radius > 0 || isImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr)
.add(markerGroup);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Convert state properties from API naming conventions to SVG attributes
*
* @param {Object} options API options object
* @param {Object} base1 SVG attribute object to inherit from
* @param {Object} base2 Second level SVG attribute object to inherit from
*/
convertAttribs: function (options, base1, base2, base3) {
var conversion = this.pointAttrToOptions,
attr,
option,
obj = {};
options = options || {};
base1 = base1 || {};
base2 = base2 || {};
base3 = base3 || {};
for (attr in conversion) {
option = conversion[attr];
obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
}
return obj;
},
/**
* Get the state attributes. Each series type has its own set of attributes
* that are allowed to change on a point's state change. Series wide attributes are stored for
* all series, and additionally point specific attributes are stored for all
* points with individual marker options. If such options are not defined for the point,
* a reference to the series wide attributes is stored in point.pointAttr.
*/
getAttribs: function () {
var series = this,
seriesOptions = series.options,
normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
stateOptions = normalOptions.states,
stateOptionsHover = stateOptions[HOVER_STATE],
pointStateOptionsHover,
seriesColor = series.color,
normalDefaults = {
stroke: seriesColor,
fill: seriesColor
},
points = series.points || [], // #927
i,
point,
seriesPointAttr = [],
pointAttr,
pointAttrToOptions = series.pointAttrToOptions,
hasPointSpecificOptions,
negativeColor = seriesOptions.negativeColor,
defaultLineColor = normalOptions.lineColor,
key;
// series type specific modifications
if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
// if no hover radius is given, default to normal radius + 2
stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
} else { // column, bar, pie
// if no hover color is given, brighten the normal color
stateOptionsHover.color = stateOptionsHover.color ||
Color(stateOptionsHover.color || seriesColor)
.brighten(stateOptionsHover.brightness).get();
}
// general point attributes for the series normal state
seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
// HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
each([HOVER_STATE, SELECT_STATE], function (state) {
seriesPointAttr[state] =
series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
});
// set it
series.pointAttr = seriesPointAttr;
// Generate the point-specific attribute collections if specific point
// options are given. If not, create a referance to the series wide point
// attributes
i = points.length;
while (i--) {
point = points[i];
normalOptions = (point.options && point.options.marker) || point.options;
if (normalOptions && normalOptions.enabled === false) {
normalOptions.radius = 0;
}
if (point.negative && negativeColor) {
point.color = point.fillColor = negativeColor;
}
hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
// check if the point has specific visual options
if (point.options) {
for (key in pointAttrToOptions) {
if (defined(normalOptions[pointAttrToOptions[key]])) {
hasPointSpecificOptions = true;
}
}
}
// a specific marker config object is defined for the individual point:
// create it's own attribute collection
if (hasPointSpecificOptions) {
normalOptions = normalOptions || {};
pointAttr = [];
stateOptions = normalOptions.states || {}; // reassign for individual point
pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
// Handle colors for column and pies
if (!seriesOptions.marker) { // column, bar, point
// if no hover color is given, brighten the normal color
pointStateOptionsHover.color =
Color(pointStateOptionsHover.color || point.color)
.brighten(pointStateOptionsHover.brightness ||
stateOptionsHover.brightness).get();
}
// normal point state inherits series wide normal state
pointAttr[NORMAL_STATE] = series.convertAttribs(extend({
color: point.color, // #868
fillColor: point.color, // Individual point color or negative color markers (#2219)
lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white
}, normalOptions), seriesPointAttr[NORMAL_STATE]);
// inherit from point normal and series hover
pointAttr[HOVER_STATE] = series.convertAttribs(
stateOptions[HOVER_STATE],
seriesPointAttr[HOVER_STATE],
pointAttr[NORMAL_STATE]
);
// inherit from point normal and series hover
pointAttr[SELECT_STATE] = series.convertAttribs(
stateOptions[SELECT_STATE],
seriesPointAttr[SELECT_STATE],
pointAttr[NORMAL_STATE]
);
// no marker config object is created: copy a reference to the series-wide
// attribute collection
} else {
pointAttr = seriesPointAttr;
}
point.pointAttr = pointAttr;
}
},
/**
* Update the series with a new set of options
*/
update: function (newOptions, redraw) {
var chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
n;
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and reinsert methods from the type prototype
this.remove(false);
for (n in proto) { // Overwrite series-type specific methods (#2270)
if (proto.hasOwnProperty(n)) {
this[n] = UNDEFINED;
}
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
this.init(chart, newOptions);
if (pick(redraw, true)) {
chart.redraw(false);
}
},
/**
* Clear DOM objects and free up memory
*/
destroy: function () {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(['xAxis', 'yAxis'], function (AXIS) {
axis = series[AXIS];
if (axis) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
axis.stacks = {}; // Rebuild stacks when updating (#2229)
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// destroy all SVGElements associated to the series
each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
if (series[prop]) {
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
});
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Draw the data labels
*/
drawDataLabels: function () {
var series = this,
seriesOptions = series.options,
cursor = seriesOptions.cursor,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
str,
dataLabelsGroup;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
series.visible ? VISIBLE : HIDDEN,
options.zIndex || 6
);
// Make the labels for each point
generalOptions = options;
each(points, function (point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true;
// Determine if each data label is enabled
pointOptions = point.options && point.options.dataLabels;
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// Determine the color
options.style.color = pick(options.color, options.style.color, series.color, 'black');
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
fill: options.backgroundColor,
stroke: options.borderColor,
'stroke-width': options.borderWidth,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === UNDEFINED) {
delete attr[name];
}
}
dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0,
-999,
null,
null,
null,
options.useHTML
)
.attr(attr)
.css(extend(options.style, cursor && { cursor: cursor }))
.add(dataLabelsGroup)
.shadow(options.shadow);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
},
/**
* Align each individual data label
*/
alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -999),
plotY = pick(point.plotY, -999),
bBox = dataLabel.getBBox(),
visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted),
alignAttr; // the final position;
if (visible) {
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (options.rotation) { // Fancy box alignment isn't supported for rotated text
alignAttr = {
align: options.align,
x: alignTo.x + options.x + alignTo.width / 2,
y: alignTo.y + options.y + alignTo.height / 2
};
dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
// Handle justify or crop
if (pick(options.overflow, 'justify') === 'justify') {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
} else if (pick(options.crop, true)) {
// Now check that the data label is within the plot area
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
}
}
// Show or hide based on the final aligned position
if (!visible) {
dataLabel.attr({ y: -999 });
}
},
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified;
// Off left
off = alignAttr.x;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
},
/**
* Return the graph path of a segment
*/
getSegmentPath: function (segment) {
var series = this,
segmentPath = [],
step = series.options.step;
// build the segment line
each(segment, function (point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint;
if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
} else {
// moveTo or lineTo
segmentPath.push(i ? L : M);
// step line?
if (step && i) {
lastPoint = segment[i - 1];
if (step === 'right') {
segmentPath.push(
lastPoint.plotX,
plotY
);
} else if (step === 'center') {
segmentPath.push(
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
(lastPoint.plotX + plotX) / 2,
plotY
);
} else {
segmentPath.push(
plotX,
lastPoint.plotY
);
}
}
// normal line to next point
segmentPath.push(
point.plotX,
point.plotY
);
}
});
return segmentPath;
},
/**
* Get the graph path
*/
getGraphPath: function () {
var series = this,
graphPath = [],
segmentPath,
singlePoints = []; // used in drawTracker
// Divide into segments and build graph and area paths
each(series.segments, function (segment) {
segmentPath = series.getSegmentPath(segment);
// add the segment to the graph, or a single point for tracking
if (segment.length > 1) {
graphPath = graphPath.concat(segmentPath);
} else {
singlePoints.push(segment[0]);
}
});
// Record it for use in drawGraph and drawTracker, and return graphPath
series.singlePoints = singlePoints;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function () {
var series = this,
options = this.options,
props = [['graph', options.lineColor || this.color]],
lineWidth = options.lineWidth,
dashStyle = options.dashStyle,
roundCap = options.linecap !== 'square',
graphPath = this.getGraphPath(),
negativeColor = options.negativeColor;
if (negativeColor) {
props.push(['graphNeg', negativeColor]);
}
// draw the graph
each(props, function (prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
stop(graph); // cancel running animations, #459
graph.animate({ d: graphPath });
} else if (lineWidth && graphPath.length) { // #1487
attribs = {
stroke: prop[1],
'stroke-width': lineWidth,
zIndex: 1 // #1069
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
} else if (roundCap) {
attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
}
series[graphKey] = series.chart.renderer.path(graphPath)
.attr(attribs)
.add(series.group)
.shadow(!i && options.shadow);
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
clipNeg: function () {
var options = this.options,
chart = this.chart,
renderer = chart.renderer,
negativeColor = options.negativeColor || options.negativeFillColor,
translatedThreshold,
posAttr,
negAttr,
graph = this.graph,
area = this.area,
posClip = this.posClip,
negClip = this.negClip,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartSizeMax = mathMax(chartWidth, chartHeight),
yAxis = this.yAxis,
above,
below;
if (negativeColor && (graph || area)) {
translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true));
above = {
x: 0,
y: 0,
width: chartSizeMax,
height: translatedThreshold
};
below = {
x: 0,
y: translatedThreshold,
width: chartSizeMax,
height: chartSizeMax
};
if (chart.inverted) {
above.height = below.y = chart.plotWidth - translatedThreshold;
if (renderer.isVML) {
above = {
x: chart.plotWidth - translatedThreshold - chart.plotLeft,
y: 0,
width: chartWidth,
height: chartHeight
};
below = {
x: translatedThreshold + chart.plotLeft - chartWidth,
y: 0,
width: chart.plotLeft + translatedThreshold,
height: chartWidth
};
}
}
if (yAxis.reversed) {
posAttr = below;
negAttr = above;
} else {
posAttr = above;
negAttr = below;
}
if (posClip) { // update
posClip.animate(posAttr);
negClip.animate(negAttr);
} else {
this.posClip = posClip = renderer.clipRect(posAttr);
this.negClip = negClip = renderer.clipRect(negAttr);
if (graph && this.graphNeg) {
graph.clip(posClip);
this.graphNeg.clip(negClip);
}
if (area) {
area.clip(posClip);
this.areaNeg.clip(negClip);
}
}
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function () {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function (groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert();
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function () {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function (prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
visibility: visibility,
zIndex: zIndex || 0.1 // IE8 needs this
})
.add(parent);
}
// Place it on first and subsequent (redraw) calls
group[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function () {
return {
translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft,
translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function () {
var series = this,
chart = series.chart,
group,
options = series.options,
animation = options.animation,
doAnimation = animation && !!series.animate &&
chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
visibility = series.visible ? VISIBLE : HIDDEN,
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (doAnimation) {
series.animate(true);
}
// cache attributes for shapes
series.getAttribs();
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? chart.inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.clipNeg();
}
// draw the data labels (inn pies they go before the points)
series.drawDataLabels();
// draw the points
series.drawPoints();
// draw the mouse tracking area
if (series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
if (chart.inverted) {
series.invertGroups();
}
// Initial clipping, must be defined after inverting groups for VML
if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
group.clip(chart.clipRect);
}
// Run the animation
if (doAnimation) {
series.animate();
} else if (!hasRendered) {
series.afterAnimate();
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function () {
var series = this,
chart = series.chart,
wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.setTooltipPoints(true);
series.render();
if (wasDirtyData) {
fireEvent(series, 'updatedData');
}
},
/**
* Set the state of the graph
*/
setState: function (state) {
var series = this,
options = series.options,
graph = series.graph,
graphNeg = series.graphNeg,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs;
state = state || NORMAL_STATE;
if (series.state !== state) {
series.state = state;
if (stateOptions[state] && stateOptions[state].enabled === false) {
return;
}
if (state) {
lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
}
if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
attribs = {
'stroke-width': lineWidth
};
// use attr because animate will cause any other animation on the graph to stop
graph.attr(attribs);
if (graphNeg) {
graphNeg.attr(attribs);
}
}
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
* the visibility is toggled.
*/
setVisible: function (vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function (otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function () {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function () {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* UNDEFINED, the selection state is toggled.
*/
select: function (selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTracker: function () {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
cursor = options.cursor,
css = cursor && { cursor: cursor },
singlePoints = series.singlePoints,
singlePoint,
i,
onMouseOver = function () {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
};
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === M) { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
}
if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}
// draw the tracker
if (tracker) {
tracker.attr({ d: trackerPath });
} else { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? VISIBLE : HIDDEN,
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : NONE,
'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function (tracker) {
tracker.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
}; // end Series prototype
/**
* LineSeries object
*/
var LineSeries = extendClass(Series);
seriesTypes.line = LineSeries;
/**
* Set the default options for area
*/
defaultPlotOptions.area = merge(defaultSeriesOptions, {
threshold: 0
// trackByArea: false,
// lineColor: null, // overrides color, but lets fillColor be unaltered
// fillOpacity: 0.75,
// fillColor: null
});
/**
* AreaSeries object
*/
var AreaSeries = extendClass(Series, {
type: 'area',
/**
* For stacks, don't split segments on null values. Instead, draw null values with
* no marker. Also insert dummy points for any X position that exists in other series
* in the stack.
*/
getSegments: function () {
var segments = [],
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
plotX,
plotY,
points = this.points,
connectNulls = this.options.connectNulls,
val,
i,
x;
if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
// Create a map where we can quickly look up the points by their X value.
for (i = 0; i < points.length; i++) {
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
for (x in stack) {
if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
keys.push(+x);
}
}
keys.sort(function (a, b) {
return a - b;
});
each(keys, function (x) {
if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
return;
// The point exists, push it to the segment
} else if (pointMap[x]) {
segment.push(pointMap[x]);
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
plotX = xAxis.translate(x);
val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991
plotY = yAxis.toPixels(val, true);
segment.push({
y: null,
plotX: plotX,
clientX: plotX,
plotY: plotY,
yBottom: plotY,
onMouseOver: noop
});
}
});
if (segment.length) {
segments.push(segment);
}
} else {
Series.prototype.getSegments.call(this);
segments = this.segments;
}
this.segments = segments;
},
/**
* Extend the base Series getSegmentPath method by adding the path for the area.
* This path is pushed to the series.areaPath property.
*/
getSegmentPath: function (segment) {
var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
i,
options = this.options,
segLength = segmentPath.length,
translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
yBottom;
if (segLength === 3) { // for animation from 1 to two points
areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
}
if (options.stacking && !this.closedStacks) {
// Follow stack back. Todo: implement areaspline. A general solution could be to
// reverse the entire graphPath of the previous series, though may be hard with
// splines and with series with different extremes
for (i = segment.length - 1; i >= 0; i--) {
yBottom = pick(segment[i].yBottom, translatedThreshold);
// step line?
if (i < segment.length - 1 && options.step) {
areaSegmentPath.push(segment[i + 1].plotX, yBottom);
}
areaSegmentPath.push(segment[i].plotX, yBottom);
}
} else { // follow zero line back
this.closeSegment(areaSegmentPath, segment, translatedThreshold);
}
this.areaPath = this.areaPath.concat(areaSegmentPath);
return segmentPath;
},
/**
* Extendable method to close the segment path of an area. This is overridden in polar
* charts.
*/
closeSegment: function (path, segment, translatedThreshold) {
path.push(
L,
segment[segment.length - 1].plotX,
translatedThreshold,
L,
segment[0].plotX,
translatedThreshold
);
},
/**
* Draw the graph and the underlying area. This method calls the Series base
* function and adds the area. The areaPath is calculated in the getSegmentPath
* method called from Series.prototype.drawGraph.
*/
drawGraph: function () {
// Define or reset areaPath
this.areaPath = [];
// Call the base method
Series.prototype.drawGraph.apply(this);
// Define local variables
var series = this,
areaPath = this.areaPath,
options = this.options,
negativeColor = options.negativeColor,
negativeFillColor = options.negativeFillColor,
props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
if (negativeColor || negativeFillColor) {
props.push(['areaNeg', negativeColor, negativeFillColor]);
}
each(props, function (prop) {
var areaKey = prop[0],
area = series[areaKey];
// Create or update the area
if (area) { // update
area.animate({ d: areaPath });
} else { // create
series[areaKey] = series.chart.renderer.path(areaPath)
.attr({
fill: pick(
prop[2],
Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
),
zIndex: 0 // #1069
}).add(series.group);
}
});
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function (legend, item) {
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
legend.options.symbolWidth,
12,
2
).attr({
zIndex: 3
}).add(item.legendGroup);
}
});
seriesTypes.area = AreaSeries;/**
* Set the default options for spline
*/
defaultPlotOptions.spline = merge(defaultSeriesOptions);
/**
* SplineSeries object
*/
var SplineSeries = extendClass(Series, {
type: 'spline',
/**
* Get the spline segment from a given point's previous neighbour to the given point
*/
getPointSpline: function (segment, point, i) {
var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
denom = smoothing + 1,
plotX = point.plotX,
plotY = point.plotY,
lastPoint = segment[i - 1],
nextPoint = segment[i + 1],
leftContX,
leftContY,
rightContX,
rightContY,
ret;
// find control points
if (lastPoint && nextPoint) {
var lastX = lastPoint.plotX,
lastY = lastPoint.plotY,
nextX = nextPoint.plotX,
nextY = nextPoint.plotY,
correction;
leftContX = (smoothing * plotX + lastX) / denom;
leftContY = (smoothing * plotY + lastY) / denom;
rightContX = (smoothing * plotX + nextX) / denom;
rightContY = (smoothing * plotY + nextY) / denom;
// have the two control points make a straight line through main point
correction = ((rightContY - leftContY) * (rightContX - plotX)) /
(rightContX - leftContX) + plotY - rightContY;
leftContY += correction;
rightContY += correction;
// to prevent false extremes, check that control points are between
// neighbouring points' y values
if (leftContY > lastY && leftContY > plotY) {
leftContY = mathMax(lastY, plotY);
rightContY = 2 * plotY - leftContY; // mirror of left control point
} else if (leftContY < lastY && leftContY < plotY) {
leftContY = mathMin(lastY, plotY);
rightContY = 2 * plotY - leftContY;
}
if (rightContY > nextY && rightContY > plotY) {
rightContY = mathMax(nextY, plotY);
leftContY = 2 * plotY - rightContY;
} else if (rightContY < nextY && rightContY < plotY) {
rightContY = mathMin(nextY, plotY);
leftContY = 2 * plotY - rightContY;
}
// record for drawing in next point
point.rightContX = rightContX;
point.rightContY = rightContY;
}
// Visualize control points for debugging
/*
if (leftContX) {
this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
.attr({
stroke: 'red',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'red',
'stroke-width': 1
})
.add();
this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
.attr({
stroke: 'green',
'stroke-width': 1,
fill: 'none'
})
.add();
this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
.attr({
stroke: 'green',
'stroke-width': 1
})
.add();
}
*/
// moveTo or lineTo
if (!i) {
ret = [M, plotX, plotY];
} else { // curve from last point to this
ret = [
'C',
lastPoint.rightContX || lastPoint.plotX,
lastPoint.rightContY || lastPoint.plotY,
leftContX || plotX,
leftContY || plotY,
plotX,
plotY
];
lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
}
return ret;
}
});
seriesTypes.spline = SplineSeries;
/**
* Set the default options for areaspline
*/
defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
/**
* AreaSplineSeries object
*/
var areaProto = AreaSeries.prototype,
AreaSplineSeries = extendClass(SplineSeries, {
type: 'areaspline',
closedStacks: true, // instead of following the previous graph back, follow the threshold back
// Mix in methods from the area series
getSegmentPath: areaProto.getSegmentPath,
closeSegment: areaProto.closeSegment,
drawGraph: areaProto.drawGraph,
drawLegendSymbol: areaProto.drawLegendSymbol
});
seriesTypes.areaspline = AreaSplineSeries;
/**
* Set the default options for column
*/
defaultPlotOptions.column = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
brightness: 0.1,
shadow: false
},
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
stickyTracking: false,
threshold: 0
});
/**
* ColumnSeries object
*/
var ColumnSeries = extendClass(Series, {
type: 'column',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color',
r: 'borderRadius'
},
cropShoulder: 0,
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function () {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function () {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnIndex,
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function (otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === UNDEFINED) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = mathMin(
mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1),
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
optionPointWidth = options.pointWidth,
pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
pointOffsetWidth * options.pointPadding,
pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
colIndex = (reversedXAxis ?
columnCount - (series.columnIndex || 0) : // #1251
series.columnIndex) || 0,
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
return (series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
});
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function () {
var series = this,
chart = series.chart,
options = series.options,
borderWidth = options.borderWidth,
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1;
if (chart.renderer.isVML && chart.inverted) {
yCrisp += 1;
}
Series.prototype.translate.apply(series);
// record the new values
each(series.points, function (point) {
var yBottom = pick(point.yBottom, translatedThreshold),
plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = mathMin(plotY, yBottom),
right,
bottom,
fromTop,
fromLeft,
barH = mathMax(plotY, yBottom) - barY;
// Handle options.minPointLength
if (mathAbs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
barY =
mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Round off to obtain crisp edges
fromLeft = mathAbs(barX) < 0.5;
right = mathRound(barX + barW) + xCrisp;
barX = mathRound(barX) + xCrisp;
barW = right - barX;
fromTop = mathAbs(barY) < 0.5;
bottom = mathRound(barY + barH) + yCrisp;
barY = mathRound(barY) + yCrisp;
barH = bottom - barY;
// Top and left edges are exceptions
if (fromLeft) {
barX += 1;
barW -= 1;
}
if (fromTop) {
barY -= 1;
barH += 1;
}
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = {
x: barX,
y: barY,
width: barW,
height: barH
};
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
/**
* Columns have no graph
*/
drawGraph: noop,
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function () {
var series = this,
options = series.options,
renderer = series.chart.renderer,
shapeArgs;
// draw the columns
each(series.points, function (point) {
var plotY = point.plotY,
graphic = point.graphic;
if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
if (graphic) { // update
stop(graphic);
graphic.animate(merge(shapeArgs));
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE])
.add(series.group)
.shadow(options.shadow, null, options.stacking && !options.borderRadius);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
drawTracker: function () {
var series = this,
chart = series.chart,
pointer = chart.pointer,
cursor = series.options.cursor,
css = cursor && { cursor: cursor },
onMouseOver = function (e) {
var target = e.target,
point;
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function (point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function (key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (inverted) {
alignTo = {
x: chart.plotWidth - alignTo.y - alignTo.height,
y: chart.plotHeight - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align,
!inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function (init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (hasSVG) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr.scaleY = 1;
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, series.options.animation);
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function () {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
seriesTypes.column = ColumnSeries;
/**
* Set the default options for bar
*/
defaultPlotOptions.bar = merge(defaultPlotOptions.column);
/**
* The Bar series class
*/
var BarSeries = extendClass(ColumnSeries, {
type: 'bar',
inverted: true
});
seriesTypes.bar = BarSeries;
/**
* Set the default options for scatter
*/
defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
lineWidth: 0,
tooltip: {
headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>',
followPointer: true
},
stickyTracking: false
});
/**
* The scatter series class
*/
var ScatterSeries = extendClass(Series, {
type: 'scatter',
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['markerGroup'],
takeOrdinalPosition: false, // #2342
drawTracker: ColumnSeries.prototype.drawTracker,
setTooltipPoints: noop
});
seriesTypes.scatter = ScatterSeries;
/**
* Set the default options for pie
*/
defaultPlotOptions.pie = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
borderWidth: 1,
center: [null, null],
clip: false,
colorByPoint: true, // always true for pies
dataLabels: {
// align: null,
// connectorWidth: 1,
// connectorColor: point.color,
// connectorPadding: 5,
distance: 30,
enabled: true,
formatter: function () {
return this.point.name;
}
// softConnector: true,
//y: 0
},
ignoreHiddenPoint: true,
//innerSize: 0,
legendType: 'point',
marker: null, // point options are specified in the base options
size: null,
showInLegend: false,
slicedOffset: 10,
states: {
hover: {
brightness: 0.1,
shadow: false
}
},
stickyTracking: false,
tooltip: {
followPointer: true
}
});
/**
* Extended point object for pies
*/
var PiePoint = extendClass(Point, {
/**
* Initiate the pie slice
*/
init: function () {
Point.prototype.init.apply(this, arguments);
var point = this,
toggleSlice;
// Disallow negative values (#1530)
if (point.y < 0) {
point.y = null;
}
//visible: options.visible !== false,
extend(point, {
visible: point.visible !== false,
name: pick(point.name, 'Slice')
});
// add event listener for select
toggleSlice = function (e) {
point.slice(e.type === 'select');
};
addEvent(point, 'select', toggleSlice);
addEvent(point, 'unselect', toggleSlice);
return point;
},
/**
* Toggle the visibility of the pie slice
* @param {Boolean} vis Whether to show the slice or not. If undefined, the
* visibility is toggled
*/
setVisible: function (vis) {
var point = this,
series = point.series,
chart = series.chart,
method;
// if called without an argument, toggle visibility
point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
if (point[key]) {
point[key][method]();
}
});
if (point.legendItem) {
chart.legend.colorizeItem(point, vis);
}
// Handle ignore hidden slices
if (!series.isDirty && series.options.ignoreHiddenPoint) {
series.isDirty = true;
chart.redraw();
}
},
/**
* Set or toggle whether the slice is cut out from the pie
* @param {Boolean} sliced When undefined, the slice state is toggled
* @param {Boolean} redraw Whether to redraw the chart. True by default.
*/
slice: function (sliced, redraw, animation) {
var point = this,
series = point.series,
chart = series.chart,
translation;
setAnimation(animation, chart);
// redraw is true by default
redraw = pick(redraw, true);
// if called without an argument, toggle
point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
translation = sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
point.graphic.animate(translation);
if (point.shadowGroup) {
point.shadowGroup.animate(translation);
}
}
});
/**
* The Pie series class
*/
var PieSeries = {
type: 'pie',
isCartesian: false,
pointClass: PiePoint,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'dataLabelsGroup'],
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color'
},
/**
* Pies have one color each point
*/
getColor: noop,
/**
* Animate the pies in
*/
animate: function (init) {
var series = this,
points = series.points,
startAngleRad = series.startAngleRad;
if (!init) {
each(points, function (point) {
var graphic = point.graphic,
args = point.shapeArgs;
if (graphic) {
// start values
graphic.attr({
r: series.center[3] / 2, // animate from inner radius (#779)
start: startAngleRad,
end: startAngleRad
});
// animate
graphic.animate({
r: args.r,
start: args.start,
end: args.end
}, series.options.animation);
}
});
// delete this function to allow it only once
series.animate = null;
}
},
/**
* Extend the basic setData method by running processData and generatePoints immediately,
* in order to access the points from the legend.
*/
setData: function (data, redraw) {
Series.prototype.setData.call(this, data, false);
this.processData();
this.generatePoints();
if (pick(redraw, true)) {
this.chart.redraw();
}
},
/**
* Extend the generatePoints method by adding total and percentage properties to each point
*/
generatePoints: function () {
var i,
total = 0,
points,
len,
point,
ignoreHiddenPoint = this.options.ignoreHiddenPoint;
Series.prototype.generatePoints.call(this);
// Populate local vars
points = this.points;
len = points.length;
// Get the total sum
for (i = 0; i < len; i++) {
point = points[i];
total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
}
this.total = total;
// Set each point's properties
for (i = 0; i < len; i++) {
point = points[i];
point.percentage = total > 0 ? (point.y / total) * 100 : 0;
point.total = total;
}
},
/**
* Get the center of the pie based on the size and center options relative to the
* plot area. Borrowed by the polar and gauge series types.
*/
getCenter: function () {
var options = this.options,
chart = this.chart,
slicingRoom = 2 * (options.slicedOffset || 0),
handleSlicingRoom,
plotWidth = chart.plotWidth - 2 * slicingRoom,
plotHeight = chart.plotHeight - 2 * slicingRoom,
centerOption = options.center,
positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
smallestSize = mathMin(plotWidth, plotHeight),
isPercent;
return map(positions, function (length, i) {
isPercent = /%$/.test(length);
handleSlicingRoom = i < 2 || (i === 2 && isPercent);
return (isPercent ?
// i == 0: centerX, relative to width
// i == 1: centerY, relative to height
// i == 2: size, relative to smallestSize
// i == 4: innerSize, relative to smallestSize
[plotWidth, plotHeight, smallestSize, smallestSize][i] *
pInt(length) / 100 :
length) + (handleSlicingRoom ? slicingRoom : 0);
});
},
/**
* Do translation for pie slices
*/
translate: function (positions) {
this.generatePoints();
var series = this,
cumulative = 0,
precision = 1000, // issue #172
options = series.options,
slicedOffset = options.slicedOffset,
connectorOffset = slicedOffset + options.borderWidth,
start,
end,
angle,
startAngle = options.startAngle || 0,
startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90),
circ = endAngleRad - startAngleRad, //2 * mathPI,
points = series.points,
radiusX, // the x component of the radius vector for a given point
radiusY,
labelDistance = options.dataLabels.distance,
ignoreHiddenPoint = options.ignoreHiddenPoint,
i,
len = points.length,
point;
// Get positions - either an integer or a percentage string must be given.
// If positions are passed as a parameter, we're in a recursive loop for adjusting
// space for data labels.
if (!positions) {
series.center = positions = series.getCenter();
}
// utility for getting the x value from a given y, used for anticollision logic in data labels
series.getX = function (y, left) {
angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance));
return positions[0] +
(left ? -1 : 1) *
(mathCos(angle) * (positions[2] / 2 + labelDistance));
};
// Calculate the geometry for each point
for (i = 0; i < len; i++) {
point = points[i];
// set start and end angle
start = startAngleRad + (cumulative * circ);
if (!ignoreHiddenPoint || point.visible) {
cumulative += point.percentage / 100;
}
end = startAngleRad + (cumulative * circ);
// set the shape
point.shapeType = 'arc';
point.shapeArgs = {
x: positions[0],
y: positions[1],
r: positions[2] / 2,
innerR: positions[3] / 2,
start: mathRound(start * precision) / precision,
end: mathRound(end * precision) / precision
};
// center for the sliced out slice
angle = (end + start) / 2;
if (angle > 0.75 * circ) {
angle -= 2 * mathPI;
}
point.slicedTranslation = {
translateX: mathRound(mathCos(angle) * slicedOffset),
translateY: mathRound(mathSin(angle) * slicedOffset)
};
// set the anchor point for tooltips
radiusX = mathCos(angle) * positions[2] / 2;
radiusY = mathSin(angle) * positions[2] / 2;
point.tooltipPos = [
positions[0] + radiusX * 0.7,
positions[1] + radiusY * 0.7
];
point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
point.angle = angle;
// set the anchor point for data labels
connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
point.labelPos = [
positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
positions[0] + radiusX, // landing point for connector
positions[1] + radiusY, // a/a
labelDistance < 0 ? // alignment
'center' :
point.half ? 'right' : 'left', // alignment
angle // center angle
];
}
},
setTooltipPoints: noop,
drawGraph: null,
/**
* Draw the data points
*/
drawPoints: function () {
var series = this,
chart = series.chart,
renderer = chart.renderer,
groupTranslation,
//center,
graphic,
//group,
shadow = series.options.shadow,
shadowGroup,
shapeArgs;
if (shadow && !series.shadowGroup) {
series.shadowGroup = renderer.g('shadow')
.add(series.group);
}
// draw the slices
each(series.points, function (point) {
graphic = point.graphic;
shapeArgs = point.shapeArgs;
shadowGroup = point.shadowGroup;
// put the shadow behind all points
if (shadow && !shadowGroup) {
shadowGroup = point.shadowGroup = renderer.g('shadow')
.add(series.shadowGroup);
}
// if the point is sliced, use special translation, else use plot area traslation
groupTranslation = point.sliced ? point.slicedTranslation : {
translateX: 0,
translateY: 0
};
//group.translate(groupTranslation[0], groupTranslation[1]);
if (shadowGroup) {
shadowGroup.attr(groupTranslation);
}
// draw the slice
if (graphic) {
graphic.animate(extend(shapeArgs, groupTranslation));
} else {
point.graphic = graphic = renderer.arc(shapeArgs)
.setRadialReference(series.center)
.attr(
point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
)
.attr({ 'stroke-linejoin': 'round' })
.attr(groupTranslation)
.add(series.group)
.shadow(shadow, shadowGroup);
}
// detect point specific visibility
if (point.visible === false) {
point.setVisible(false);
}
});
},
/**
* Utility for sorting data labels
*/
sortByAngle: function (points, sign) {
points.sort(function (a, b) {
return a.angle !== undefined && (b.angle - a.angle) * sign;
});
},
/**
* Override the base drawDataLabels method by pie specific functionality
*/
drawDataLabels: function () {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
connectorPath,
softConnector = pick(options.softConnector, true),
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [// divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
rankArr,
i,
j,
overflow = [0, 0, 0, 0], // top, right, bottom, left
sort = function (a, b) {
return b.y - a.y;
};
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
// arrange points for detection collision
each(data, function (point) {
if (point.dataLabel) { // it may have been cancelled in the base method (#407)
halves[point.half].push(point);
}
});
// assume equal label heights
i = 0;
while (!labelHeight && data[i]) { // #1569
labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
i++;
}
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
i = 2;
while (i--) {
var slots = [],
slotsLength,
usedSlots = [],
points = halves[i],
pos,
length = points.length,
slotIndex;
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
// build the slots
for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
slots.push(pos);
// visualize the slot
/*
var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
slotY = pos + chart.plotTop;
if (!isNaN(slotX)) {
chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
.attr({
'stroke-width': 1,
stroke: 'silver'
})
.add();
chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
.attr({
fill: 'silver'
}).add();
}
*/
}
slotsLength = slots.length;
// if there are more values than available slots, remove lowest values
if (length > slotsLength) {
// create an array for sorting and ranking the points within each quarter
rankArr = [].concat(points);
rankArr.sort(sort);
j = length;
while (j--) {
rankArr[j].rank = j;
}
j = length;
while (j--) {
if (points[j].rank >= slotsLength) {
points.splice(j, 1);
}
}
length = points.length;
}
// The label goes to the nearest open slot, but not closer to the edge than
// the label's index.
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
var closest = 9999,
distance,
slotI;
// find the closest slot index
for (slotI = 0; slotI < slotsLength; slotI++) {
distance = mathAbs(slots[slotI] - labelPos[1]);
if (distance < closest) {
closest = distance;
slotIndex = slotI;
}
}
// if that slot index is closer to the edges of the slots, move it
// to the closest appropriate slot
if (slotIndex < j && slots[j] !== null) { // cluster at the top
slotIndex = j;
} else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
slotIndex = slotsLength - length + j;
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
} else {
// Slot is taken, find next free slot below. In the next run, the next slice will find the
// slot above these, because it is the closest one
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
}
usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
slots[slotIndex] = null; // mark as taken
}
// sort them in order to fill in from the top
usedSlots.sort(sort);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
var slot, naturalY;
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? HIDDEN : VISIBLE;
naturalY = labelPos[1];
if (distanceOption > 0) {
slot = usedSlots.pop();
slotIndex = slot.i;
// if the slot next to currrent slot is free, the y value is allowed
// to fall back to the natural position
y = slot.y;
if ((naturalY > y && slots[slotIndex + 1] !== null) ||
(naturalY < y && slots[slotIndex - 1] !== null)) {
y = naturalY;
}
} else {
y = naturalY;
}
// get the x - use the natural x position for first and last slot, to prevent the top
// and botton slice connectors from touching each other on either side
x = options.justify ?
seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
dataLabel.connX = x;
dataLabel.connY = y;
// Detect overflowing data labels
if (this.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
} // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function (point) {
connector = point.connector;
labelPos = point.labelPos;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos) {
visibility = dataLabel._attr.visibility;
x = dataLabel.connX;
y = dataLabel.connY;
connectorPath = softConnector ? [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
] : [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
L,
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
];
if (connector) {
connector.animate({ d: connectorPath });
connector.attr('visibility', visibility);
} else {
point.connector = connector = series.chart.renderer.path(connectorPath).attr({
'stroke-width': connectorWidth,
stroke: options.connectorColor || point.color || '#606060',
visibility: visibility
})
.add(series.group);
}
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
},
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
verifyDataLabelOverflow: function (overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = mathMax(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = mathMax(
mathMin(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
this.translate(center);
each(this.points, function (point) {
if (point.dataLabel) {
point.dataLabel._pos = null; // reset
}
});
this.drawDataLabels();
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
},
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
placeDataLabels: function () {
each(this.points, function (point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({ y: -999 });
}
}
});
},
alignDataLabel: noop,
/**
* Draw point specific tracker objects. Inherit directly from column series.
*/
drawTracker: ColumnSeries.prototype.drawTracker,
/**
* Use a simple symbol from column prototype
*/
drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
/**
* Pies don't have point marker symbols
*/
getSymbol: noop
};
PieSeries = extendClass(Series, PieSeries);
seriesTypes.pie = PieSeries;
// global variables
extend(Highcharts, {
// Constructors
Axis: Axis,
Chart: Chart,
Color: Color,
Legend: Legend,
Pointer: Pointer,
Point: Point,
Tick: Tick,
Tooltip: Tooltip,
Renderer: Renderer,
Series: Series,
SVGElement: SVGElement,
SVGRenderer: SVGRenderer,
// Various
arrayMin: arrayMin,
arrayMax: arrayMax,
charts: charts,
dateFormat: dateFormat,
format: format,
pathAnim: pathAnim,
getOptions: getOptions,
hasBidiBug: hasBidiBug,
isTouchDevice: isTouchDevice,
numberFormat: numberFormat,
seriesTypes: seriesTypes,
setOptions: setOptions,
addEvent: addEvent,
removeEvent: removeEvent,
createElement: createElement,
discardElement: discardElement,
css: css,
each: each,
extend: extend,
map: map,
merge: merge,
pick: pick,
splat: splat,
extendClass: extendClass,
pInt: pInt,
wrap: wrap,
svg: hasSVG,
canvas: useCanVG,
vml: !hasSVG && !useCanVG,
product: PRODUCT,
version: VERSION
});
}());
|
src/svg-icons/image/view-comfy.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageViewComfy = (props) => (
<SvgIcon {...props}>
<path d="M3 9h4V5H3v4zm0 5h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zM8 9h4V5H8v4zm5-4v4h4V5h-4zm5 9h4v-4h-4v4zM3 19h4v-4H3v4zm5 0h4v-4H8v4zm5 0h4v-4h-4v4zm5 0h4v-4h-4v4zm0-14v4h4V5h-4z"/>
</SvgIcon>
);
ImageViewComfy = pure(ImageViewComfy);
ImageViewComfy.displayName = 'ImageViewComfy';
ImageViewComfy.muiName = 'SvgIcon';
export default ImageViewComfy;
|
packages/reactor-kitchensink/src/examples/Tabs/BottomTabs/BottomTabs.js | markbrocato/extjs-reactor | import React from 'react';
import { TabPanel, Container } from '@extjs/ext-react';
export default function BottomTabsExample() {
return (
<TabPanel
shadow
tabBar={{ docked: 'bottom' }}
defaults={{
cls: "card",
layout: "center"
}}
>
<Container title="Info" iconCls="x-fa fa-info-circle">
<div>Docking tabs to the bottom will automatically change their style.</div>
</Container>
<Container title="Download" iconCls="x-fa fa-download" badgeText="4">
<div>Badges <em>(like the 4, below)</em> can be added by setting the <code>badgeText</code> prop.</div>
</Container>
<Container title="Favorites" iconCls="x-fa fa-star" badgeText="Overflow Test">
<div>Badge labels will truncate if the text is wider than the tab.</div>
</Container>
<Container title="Bookmarks" iconCls="x-fa fa-bookmark">
<div>Tabbars are <code>ui:"dark"</code> by default, but also have light variants.</div>
</Container>
<Container title="More" iconCls="x-fa fa-ellipsis-h">
<span className="action">User tapped User</span>
</Container>
</TabPanel>
)
}
|
information/blendle-frontend-react-source/app/components/login/ResetPassword/index.js | BramscoChill/BlendleParser | import React from 'react';
import PropTypes from 'prop-types';
import BackboneView from 'components/shared/BackboneView';
import Link from 'components/Link';
import { translate } from 'instances/i18n';
import ResetTokenForm from 'views/forms/resettoken';
class ResetPassword extends React.Component {
static propTypes = {
active: PropTypes.bool,
showBack: PropTypes.bool,
onLoginLink: PropTypes.func,
};
static defaultProps() {
return {
active: true,
};
}
componentWillMount() {
this._resetTokenForm = new ResetTokenForm();
this._resetTokenForm.render();
this._resetTokenForm.setDisabled(!this.props.active);
}
componentWillReceiveProps(nextProps) {
if (nextProps.active && !this.props.active) {
this._autofocusTimeout = setTimeout(() => this._resetTokenForm.focus(), 200);
}
}
componentWillUpdate(nextProps) {
this._resetTokenForm.setDisabled(!nextProps.active);
}
componentWillUnmount() {
clearTimeout(this._autofocusTimeout);
}
_renderBack() {
if (this.props.showBack) {
return (
<Link className="lnk-toggle-pane lnk-login" onClick={this.props.onLoginLink}>
{translate('login.dropdown.to_login')}
</Link>
);
}
return null;
}
render() {
return (
<div className="v-reset-password">
<BackboneView view={this._resetTokenForm} />
{this._renderBack()}
</div>
);
}
}
export default ResetPassword;
// WEBPACK FOOTER //
// ./src/js/app/components/login/ResetPassword/index.js |
test/test_helper.js | carlos-agu/BlogPosts | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
client-angular-1.x/node_modules/babel-plugin-transform-react-jsx/lib/index.js | skeiter9/webpack-boilerplate-sk9 | "use strict";
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
exports.__esModule = true;
exports["default"] = function (_ref2) {
var t = _ref2.types;
var JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/;
var visitor = require("babel-helper-builder-react-jsx")({
pre: function pre(state) {
var tagName = state.tagName;
var args = state.args;
if (t.react.isCompatTag(tagName)) {
args.push(t.stringLiteral(tagName));
} else {
args.push(state.tagExpr);
}
},
post: function post(state, pass) {
state.callee = pass.get("jsxIdentifier");
}
});
visitor.Program = function (path, state) {
var file = state.file;
var id = state.opts.pragma || "React.createElement";
for (var _iterator = (file.ast.comments /*: Array<Object>*/), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var comment = _ref;
var matches = JSX_ANNOTATION_REGEX.exec(comment.value);
if (matches) {
id = matches[1];
if (id === "React.DOM") {
throw file.buildCodeFrameError(comment, "The @jsx React.DOM pragma has been deprecated as of React 0.12");
} else {
break;
}
}
}
state.set("jsxIdentifier", id.split(".").map(function (name) {
return t.identifier(name);
}).reduce(function (object, property) {
return t.memberExpression(object, property);
}));
};
return {
inherits: require("babel-plugin-syntax-jsx"),
visitor: visitor
};
};
module.exports = exports["default"]; |
session2/src/src/index.js | AlexQianjin/reactlearning | import React from 'react'
import { render } from 'react-dom'
import Menu from './components/Menu'
import data from './data/recipes'
window.React = React
render(
<Menu recipes={data} />,
document.getElementById("app")
) |
src/App.js | domoticz/Reacticz | import React, { Component } from 'react';
import {Responsive, WidthProvider} from 'react-grid-layout';
import AboutView from './AboutView';
import ConfigStorageHelper from './util/ConfigStorageHelper';
import DeviceListView from './DeviceListView';
import DeviceWidget from './widgets/DeviceWidget';
import JSONClientSingleton from './util/JSONClientSingleton';
import LZString from 'lz-string';
import LoadingWidget from './widgets/LoadingWidget';
import LocalStorage from './util/LocalStorage';
import MqttClientSingleton from './util/MqttClientSingleton';
import SceneWidget from './widgets/SceneWidget';
import Screensaver from './Screensaver';
import SettingsView from './SettingsView';
import Themes from './Themes';
import './App.css';
import '../node_modules/react-grid-layout/css/styles.css';
import '../node_modules/react-resizable/css/styles.css';
const ResponsiveGridLayout = WidthProvider(Responsive);
const MAX_SCREENSAVER_DELAY_SEC = 3600;
const DELAY_OFF_VALUE = -1;
const View = {
DASHBOARD: 1,
DEVICE_LIST: 2,
SERVER_SETTINGS: 3,
ABOUT: 4
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
menuOpen: false,
currentView: View.DASHBOARD,
layoutLocked: true,
serverConfig: {
mqttBrokerUrl: '',
mqttLogin: '',
mqttPassword: '',
domoticzUrl: '',
domoticzLogin: '',
domoticzPassword: ''
},
serverStatus: {
mqtt: false,
domoticz: false,
},
lastMqttMessage: null,
configId: 0,
configName: '',
multiConfig: false,
devices: {},
deviceSpecs: {},
layout: [],
whitelist: [],
zoom: 1,
screensaverConfig: {
delay: -1,
type: "blank"
},
themeId: 'Default',
theme: {}
};
this.json = new JSONClientSingleton();
this.json.setEventHandler(this.domoticzEventHandler);
this.mqtt = new MqttClientSingleton();
this.mqtt.setEventHandler(this.mqttEventHandler);
this.store = new LocalStorage();
this.configHelper = new ConfigStorageHelper();
}
componentWillMount() {
const storedServerConfig = this.store.read('serverConfig');
const themeId = this.store.read('themeId') || this.state.themeId;
const zoom = this.store.read('zoom') || this.state.zoom;
const screensaverConfig = this.store.read('screensaverConfig') || this.state.screensaverConfig;
const configId = this.readConfigIdFromUrlParam();
const configs = this.configHelper.getConfigs();
const config = this.configHelper.getConfig(configId) || {};
const configName = config.name || 'Dashboard';
this.setState({
whitelist: config.whitelist || [],
layout: config.layout || [],
configId: configId,
configName: configName,
multiConfig: configs.length > 1,
zoom: zoom,
screensaverConfig: screensaverConfig,
themeId: themeId,
theme: Themes[themeId] || {}
});
if (storedServerConfig) {
this.setState({serverConfig: storedServerConfig});
}
this.setState({ multiConfig: this.configHelper.getConfigs().length > 1});
window.onpopstate = this.handlePopstate;
this.updateDocumentTitle(configName);
}
componentDidMount() {
this.connectClients(this.state.serverConfig);
this.readSharedConfigFromUrl();
if (this.hasWhitelistedScenes()) {
this.requestScenesStatus();
}
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: setInterval(this.timer, 5000)});
}
componentWillUnmount() {
this.json.setEventHandler(() => {});
this.mqtt.setEventHandler(() => {});
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
}
timer=()=>{
this.state.whitelist.forEach(device => this.requestDeviceStatus(device));
}
handlePopstate = (event) => {
if (event.state && event.state.id !== undefined) {
this.loadConfig(event.state.id, true /* opt_noHistoryPush */ );
}
}
connectClients(config) {
this.mqtt.connect(config.mqttBrokerUrl, config.mqttLogin, config.mqttPassword);
this.json.setServerUrl(config.domoticzUrl, config.domoticzLogin, config.domoticzPassword);
}
mqttEventHandler = (eventType, opt_data = null) => {
switch (eventType) {
case 'connected':
this.setState({serverStatus:
Object.assign(this.state.serverStatus, {mqtt: !!opt_data})});
if (opt_data === true) {
for (let i = 0; i < this.state.whitelist.length; i++) {
this.requestDeviceStatus(this.state.whitelist[i]);
}
}
break;
case 'error':
// nothing to do here for now.
break;
case 'message':
if (this.state.whitelist.indexOf('d|' + opt_data.idx) >= 0) {
const devices = Object.assign({}, this.state.devices);
devices['d|' + opt_data.idx] = opt_data;
this.setState({devices: devices});
// Update scene status (with a little debounce check).
if (this.hasWhitelistedScenes()) {
this.requestScenesStatus(true /* opt_throttle */);
}
}
this.render();
break;
default:
console.log('unknown event type from MqttClientSingleton', eventType);
break;
}
}
domoticzEventHandler = (eventType, opt_data = null) => {
switch (eventType) {
case 'connected':
this.setState({serverStatus:
Object.assign(this.state.serverStatus, {domoticz: !!opt_data})});
break;
default:
console.log('unknown event type from JSONClientSingleton', eventType);
break;
}
}
updateDocumentTitle = (configName) => {
if (document) {
document.title = configName ? configName + ' | Reacticz' : 'Reacticz';
}
}
readConfigIdFromUrlParam() {
const param = Number(document.location.search.slice(1));
if (param >= 0 && Math.round(param) === param) {
if (this.configHelper.getConfig(param)) {
return param;
}
return 0;
}
return 0;
}
getPrevConfig = () => {
this.getNewConfig(true /* opt_prev */);
}
getNextConfig = () => {
this.getNewConfig();
}
getNewConfig = (opt_prev = false) => {
const newId = this.configHelper.getNextId(this.state.configId, opt_prev);
this.loadConfig(newId);
}
loadConfig(id, opt_noHistoryPush = false) {
const config = this.configHelper.getConfig(id);
if (!config) {
console.log('Unable to load config with id ' + id);
return;
}
this.setState({
configId: id,
configName: config.name,
layout: config.layout,
whitelist: config.whitelist
});
!opt_noHistoryPush && window.history.pushState({id: id}, '', '?' + id);
this.setState({
multiConfig: this.configHelper.getConfigs().length > 1,
layoutLocked: true
});
this.updateDocumentTitle(config.name);
for (let i = 0; i < config.whitelist.length; i++) {
this.requestDeviceStatus(config.whitelist[i]);
}
}
deleteCurrentConfig = () => {
if (!window.confirm('Delete this dashboard ?')) {
return;
}
this.configHelper.deleteConfig(this.state.configId);
const nextConfigId =
this.configHelper.getConfigs().length >= this.state.configId + 1 ?
this.state.configId : 0;
this.loadConfig(nextConfigId);
}
readSharedConfigFromUrl = (opt_param) => {
const param = opt_param || document.location.hash.slice(1);
if (!param) {
return;
}
if (window.confirm(
'Reacticz configuration parameters detected! Apply here?\n' +
'\nNote: if a dashboard configuration is found in the parameters and ' +
'your already have one setup here, a new separate dashboard will be ' +
'created.')) {
try {
const config =
JSON.parse(LZString.decompressFromEncodedURIComponent(param));
config.s && this.handleServerConfigChange(config.s);
config.t && this.handleThemeChange(config.t);
if (config.w) {
// Importing dashboard config.
if (this.state.whitelist.length > 0) {
console.log('adding config');
// Don't override the current dahboard.
this.loadConfig(this.configHelper.addConfig({
name: config.n || 'Imported dashboard',
layout: config.l || [],
whitelist: config.w || []
}));
return;
}
this.handleConfigNameChange(config.n || 'Imported dashboard');
this.handleDeviceListChange(config.w || []);
this.storeConfigChange({layout: config.l || []});
this.setState({layout: config.l || []});
}
} catch (e) {
console.log(e);
alert('Sorry, something went wrong. The configuration could not be read.');
}
}
document.location.hash = '';
}
importConfigPrompt = () => {
const url = prompt('Please paste the full configuration URL to import.\n\n'
+ 'This URL can be found in the About page of a configured Reacticz '
+ 'dashboard.');
if (url && url.split('#').length === 2) {
this.readSharedConfigFromUrl(url.split('#')[1]);
}
}
handleServerConfigChange = (config) => {
this.setState({serverConfig: config});
this.store.write('serverConfig', config);
this.connectClients(config);
}
handleThemeChange = (themeId) => {
const theme = Themes[themeId];
if (theme) {
this.setState({themeId: themeId, theme: theme});
this.store.write('themeId', themeId);
}
}
handleZoomChange = (zoom) => {
this.setState({zoom: zoom});
this.store.write('zoom', zoom);
}
handleScreensaverConfigChange = (config = {}) => {
config.delay = config.delay !== DELAY_OFF_VALUE ? Math.abs(Math.min(config.delay, MAX_SCREENSAVER_DELAY_SEC)) : config.delay;
this.setState({
screensaverConfig: config
});
this.store.write('screensaverConfig', config);
}
handleConfigNameChange = (configName) => {
this.setState({configName: configName});
this.storeConfigChange({name: configName});
}
storeConfigChange = (partialConfigObject) => {
this.configHelper.storeConfigChange(
this.state.configId, partialConfigObject);
}
handleDeviceListChange = (list) => {
const devices = Object.assign({}, this.state.devices);
// Delete device info for devices that were removed from the whitelist.
for (let i = 0; i < this.state.whitelist.length; i++) {
const id = this.state.whitelist[i];
if (list.indexOf(id) < 0) {
delete devices[id];
}
}
this.setState({whitelist: list, devices: devices});
this.storeConfigChange({whitelist: list})
this.cleanupLayout(list);
for (let i = 0; i < list.length; i++) {
if (!devices[list[i]]) {
this.requestDeviceStatus(list[i]);
}
}
if (this.hasWhitelistedScenes(list)) {
this.requestScenesStatus();
}
}
removeDevice = (id) => {
if (window.confirm('Remove this widget ?')) {
const whitelist = this.state.whitelist.slice(0);
whitelist.splice(whitelist.indexOf(id), 1);
this.handleDeviceListChange(whitelist);
}
}
requestDeviceStatus = (id) => {
const explodedId = id.split('|');
if (explodedId[0] !== 'd') {
// Not a device type.
return;
}
const idx = parseInt(id.split('|')[1], 10);
this.mqtt.publish({'command': 'getdeviceinfo', 'idx': idx });
}
hasWhitelistedScenes(opt_list) {
const list = opt_list || this.state.whitelist;
return list.some((id) => (id[0] === 's' || id[0] === 'g'));
}
requestDeviceSpec = (id) => {
const explodedId = id.split('|');
if (explodedId[0] !== 'd') {
// Not a device type.
return;
}
this.json.get({type: 'devices', rid: explodedId[1] }, (data) =>{
const deviceSpecs = Object.assign({}, this.state.deviceSpecs);
deviceSpecs[id] = data.result[0];
this.setState({deviceSpecs: deviceSpecs});
});
}
requestScenesStatus = (opt_throttle = false) => {
const getScenes = opt_throttle ?
this.json.getAllScenesThrottled : this.json.getAllScenes;
getScenes((data) => {
if (data.status !== "OK") {
alert("Unable to get scenes status.");
return;
}
const scenes = data.result;
const devices = Object.assign({}, this.state.devices);
for (let i = 0; i < scenes.length; i++) {
const scene = scenes[i];
const fullId = (scene.Type === 'Group' ? 'g' : 's') + '|' + scene.idx;
if (this.state.whitelist.indexOf(fullId) >= 0) {
devices[fullId] = scene;
}
}
this.setState({devices: devices});
});
}
toggleMenu = () => {
this.setState({ 'menuOpen': !this.state.menuOpen });
}
toggleSettings = () => {
this.setState({
'currentView': View.SERVER_SETTINGS,
'layoutLocked': true });
}
toggleDeviceList = () => {
this.setState({
'currentView': View.DEVICE_LIST,
'layoutLocked': true });
}
toggleAbout = () => {
this.setState({
'currentView': View.ABOUT,
'layoutLocked': true });
}
toggleLayoutEdit = () => {
this.setState({ 'layoutLocked': !this.state.layoutLocked });
}
toMainView = () => {
this.setState({ 'currentView': View.DASHBOARD });
}
cleanupLayout(list) {
// Clear layout items for devices that are no longer present.
const ids = [];
let maxY = -1;
const updatedLayout = this.state.layout.filter(function(deviceLayout) {
ids.push(deviceLayout.i);
maxY = Math.max(deviceLayout.y, maxY);
return list.indexOf(deviceLayout.i) >= 0;
}, this);
// Add missing layouts
for (let i = 0; i < list.length; i++) {
const deviceId = list[i];
if (ids.indexOf(deviceId) < 0) {
updatedLayout.push({x: 0, y: ++maxY, w: 2, h: 1, i: deviceId})
}
};
this.setState({layout: updatedLayout});
this.storeConfigChange({layout: updatedLayout});
}
onLayoutChange = (layout) => {
this.setState({layout: layout});
this.storeConfigChange({'layout': layout});
}
renderCurrentView = (opt_forceView = null) => {
const view = opt_forceView || this.state.currentView;
switch (view) {
case View.ABOUT:
return (<AboutView appState={this.state} themes={Themes}
zoom={this.state.zoom}
screensaverConfig={this.state.screensaverConfig}
configName={this.state.configName}
onThemeChange={this.handleThemeChange}
onZoomChange={this.handleZoomChange}
onScreensaverConfigChange={this.handleScreensaverConfigChange}
multiConfig={this.state.multiConfig} />);
case View.SERVER_SETTINGS:
return (<SettingsView config={this.state.serverConfig}
serverStatus={this.state.serverStatus}
onChange={this.handleServerConfigChange}
importConfigPrompt={this.importConfigPrompt} />);
case View.DEVICE_LIST:
return (<DeviceListView onWhitelistChange={this.handleDeviceListChange}
idxWhitelist={this.state.whitelist} name={this.state.configName}
onNameChange={this.handleConfigNameChange} />);
default:
if (this.state.whitelist.length === 0) {
return (
<div className="addDevices">
{!this.state.multiConfig && <h2>Welcome to your Reacticz dashboard!</h2>}
{this.state.multiConfig && <h2>This is a new blank dashboard!</h2>}
{this.state.multiConfig && <p>Use the arrows (<svg className='icon'><use xlinkHref="#navigate-before" /></svg> and <svg className='icon'><use xlinkHref="#navigate-next" /></svg>) at the bottom to switch between your dashboards.</p>}
<p>This dashboard is currently empty. Open the menu at the top right (<svg className='icon'><use xlinkHref="#settings" /></svg>) and go to the devices list screen (<svg className='icon'><use xlinkHref="#playlist-add-check" /></svg>) to select the widgets you want to add.</p>
<p>Then come back here (<svg className='icon'><use xlinkHref="#home" /></svg>) and unlock the layout (<svg className='icon'><use xlinkHref="#lock" /></svg>) to drag and resize the widgets however you like.</p>
<p>That's it!</p>
</div>
);
}
const widgets = this.state.layout.map(function(deviceLayout) {
const deviceId = deviceLayout.i;
const device = this.state.devices[deviceId];
if (!device) {
// Device not available
return (<div key={deviceId} className="gridItem">
<LoadingWidget onRemove={() => this.removeDevice(deviceId)}
theme={this.state.theme}/></div>);
}
let widget = '';
if (device.Type === 'Group' || device.Type === 'Scene') {
widget = <SceneWidget
readOnly={!this.state.layoutLocked}
key={'item'+ deviceId}
scene={device}
onChange={this.requestScenesStatus}
theme={this.state.theme} />
} else {
widget = <DeviceWidget
className="widget"
layoutWidth={deviceLayout.w}
readOnly={!this.state.layoutLocked}
key={'item'+ deviceId}
device={device}
requestDeviceSpec={() => this.requestDeviceSpec(deviceId)}
deviceSpec={this.state.deviceSpecs[deviceId]}
theme={this.state.theme} />
}
return (
<div key={deviceId} className={this.state.layoutLocked ? 'gridItem':'gridItem resizeable'}>
{widget}
</div>
);
}, this);
const style = {
fontSize: (100 * this.state.zoom) + '%'
};
return (
<ResponsiveGridLayout
layouts={{lg:this.state.layout}}
onDragStop={this.onLayoutChange}
onResizeStop={this.onLayoutChange}
isDraggable={!this.state.layoutLocked}
isResizable={!this.state.layoutLocked}
compactType={null}
breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}}
cols={{lg: 12, md: 10, sm: 8, xs: 6, xxs: 4}}
className="layout"
style={style}
items={this.state.whitelist.length}
rowHeight={100}>
{widgets}
</ResponsiveGridLayout>);
}
}
renderFooter(showFooter) {
const footerStyle = {
background: this.state.theme.overlayBackground,
color: this.state.theme.overlayText,
fill: this.state.theme.menuIcon,
fontSize: (100 * this.state.zoom) + '%',
height:(50 * this.state.zoom) + 'px',
lineHeight: (50 * this.state.zoom) + 'px',
};
return (
<div className={'footer' + (showFooter ? '' : ' hidden')} style={footerStyle}>
<div className="left">
{this.state.layoutLocked && this.state.multiConfig &&
<button title="Previous Layout" onClick={this.getPrevConfig}>
<svg className="icon"><use xlinkHref="#navigate-before" /></svg>
</button>
}
{!this.state.layoutLocked && this.state.multiConfig &&
<button title="Delete" onClick={this.deleteCurrentConfig}>
<svg className="icon"><use xlinkHref="#delete" /></svg>
</button>
}
</div>
<div className="right">
{this.state.layoutLocked && this.state.multiConfig &&
<button title="Next Layout" onClick={this.getNextConfig}>
<svg className="icon"><use xlinkHref="#navigate-next" /></svg>
</button>
}
{!this.state.layoutLocked &&
<button title="Add a new dashboard" onClick={() => this.loadConfig(this.configHelper.addConfig())}>
<svg className="icon"><use xlinkHref="#add" /></svg>
</button>
}
</div>
<div className="title">{this.state.configName}</div>
</div>);
}
render() {
const shouldConfigure = !this.state.serverConfig.mqttBrokerUrl || !this.state.serverConfig.domoticzUrl;
const view = this.renderCurrentView(shouldConfigure ? View.SERVER_SETTINGS : undefined);
const currentView = this.state.currentView;
const menuIconStyle = {
fill: this.state.theme.menuIcon
};
const menuIconSelectedStyle = {
fill: this.state.theme.menuIconSelected
};
const appStyle = {
background: this.state.theme.appBackground,
color: this.state.theme.appText,
fill: this.state.theme.appText
};
const appBarStyle = {
background: this.state.menuOpen ? this.state.theme.overlayBackground : '',
display: shouldConfigure ? 'none' : ''
};
if (document) {
document.body.style.background = this.state.theme.appBackground;
}
const showFooter = (currentView === View.DASHBOARD || currentView === View.DEVICE_LIST) && (this.state.multiConfig || !this.state.layoutLocked);
return (
<div className="App" style={appStyle}>
<div key='menu' className={this.state.menuOpen ? 'appbar open' : 'appbar'} style={appBarStyle}>
<button key='toggle' title='Menu' onClick={this.toggleMenu}>
<svg className="icon" style={menuIconStyle}><use xlinkHref="#settings" /></svg>
</button>
{currentView !== View.DASHBOARD &&
<button onClick={this.toMainView} title='Home'>
<svg className='icon' style={menuIconStyle}><use xlinkHref="#home" /></svg></button>}
{currentView === View.DASHBOARD &&
<button onClick={this.toggleLayoutEdit} title='Layout lock'>
<svg className='icon' style={(currentView === View.DASHBOARD ? menuIconSelectedStyle : menuIconStyle)}><use xlinkHref={this.state.layoutLocked ? '#lock' : '#lock-open'} /></svg></button>}
<button onClick={this.toggleDeviceList} title='Device selection'>
<svg className='icon' style={(currentView === View.DEVICE_LIST ? menuIconSelectedStyle : menuIconStyle)}><use xlinkHref='#playlist-add-check' /></svg>
</button>
<button onClick={this.toggleSettings} title='Server settings'>
<svg className='icon' style={(currentView === View.SERVER_SETTINGS ? menuIconSelectedStyle : menuIconStyle)}><use xlinkHref='#router' /></svg>
</button>
<button onClick={this.toggleAbout} title='About'>
<svg className='icon' style={(currentView === View.ABOUT ? menuIconSelectedStyle : menuIconStyle)}><use xlinkHref='#info-outline' /></svg>
</button>
</div>
{view}
{this.renderFooter(showFooter)}
{this.state.screensaverConfig.delay >= 0 && <Screensaver type={this.state.screensaverConfig.type} delay={this.state.screensaverConfig.delay} theme={this.state.theme} />}
</div>
);
}
}
export default App;
|
src/pages/projects.js | stolinski/st2017 | import React from 'react';
import Layout from '../components/Layout';
import { Title, MainWrapper } from '../components/Headings';
import { ProjectsList } from '../components/ProjectsStyles';
const projects = [
{
title: 'Level Up Tutorials',
link: 'https://www.leveluptutorials.com/',
desc:
'2000+ Web Dev Tutorials on: <a target="_blank" href="https://www.youtube.com/channel/UCyU5wkjgQYGRB0hIHMwm2Sg">Youtube</a><br />Built With: Meteor, React, Stylus',
},
{
title: 'Syntax',
link: 'https://syntax.fm/',
desc: 'A popular web-dev podcast hosted by Wes Bos & Scott Tolinski',
},
{
title: 'Ford.com Global UX',
link: 'http://www.ford.com/',
desc:
'Design Prototypes and Interactive Digital Styleguide for the Ford.com Global Redesign:<br />Built With: Angular.js, Sass',
},
{
title: 'Q LTD',
link: 'http://qltd.com/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built With: Node.js, Express, MongoDB, Sass/Compass/Susy',
},
{
title: 'ACM SIGGRAPH',
link: 'http://www.siggraph.org/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built With: Drupal 7, Omega 3, Sass/Compass',
},
{
title: 'Concrete.org',
link: 'http://www.concrete.org/',
desc:
'Built for: <a target="_blank" href="http://qltd.com">Q LTD</a><br />Built Templates With: HTML5, CSS3, JavaScript',
},
];
export default class Projects extends React.Component {
render() {
return (
<Layout {...this.props}>
<MainWrapper color="#e74c3c">
<Title>Projects</Title>
<p>
I've worked on many types of projects both personal and professional. Here are some projects I've
developed/created.
</p>
<ProjectsList>
{projects.map(project => (
<li key={project.title}>
<h3 className="project-title">
<a target="_blank" rel="noopener noreferrer" href={project.link}>
{project.title}
</a>
</h3>
<p dangerouslySetInnerHTML={{ __html: project.desc }} />
</li>
))}
</ProjectsList>
</MainWrapper>
</Layout>
);
}
}
|
src/containers/pages/create-deck/after-class-selection/right-container/topbar-assets/import-deck.js | vFujin/HearthLounge | import React from 'react';
import PropTypes from 'prop-types';
import Button from '../../../../../../components/buttons/button';
const DeckstringInput = ({importedDeckstring, handleInputChange, handleDeckImport}) =>{
return (
<div className="deck-import">
<input id="deckstring-popover" placeholder="Paste deckstring here" type="text" value={importedDeckstring} onChange={handleInputChange}/>
<Button text="Import" type="import" id="deck-import" handleClick={handleDeckImport} />
</div>
)
};
DeckstringInput.propTypes = {
handleInputChange: PropTypes.func.isRequired,
handleDeckImport: PropTypes.func.isRequired,
importedDeckstring: PropTypes.string
};
DeckstringInput.defaultProps = {
importedDeckstring: ""
};
export default DeckstringInput; |
node_modules/react-icons/md/bluetooth-disabled.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const MdBluetoothDisabled = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.6 30.3l3.2-3.1-3.2-3.2v6.3z m-12.6-23.7l24.4 24.4-2.4 2.4-3.8-3.9-7.2 7.1h-1.6v-12.6l-7.7 7.6-2.3-2.3 9.3-9.3-11.1-11z m12.6 3.1v5.4l-3.2-3.4v-8.3h1.6l9.5 9.4-5 5.1-2.4-2.4 2.7-2.7z"/></g>
</Icon>
)
export default MdBluetoothDisabled
|
web/nodejs/react-router-bootstrap/tests/visual/ButtonVisual.js | woylaski/notebook | import React from 'react';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';
import Button from 'react-bootstrap/lib/Button';
import { Link } from 'react-router';
import LinkContainer from '../../src/LinkContainer';
export default () => (
<div>
<Link to="home">Back to Index</Link>
<h2>Button</h2>
<h3>Baseline</h3>
<ButtonToolbar>
<Button>Default</Button>
<Button bsStyle="success">Success</Button>
<Button bsStyle="info">Info</Button>
<Button bsStyle="warning">Warning</Button>
<Button bsStyle="danger">Danger</Button>
<Button bsStyle="link">Link</Button>
</ButtonToolbar>
<h3>LinkContainer</h3>
<ButtonToolbar>
<LinkContainer to="/home">
<Button>Default</Button>
</LinkContainer>
<LinkContainer to="/home">
<Button bsStyle="success">Success</Button>
</LinkContainer>
<LinkContainer to="/home">
<Button bsStyle="info">Info</Button>
</LinkContainer>
<LinkContainer to="/home">
<Button bsStyle="warning">Warning</Button>
</LinkContainer>
<LinkContainer to="/home">
<Button bsStyle="danger">Danger</Button>
</LinkContainer>
<LinkContainer to="/home">
<Button bsStyle="link">Link</Button>
</LinkContainer>
</ButtonToolbar>
</div>
);
|
node_modules/react-icons/ti/heart-half-outline.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const TiHeartHalfOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m3.7 15.7c0 2.1 0.3 5.5 3.3 8.5 2.7 2.6 11.5 8.6 11.8 9 0.4 0.1 0.7 0.3 1 0.3s0.7-0.2 1-0.3c0.4-0.4 9.2-6.2 11.9-9 3-3 3.3-6.4 3.3-8.5 0-5-4-9-9-9-2.7 0-5.3 1.5-7 3.8-1.7-2.3-4.3-3.8-7.3-3.8-4.9 0-9 4-9 9z m16.3 1.6c1 0 1.7-0.6 1.7-1.6 0-3.2 2.5-5.7 5.6-5.7s5.7 2.5 5.7 5.7c0 1.8-0.3 4-2.5 6.1-2 2-8.2 6.4-10.5 7.9v-12.4z"/></g>
</Icon>
)
export default TiHeartHalfOutline
|
vendor/bower/jquery/src/sizzle/test/jquery.js | pipop1150/choke | /*!
* jQuery JavaScript Library v1.9.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-2-4
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + 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 ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
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" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}
this.each(function() {
jQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
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.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
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 );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return jQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// 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 ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
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;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = 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 = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[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: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( 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)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem ) {
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 ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = jQuery.isFunction( value );
// 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 ( !isFunc && typeof value !== "string" ) {
value = jQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
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: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 ) {
isSuccess = true;
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
isSuccess = true;
statusText = "notmodified";
// If we have data, let's convert it
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
});
/* 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 firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv2, current, conv, tmp,
converters = {},
i = 0,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ];
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var value, name, index, easing, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/*jshint validthis:true */
var prop, index, length,
value, dataShow, toggle,
tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.cur && hooks.cur.finish ) {
hooks.cur.finish.call( this );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.documentElement;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// })();
// 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 ); |
CompositeUi/src/views/component/Advice.js | kreta/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <[email protected]>
* (c) Gorka Laucirica <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import './../../scss/components/_advice.scss';
import React from 'react';
const Advice = props =>
<p className="advice">
{props.children}
</p>;
export default Advice;
|
client/containers/Annotate.js | exacs/liqen-face | import React from 'react'
import { connect } from 'react-redux'
import zipWith from 'lodash/fp/zipWith'
import fetch from 'isomorphic-fetch'
import Article from '../components/annotator/article'
import MultiList from '../components/annotator-drawer/multi-list'
import LiqenCreator from '../components/annotator-drawer/liqen-creator'
import { createAnnotation, createLiqen } from '../actions/index'
const article = window.__ARTICLE__
export class Annotate extends React.Component {
constructor (props) {
super(props)
this.state = {
articleBody: {
name: 'div',
attrs: {},
children: []
}
}
}
componentDidMount () {
fetch(`/parseArticle?uri=${article.source.uri}`)
.then(response => response.json())
.then(obj => {
this.setState({articleBody: obj.body.object})
})
}
render () {
const {
question,
answer,
annotations,
liqens,
tags,
onCreateAnnotation,
onCreateLiqen
} = this.props
return (
<div className='row'>
<aside className='hidden-md-down col-lg-4 flex-last'>
<h3 className='h6 text-uppercase text-muted'>Create your Liqen (your Answer)</h3>
<LiqenCreator
question={question}
answer={answer}
onSubmit={onCreateLiqen}
/>
<MultiList
annotations={annotations}
liqens={liqens}
/>
</aside>
<div className='col-lg-8 col-xl-7'>
<header>
<h1 className="article-title">{article.title}</h1>
</header>
<main className='article-body'>
<Article
body={this.state.articleBody}
tags={tags}
onCreateAnnotation={onCreateAnnotation}
/>
</main>
</div>
</div>
)
}
}
const mapStateToAnswer = (state) => {
const questionAnswer = state.question.answer.map(
({tag, required}) => ({
tag: state.tags[tag].title,
required
})
)
const liqenAnswer = state.newLiqen.answer.map(
a => state.annotations[a] || null
)
const zipper = (qa, la) => ({
title: qa.tag,
exact: (la && la.target && la.target.exact) || ''
})
return zipWith(zipper, questionAnswer, liqenAnswer)
}
const mapStateToAnnotations = (state) => {
const ret = []
for (let ref in state.annotations) {
const {tag, checked, pending, target} = state.annotations[ref]
ret.push({
tag: state.tags[tag].title,
ref,
target,
checked,
pending
})
}
return ret
}
const mapStateToLiqens = (state) => {
const ret = []
for (let ref in state.liqens) {
const {answer, pending} = state.liqens[ref]
ret.push({
answer: answer
.map(a => {
if (!state.annotations[a]) {
return null
}
const {tag, target} = state.annotations[a]
return {
target,
ref: a,
tag: state.tags[tag]
}
})
.filter(a => a !== null),
ref,
pending
})
}
return ret
}
const mapStateToProps = (state) => ({
question: state.question.title,
answer: mapStateToAnswer(state),
annotations: mapStateToAnnotations(state),
liqens: mapStateToLiqens(state),
tags: state.question.answer.map(
({tag}) => ({ref: tag, title: state.tags[tag].title})
),
enableCreateLiqen: state.newLiqen.answer.every(
a => state.annotations[a] && !state.annotations[a].pending
)
})
const mapDispatchToProps = (dispatch) => ({
onCreateAnnotation: ({target, tag}) => dispatch(createAnnotation(target, tag)),
onCreateLiqen: () => dispatch(createLiqen())
})
const mergeProps = (stateProps, dispatchProps) =>
Object.assign({}, stateProps, dispatchProps, {
onCreateLiqen: stateProps.enableCreateLiqen && dispatchProps.onCreateLiqen
})
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(Annotate)
|
src/svg-icons/action/delete-forever.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDeleteForever = (props) => (
<SvgIcon {...props}>
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zm2.46-7.12l1.41-1.41L12 12.59l2.12-2.12 1.41 1.41L13.41 14l2.12 2.12-1.41 1.41L12 15.41l-2.12 2.12-1.41-1.41L10.59 14l-2.13-2.12zM15.5 4l-1-1h-5l-1 1H5v2h14V4z"/>
</SvgIcon>
);
ActionDeleteForever = pure(ActionDeleteForever);
ActionDeleteForever.displayName = 'ActionDeleteForever';
ActionDeleteForever.muiName = 'SvgIcon';
export default ActionDeleteForever;
|
contrib/hello-world-react/src/www/js/components/item-cart.js | intuit/wasabi | import React from 'react';
export const ItemCartComponent = props => <table style={{width: '500px'}}>
<thead><tr><th style={{width: '260px'}}>Name</th><th style={{width: '100px'}}>Price</th><th>Quantity</th><th> </th></tr></thead>
<tbody>
{ props.cart.map((nextProduct, index) => <tr key={index}>
<td className="storeProductName">{nextProduct.name}</td><td className="storePriceCell">${nextProduct.cost}</td><td style={{textAlign: 'center'}}>{nextProduct.quantity}</td><td className="buttonCell"><button onClick={() => props.removeFunc(nextProduct)}>Remove</button></td>
</tr>)}
</tbody>
</table>;
|
packages/wix-style-react/src/EmptyState/EmptyState.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import { classes, st } from './EmptyState.st.css';
import Heading from '../Heading';
import Text from '../Text';
import { FontUpgradeContext } from '../FontUpgrade/context';
/**
* Representing a state of an empty page, section, table, etc.
*/
const EmptyState = ({
theme,
title,
subtitle,
image,
classNames: classNamesProp,
children,
dataHook,
align,
}) => (
<div
className={st(classes.root, { theme, align })}
data-hook={dataHook}
data-theme={theme}
data-align={align}
>
<div className={classes.container}>
{image && (
<div
className={st(
classes.imageContainer,
{},
(classNamesProp && classNamesProp.imageContainer) || '',
)}
data-hook="empty-state-image-container"
>
{typeof image === 'string' ? (
<img
className={classes.imageElement}
src={image}
data-hook="image-element"
/>
) : (
React.cloneElement(image, {
'data-hook': 'image-node',
})
)}
</div>
)}
{title && (
<div
className={classes.titleContainer}
data-hook="empty-state-title-container"
>
{theme === 'section' ? (
<FontUpgradeContext.Consumer>
{({ active }) => (
<Text
weight={active ? 'bold' : 'normal'}
className={classes.sectionTitle}
>
{title}
</Text>
)}
</FontUpgradeContext.Consumer>
) : (
<Heading className={classes.title} appearance="H3">
{title}
</Heading>
)}
</div>
)}
{subtitle && (
<div
className={classes.subtitleContainer}
data-hook="empty-state-subtitle-container"
>
<Text className={classes.subtitle} secondary>
{subtitle}
</Text>
</div>
)}
{children && (
<div
className={classes.childrenContainer}
data-hook="empty-state-children-container"
>
{children}
</div>
)}
</div>
</div>
);
EmptyState.displayName = 'EmptyState';
EmptyState.propTypes = {
/** The theme of the EmptyState */
theme: PropTypes.oneOf(['page', 'page-no-border', 'section']),
/** Content for the title of the Empty State */
title: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
/** Content for the subtitle of the Empty State */
subtitle: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
/** The Empty State image, can be either a string representing the image URL, or a node to render instead */
image: PropTypes.node,
/** The Empty State image bottom margin. If not specified, use the default padding defined in the css */
classNames: PropTypes.shape({
imageContainer: PropTypes.string,
}),
/** Children to render below the subtitle, ideally an action of some type (Button or TextButton for instance) */
children: PropTypes.node,
dataHook: PropTypes.string,
align: PropTypes.oneOf(['start', 'center', 'end']),
};
EmptyState.defaultProps = {
theme: 'section',
image: null,
children: null,
align: 'center',
};
export default EmptyState;
|
ajax/libs/yui/3.11.0/scrollview-base/scrollview-base.js | panshuiqing/cdnjs | YUI.add('scrollview-base', function (Y, NAME) {
/**
* The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators
*
* @module scrollview
* @submodule scrollview-base
*/
// Local vars
var getClassName = Y.ClassNameManager.getClassName,
DOCUMENT = Y.config.doc,
IE = Y.UA.ie,
NATIVE_TRANSITIONS = Y.Transition.useNative,
vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated
SCROLLVIEW = 'scrollview',
CLASS_NAMES = {
vertical: getClassName(SCROLLVIEW, 'vert'),
horizontal: getClassName(SCROLLVIEW, 'horiz')
},
EV_SCROLL_END = 'scrollEnd',
FLICK = 'flick',
DRAG = 'drag',
MOUSEWHEEL = 'mousewheel',
UI = 'ui',
TOP = 'top',
LEFT = 'left',
PX = 'px',
AXIS = 'axis',
SCROLL_Y = 'scrollY',
SCROLL_X = 'scrollX',
BOUNCE = 'bounce',
DISABLED = 'disabled',
DECELERATION = 'deceleration',
DIM_X = 'x',
DIM_Y = 'y',
BOUNDING_BOX = 'boundingBox',
CONTENT_BOX = 'contentBox',
GESTURE_MOVE = 'gesturemove',
START = 'start',
END = 'end',
EMPTY = '',
ZERO = '0s',
SNAP_DURATION = 'snapDuration',
SNAP_EASING = 'snapEasing',
EASING = 'easing',
FRAME_DURATION = 'frameDuration',
BOUNCE_RANGE = 'bounceRange',
_constrain = function (val, min, max) {
return Math.min(Math.max(val, min), max);
};
/**
* ScrollView provides a scrollable widget, supporting flick gestures,
* across both touch and mouse based devices.
*
* @class ScrollView
* @param config {Object} Object literal with initial attribute values
* @extends Widget
* @constructor
*/
function ScrollView() {
ScrollView.superclass.constructor.apply(this, arguments);
}
Y.ScrollView = Y.extend(ScrollView, Y.Widget, {
// *** Y.ScrollView prototype
/**
* Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit.
* Used by the _transform method.
*
* @property _forceHWTransforms
* @type boolean
* @protected
*/
_forceHWTransforms: Y.UA.webkit ? true : false,
/**
* <p>Used to control whether or not ScrollView's internal
* gesturemovestart, gesturemove and gesturemoveend
* event listeners should preventDefault. The value is an
* object, with "start", "move" and "end" properties used to
* specify which events should preventDefault and which shouldn't:</p>
*
* <pre>
* {
* start: false,
* move: true,
* end: false
* }
* </pre>
*
* <p>The default values are set up in order to prevent panning,
* on touch devices, while allowing click listeners on elements inside
* the ScrollView to be notified as expected.</p>
*
* @property _prevent
* @type Object
* @protected
*/
_prevent: {
start: false,
move: true,
end: false
},
/**
* Contains the distance (postive or negative) in pixels by which
* the scrollview was last scrolled. This is useful when setting up
* click listeners on the scrollview content, which on mouse based
* devices are always fired, even after a drag/flick.
*
* <p>Touch based devices don't currently fire a click event,
* if the finger has been moved (beyond a threshold) so this
* check isn't required, if working in a purely touch based environment</p>
*
* @property lastScrolledAmt
* @type Number
* @public
* @default 0
*/
lastScrolledAmt: 0,
/**
* Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis
*
* @property _minScrollX
* @type number
* @protected
*/
_minScrollX: null,
/**
* Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis
*
* @property _maxScrollX
* @type number
* @protected
*/
_maxScrollX: null,
/**
* Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis
*
* @property _minScrollY
* @type number
* @protected
*/
_minScrollY: null,
/**
* Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis
*
* @property _maxScrollY
* @type number
* @protected
*/
_maxScrollY: null,
/**
* Designated initializer
*
* @method initializer
* @param {config} Configuration object for the plugin
*/
initializer: function () {
var sv = this;
// Cache these values, since they aren't going to change.
sv._bb = sv.get(BOUNDING_BOX);
sv._cb = sv.get(CONTENT_BOX);
// Cache some attributes
sv._cAxis = sv.get(AXIS);
sv._cBounce = sv.get(BOUNCE);
sv._cBounceRange = sv.get(BOUNCE_RANGE);
sv._cDeceleration = sv.get(DECELERATION);
sv._cFrameDuration = sv.get(FRAME_DURATION);
},
/**
* bindUI implementation
*
* Hooks up events for the widget
* @method bindUI
*/
bindUI: function () {
var sv = this;
// Bind interaction listers
sv._bindFlick(sv.get(FLICK));
sv._bindDrag(sv.get(DRAG));
sv._bindMousewheel(true);
// Bind change events
sv._bindAttrs();
// IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release.
if (IE) {
sv._fixIESelect(sv._bb, sv._cb);
}
// Set any deprecated static properties
if (ScrollView.SNAP_DURATION) {
sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);
}
if (ScrollView.SNAP_EASING) {
sv.set(SNAP_EASING, ScrollView.SNAP_EASING);
}
if (ScrollView.EASING) {
sv.set(EASING, ScrollView.EASING);
}
if (ScrollView.FRAME_STEP) {
sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);
}
if (ScrollView.BOUNCE_RANGE) {
sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);
}
// Recalculate dimension properties
// TODO: This should be throttled.
// Y.one(WINDOW).after('resize', sv._afterDimChange, sv);
},
/**
* Bind event listeners
*
* @method _bindAttrs
* @private
*/
_bindAttrs: function () {
var sv = this,
scrollChangeHandler = sv._afterScrollChange,
dimChangeHandler = sv._afterDimChange;
// Bind any change event listeners
sv.after({
'scrollEnd': sv._afterScrollEnd,
'disabledChange': sv._afterDisabledChange,
'flickChange': sv._afterFlickChange,
'dragChange': sv._afterDragChange,
'axisChange': sv._afterAxisChange,
'scrollYChange': scrollChangeHandler,
'scrollXChange': scrollChangeHandler,
'heightChange': dimChangeHandler,
'widthChange': dimChangeHandler
});
},
/**
* Bind (or unbind) gesture move listeners required for drag support
*
* @method _bindDrag
* @param drag {boolean} If true, the method binds listener to enable
* drag (gesturemovestart). If false, the method unbinds gesturemove
* listeners for drag support.
* @private
*/
_bindDrag: function (drag) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'drag' listeners
bb.detach(DRAG + '|*');
if (drag) {
bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));
}
},
/**
* Bind (or unbind) flick listeners.
*
* @method _bindFlick
* @param flick {Object|boolean} If truthy, the method binds listeners for
* flick support. If false, the method unbinds flick listeners.
* @private
*/
_bindFlick: function (flick) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'flick' listeners
bb.detach(FLICK + '|*');
if (flick) {
bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);
// Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick
sv._bindDrag(sv.get(DRAG));
}
},
/**
* Bind (or unbind) mousewheel listeners.
*
* @method _bindMousewheel
* @param mousewheel {Object|boolean} If truthy, the method binds listeners for
* mousewheel support. If false, the method unbinds mousewheel listeners.
* @private
*/
_bindMousewheel: function (mousewheel) {
var sv = this,
bb = sv._bb;
// Unbind any previous 'mousewheel' listeners
// TODO: This doesn't actually appear to work properly. Fix. #2532743
bb.detach(MOUSEWHEEL + '|*');
// Only enable for vertical scrollviews
if (mousewheel) {
// Bound to document, because that's where mousewheel events fire off of.
Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));
}
},
/**
* syncUI implementation.
*
* Update the scroll position, based on the current value of scrollX/scrollY.
*
* @method syncUI
*/
syncUI: function () {
var sv = this,
scrollDims = sv._getScrollDims(),
width = scrollDims.offsetWidth,
height = scrollDims.offsetHeight,
scrollWidth = scrollDims.scrollWidth,
scrollHeight = scrollDims.scrollHeight;
// If the axis is undefined, auto-calculate it
if (sv._cAxis === undefined) {
// This should only ever be run once (for now).
// In the future SV might post-load axis changes
sv._cAxis = {
x: (scrollWidth > width),
y: (scrollHeight > height)
};
sv._set(AXIS, sv._cAxis);
}
// get text direction on or inherited by scrollview node
sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');
// Cache the disabled value
sv._cDisabled = sv.get(DISABLED);
// Run this to set initial values
sv._uiDimensionsChange();
// If we're out-of-bounds, snap back.
if (sv._isOutOfBounds()) {
sv._snapBack();
}
},
/**
* Utility method to obtain widget dimensions
*
* @method _getScrollDims
* @return {Object} The offsetWidth, offsetHeight, scrollWidth and
* scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,
* scrollHeight]
* @private
*/
_getScrollDims: function () {
var sv = this,
cb = sv._cb,
bb = sv._bb,
TRANS = ScrollView._TRANSITION,
// Ideally using CSSMatrix - don't think we have it normalized yet though.
// origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e,
// origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f,
origX = sv.get(SCROLL_X),
origY = sv.get(SCROLL_Y),
origHWTransform,
dims;
// TODO: Is this OK? Just in case it's called 'during' a transition.
if (NATIVE_TRANSITIONS) {
cb.setStyle(TRANS.DURATION, ZERO);
cb.setStyle(TRANS.PROPERTY, EMPTY);
}
origHWTransform = sv._forceHWTransforms;
sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.
sv._moveTo(cb, 0, 0);
dims = {
'offsetWidth': bb.get('offsetWidth'),
'offsetHeight': bb.get('offsetHeight'),
'scrollWidth': bb.get('scrollWidth'),
'scrollHeight': bb.get('scrollHeight')
};
sv._moveTo(cb, -(origX), -(origY));
sv._forceHWTransforms = origHWTransform;
return dims;
},
/**
* This method gets invoked whenever the height or width attributes change,
* allowing us to determine which scrolling axes need to be enabled.
*
* @method _uiDimensionsChange
* @protected
*/
_uiDimensionsChange: function () {
var sv = this,
bb = sv._bb,
scrollDims = sv._getScrollDims(),
width = scrollDims.offsetWidth,
height = scrollDims.offsetHeight,
scrollWidth = scrollDims.scrollWidth,
scrollHeight = scrollDims.scrollHeight,
rtl = sv.rtl,
svAxis = sv._cAxis,
minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),
maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),
minScrollY = 0,
maxScrollY = Math.max(0, scrollHeight - height);
if (svAxis && svAxis.x) {
bb.addClass(CLASS_NAMES.horizontal);
}
if (svAxis && svAxis.y) {
bb.addClass(CLASS_NAMES.vertical);
}
sv._setBounds({
minScrollX: minScrollX,
maxScrollX: maxScrollX,
minScrollY: minScrollY,
maxScrollY: maxScrollY
});
},
/**
* Set the bounding dimensions of the ScrollView
*
* @method _setBounds
* @protected
* @param bounds {Object} [duration] ms of the scroll animation. (default is 0)
* @param {Number} [bounds.minScrollX] The minimum scroll X value
* @param {Number} [bounds.maxScrollX] The maximum scroll X value
* @param {Number} [bounds.minScrollY] The minimum scroll Y value
* @param {Number} [bounds.maxScrollY] The maximum scroll Y value
*/
_setBounds: function (bounds) {
var sv = this;
// TODO: Do a check to log if the bounds are invalid
sv._minScrollX = bounds.minScrollX;
sv._maxScrollX = bounds.maxScrollX;
sv._minScrollY = bounds.minScrollY;
sv._maxScrollY = bounds.maxScrollY;
},
/**
* Get the bounding dimensions of the ScrollView
*
* @method _getBounds
* @protected
*/
_getBounds: function () {
var sv = this;
return {
minScrollX: sv._minScrollX,
maxScrollX: sv._maxScrollX,
minScrollY: sv._minScrollY,
maxScrollY: sv._maxScrollY
};
},
/**
* Scroll the element to a given xy coordinate
*
* @method scrollTo
* @param x {Number} The x-position to scroll to. (null for no movement)
* @param y {Number} The y-position to scroll to. (null for no movement)
* @param {Number} [duration] ms of the scroll animation. (default is 0)
* @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)
* @param {String} [node] The node to transform. Setting this can be useful in
* dual-axis paginated instances. (default is the instance's contentBox)
*/
scrollTo: function (x, y, duration, easing, node) {
// Check to see if widget is disabled
if (this._cDisabled) {
return;
}
var sv = this,
cb = sv._cb,
TRANS = ScrollView._TRANSITION,
callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this
newX = 0,
newY = 0,
transition = {},
transform;
// default the optional arguments
duration = duration || 0;
easing = easing || sv.get(EASING); // @TODO: Cache this
node = node || cb;
if (x !== null) {
sv.set(SCROLL_X, x, {src:UI});
newX = -(x);
}
if (y !== null) {
sv.set(SCROLL_Y, y, {src:UI});
newY = -(y);
}
transform = sv._transform(newX, newY);
if (NATIVE_TRANSITIONS) {
// ANDROID WORKAROUND - try and stop existing transition, before kicking off new one.
node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);
}
// Move
if (duration === 0) {
if (NATIVE_TRANSITIONS) {
node.setStyle('transform', transform);
}
else {
// TODO: If both set, batch them in the same update
// Update: Nope, setStyles() just loops through each property and applies it.
if (x !== null) {
node.setStyle(LEFT, newX + PX);
}
if (y !== null) {
node.setStyle(TOP, newY + PX);
}
}
}
// Animate
else {
transition.easing = easing;
transition.duration = duration / 1000;
if (NATIVE_TRANSITIONS) {
transition.transform = transform;
}
else {
transition.left = newX + PX;
transition.top = newY + PX;
}
node.transition(transition, callback);
}
},
/**
* Utility method, to create the translate transform string with the
* x, y translation amounts provided.
*
* @method _transform
* @param {Number} x Number of pixels to translate along the x axis
* @param {Number} y Number of pixels to translate along the y axis
* @private
*/
_transform: function (x, y) {
// TODO: Would we be better off using a Matrix for this?
var prop = 'translate(' + x + 'px, ' + y + 'px)';
if (this._forceHWTransforms) {
prop += ' translateZ(0)';
}
return prop;
},
/**
* Utility method, to move the given element to the given xy position
*
* @method _moveTo
* @param node {Node} The node to move
* @param x {Number} The x-position to move to
* @param y {Number} The y-position to move to
* @private
*/
_moveTo : function(node, x, y) {
if (NATIVE_TRANSITIONS) {
node.setStyle('transform', this._transform(x, y));
} else {
node.setStyle(LEFT, x + PX);
node.setStyle(TOP, y + PX);
}
},
/**
* Content box transition callback
*
* @method _onTransEnd
* @param {Event.Facade} e The event facade
* @private
*/
_onTransEnd: function () {
var sv = this;
// If for some reason we're OOB, snapback
if (sv._isOutOfBounds()) {
sv._snapBack();
}
else {
/**
* Notification event fired at the end of a scroll transition
*
* @event scrollEnd
* @param e {EventFacade} The default event facade.
*/
sv.fire(EV_SCROLL_END);
}
},
/**
* gesturemovestart event handler
*
* @method _onGestureMoveStart
* @param e {Event.Facade} The gesturemovestart event facade
* @private
*/
_onGestureMoveStart: function (e) {
if (this._cDisabled) {
return false;
}
var sv = this,
bb = sv._bb,
currentX = sv.get(SCROLL_X),
currentY = sv.get(SCROLL_Y),
clientX = e.clientX,
clientY = e.clientY;
if (sv._prevent.start) {
e.preventDefault();
}
// if a flick animation is in progress, cancel it
if (sv._flickAnim) {
sv._cancelFlick();
sv._onTransEnd();
}
// Reset lastScrolledAmt
sv.lastScrolledAmt = 0;
// Stores data for this gesture cycle. Cleaned up later
sv._gesture = {
// Will hold the axis value
axis: null,
// The current attribute values
startX: currentX,
startY: currentY,
// The X/Y coordinates where the event began
startClientX: clientX,
startClientY: clientY,
// The X/Y coordinates where the event will end
endClientX: null,
endClientY: null,
// The current delta of the event
deltaX: null,
deltaY: null,
// Will be populated for flicks
flick: null,
// Create some listeners for the rest of the gesture cycle
onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),
// @TODO: Don't bind gestureMoveEnd if it's a Flick?
onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))
};
},
/**
* gesturemove event handler
*
* @method _onGestureMove
* @param e {Event.Facade} The gesturemove event facade
* @private
*/
_onGestureMove: function (e) {
var sv = this,
gesture = sv._gesture,
svAxis = sv._cAxis,
svAxisX = svAxis.x,
svAxisY = svAxis.y,
startX = gesture.startX,
startY = gesture.startY,
startClientX = gesture.startClientX,
startClientY = gesture.startClientY,
clientX = e.clientX,
clientY = e.clientY;
if (sv._prevent.move) {
e.preventDefault();
}
gesture.deltaX = startClientX - clientX;
gesture.deltaY = startClientY - clientY;
// Determine if this is a vertical or horizontal movement
// @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent
if (gesture.axis === null) {
gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;
}
// Move X or Y. @TODO: Move both if dualaxis.
if (gesture.axis === DIM_X && svAxisX) {
sv.set(SCROLL_X, startX + gesture.deltaX);
}
else if (gesture.axis === DIM_Y && svAxisY) {
sv.set(SCROLL_Y, startY + gesture.deltaY);
}
},
/**
* gesturemoveend event handler
*
* @method _onGestureMoveEnd
* @param e {Event.Facade} The gesturemoveend event facade
* @private
*/
_onGestureMoveEnd: function (e) {
var sv = this,
gesture = sv._gesture,
flick = gesture.flick,
clientX = e.clientX,
clientY = e.clientY,
isOOB;
if (sv._prevent.end) {
e.preventDefault();
}
// Store the end X/Y coordinates
gesture.endClientX = clientX;
gesture.endClientY = clientY;
// Cleanup the event handlers
gesture.onGestureMove.detach();
gesture.onGestureMoveEnd.detach();
// If this wasn't a flick, wrap up the gesture cycle
if (!flick) {
// @TODO: Be more intelligent about this. Look at the Flick attribute to see
// if it is safe to assume _flick did or didn't fire.
// Then, the order _flick and _onGestureMoveEnd fire doesn't matter?
// If there was movement (_onGestureMove fired)
if (gesture.deltaX !== null && gesture.deltaY !== null) {
isOOB = sv._isOutOfBounds();
// If we're out-out-bounds, then snapback
if (isOOB) {
sv._snapBack();
}
// Inbounds
else {
// Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's
// Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit
if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {
sv._onTransEnd();
}
}
}
}
},
/**
* Execute a flick at the end of a scroll action
*
* @method _flick
* @param e {Event.Facade} The Flick event facade
* @private
*/
_flick: function (e) {
if (this._cDisabled) {
return false;
}
var sv = this,
svAxis = sv._cAxis,
flick = e.flick,
flickAxis = flick.axis,
flickVelocity = flick.velocity,
axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,
startPosition = sv.get(axisAttr);
// Sometimes flick is enabled, but drag is disabled
if (sv._gesture) {
sv._gesture.flick = flick;
}
// Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis
if (svAxis[flickAxis]) {
sv._flickFrame(flickVelocity, flickAxis, startPosition);
}
},
/**
* Execute a single frame in the flick animation
*
* @method _flickFrame
* @param velocity {Number} The velocity of this animated frame
* @param flickAxis {String} The axis on which to animate
* @param startPosition {Number} The starting X/Y point to flick from
* @protected
*/
_flickFrame: function (velocity, flickAxis, startPosition) {
var sv = this,
axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,
bounds = sv._getBounds(),
// Localize cached values
bounce = sv._cBounce,
bounceRange = sv._cBounceRange,
deceleration = sv._cDeceleration,
frameDuration = sv._cFrameDuration,
// Calculate
newVelocity = velocity * deceleration,
newPosition = startPosition - (frameDuration * newVelocity),
// Some convinience conditions
min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,
max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,
belowMin = (newPosition < min),
belowMax = (newPosition < max),
aboveMin = (newPosition > min),
aboveMax = (newPosition > max),
belowMinRange = (newPosition < (min - bounceRange)),
withinMinRange = (belowMin && (newPosition > (min - bounceRange))),
withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),
aboveMaxRange = (newPosition > (max + bounceRange)),
tooSlow;
// If we're within the range but outside min/max, dampen the velocity
if (withinMinRange || withinMaxRange) {
newVelocity *= bounce;
}
// Is the velocity too slow to bother?
tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);
// If the velocity is too slow or we're outside the range
if (tooSlow || belowMinRange || aboveMaxRange) {
// Cancel and delete sv._flickAnim
if (sv._flickAnim) {
sv._cancelFlick();
}
// If we're inside the scroll area, just end
if (aboveMin && belowMax) {
sv._onTransEnd();
}
// We're outside the scroll area, so we need to snap back
else {
sv._snapBack();
}
}
// Otherwise, animate to the next frame
else {
// @TODO: maybe use requestAnimationFrame instead
sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);
sv.set(axisAttr, newPosition);
}
},
_cancelFlick: function () {
var sv = this;
if (sv._flickAnim) {
// Cancel the flick (if it exists)
sv._flickAnim.cancel();
// Also delete it, otherwise _onGestureMoveStart will think we're still flicking
delete sv._flickAnim;
}
},
/**
* Handle mousewheel events on the widget
*
* @method _mousewheel
* @param e {Event.Facade} The mousewheel event facade
* @private
*/
_mousewheel: function (e) {
var sv = this,
scrollY = sv.get(SCROLL_Y),
bounds = sv._getBounds(),
bb = sv._bb,
scrollOffset = 10, // 10px
isForward = (e.wheelDelta > 0),
scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);
scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);
// Because Mousewheel events fire off 'document', every ScrollView widget will react
// to any mousewheel anywhere on the page. This check will ensure that the mouse is currently
// over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,
// becuase otherwise the 'prevent' will block page scrolling.
if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {
// Reset lastScrolledAmt
sv.lastScrolledAmt = 0;
// Jump to the new offset
sv.set(SCROLL_Y, scrollToY);
// if we have scrollbars plugin, update & set the flash timer on the scrollbar
// @TODO: This probably shouldn't be in this module
if (sv.scrollbars) {
// @TODO: The scrollbars should handle this themselves
sv.scrollbars._update();
sv.scrollbars.flash();
// or just this
// sv.scrollbars._hostDimensionsChange();
}
// Fire the 'scrollEnd' event
sv._onTransEnd();
// prevent browser default behavior on mouse scroll
e.preventDefault();
}
},
/**
* Checks to see the current scrollX/scrollY position beyond the min/max boundary
*
* @method _isOutOfBounds
* @param x {Number} [optional] The X position to check
* @param y {Number} [optional] The Y position to check
* @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false)
* @private
*/
_isOutOfBounds: function (x, y) {
var sv = this,
svAxis = sv._cAxis,
svAxisX = svAxis.x,
svAxisY = svAxis.y,
currentX = x || sv.get(SCROLL_X),
currentY = y || sv.get(SCROLL_Y),
bounds = sv._getBounds(),
minX = bounds.minScrollX,
minY = bounds.minScrollY,
maxX = bounds.maxScrollX,
maxY = bounds.maxScrollY;
return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));
},
/**
* Bounces back
* @TODO: Should be more generalized and support both X and Y detection
*
* @method _snapBack
* @private
*/
_snapBack: function () {
var sv = this,
currentX = sv.get(SCROLL_X),
currentY = sv.get(SCROLL_Y),
bounds = sv._getBounds(),
minX = bounds.minScrollX,
minY = bounds.minScrollY,
maxX = bounds.maxScrollX,
maxY = bounds.maxScrollY,
newY = _constrain(currentY, minY, maxY),
newX = _constrain(currentX, minX, maxX),
duration = sv.get(SNAP_DURATION),
easing = sv.get(SNAP_EASING);
if (newX !== currentX) {
sv.set(SCROLL_X, newX, {duration:duration, easing:easing});
}
else if (newY !== currentY) {
sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});
}
else {
sv._onTransEnd();
}
},
/**
* After listener for changes to the scrollX or scrollY attribute
*
* @method _afterScrollChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterScrollChange: function (e) {
if (e.src === ScrollView.UI_SRC) {
return false;
}
var sv = this,
duration = e.duration,
easing = e.easing,
val = e.newVal,
scrollToArgs = [];
// Set the scrolled value
sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);
// Generate the array of args to pass to scrollTo()
if (e.attrName === SCROLL_X) {
scrollToArgs.push(val);
scrollToArgs.push(sv.get(SCROLL_Y));
}
else {
scrollToArgs.push(sv.get(SCROLL_X));
scrollToArgs.push(val);
}
scrollToArgs.push(duration);
scrollToArgs.push(easing);
sv.scrollTo.apply(sv, scrollToArgs);
},
/**
* After listener for changes to the flick attribute
*
* @method _afterFlickChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterFlickChange: function (e) {
this._bindFlick(e.newVal);
},
/**
* After listener for changes to the disabled attribute
*
* @method _afterDisabledChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDisabledChange: function (e) {
// Cache for performance - we check during move
this._cDisabled = e.newVal;
},
/**
* After listener for the axis attribute
*
* @method _afterAxisChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterAxisChange: function (e) {
this._cAxis = e.newVal;
},
/**
* After listener for changes to the drag attribute
*
* @method _afterDragChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDragChange: function (e) {
this._bindDrag(e.newVal);
},
/**
* After listener for the height or width attribute
*
* @method _afterDimChange
* @param e {Event.Facade} The event facade
* @protected
*/
_afterDimChange: function () {
this._uiDimensionsChange();
},
/**
* After listener for scrollEnd, for cleanup
*
* @method _afterScrollEnd
* @param e {Event.Facade} The event facade
* @protected
*/
_afterScrollEnd: function () {
var sv = this;
if (sv._flickAnim) {
sv._cancelFlick();
}
// Ideally this should be removed, but doing so causing some JS errors with fast swiping
// because _gesture is being deleted after the previous one has been overwritten
// delete sv._gesture; // TODO: Move to sv.prevGesture?
},
/**
* Setter for 'axis' attribute
*
* @method _axisSetter
* @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on
* @param name {String} The attribute name
* @return {Object} An object to specify scrollability on the x & y axes
*
* @protected
*/
_axisSetter: function (val) {
// Turn a string into an axis object
if (Y.Lang.isString(val)) {
return {
x: val.match(/x/i) ? true : false,
y: val.match(/y/i) ? true : false
};
}
},
/**
* The scrollX, scrollY setter implementation
*
* @method _setScroll
* @private
* @param {Number} val
* @param {String} dim
*
* @return {Number} The value
*/
_setScroll : function(val) {
// Just ensure the widget is not disabled
if (this._cDisabled) {
val = Y.Attribute.INVALID_VALUE;
}
return val;
},
/**
* Setter for the scrollX attribute
*
* @method _setScrollX
* @param val {Number} The new scrollX value
* @return {Number} The normalized value
* @protected
*/
_setScrollX: function(val) {
return this._setScroll(val, DIM_X);
},
/**
* Setter for the scrollY ATTR
*
* @method _setScrollY
* @param val {Number} The new scrollY value
* @return {Number} The normalized value
* @protected
*/
_setScrollY: function(val) {
return this._setScroll(val, DIM_Y);
}
// End prototype properties
}, {
// Static properties
/**
* The identity of the widget.
*
* @property NAME
* @type String
* @default 'scrollview'
* @readOnly
* @protected
* @static
*/
NAME: 'scrollview',
/**
* Static property used to define the default attribute configuration of
* the Widget.
*
* @property ATTRS
* @type {Object}
* @protected
* @static
*/
ATTRS: {
/**
* Specifies ability to scroll on x, y, or x and y axis/axes.
*
* @attribute axis
* @type String
*/
axis: {
setter: '_axisSetter',
writeOnce: 'initOnly'
},
/**
* The current scroll position in the x-axis
*
* @attribute scrollX
* @type Number
* @default 0
*/
scrollX: {
value: 0,
setter: '_setScrollX'
},
/**
* The current scroll position in the y-axis
*
* @attribute scrollY
* @type Number
* @default 0
*/
scrollY: {
value: 0,
setter: '_setScrollY'
},
/**
* Drag coefficent for inertial scrolling. The closer to 1 this
* value is, the less friction during scrolling.
*
* @attribute deceleration
* @default 0.93
*/
deceleration: {
value: 0.93
},
/**
* Drag coefficient for intertial scrolling at the upper
* and lower boundaries of the scrollview. Set to 0 to
* disable "rubber-banding".
*
* @attribute bounce
* @type Number
* @default 0.1
*/
bounce: {
value: 0.1
},
/**
* The minimum distance and/or velocity which define a flick. Can be set to false,
* to disable flick support (note: drag support is enabled/disabled separately)
*
* @attribute flick
* @type Object
* @default Object with properties minDistance = 10, minVelocity = 0.3.
*/
flick: {
value: {
minDistance: 10,
minVelocity: 0.3
}
},
/**
* Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)
* @attribute drag
* @type boolean
* @default true
*/
drag: {
value: true
},
/**
* The default duration to use when animating the bounce snap back.
*
* @attribute snapDuration
* @type Number
* @default 400
*/
snapDuration: {
value: 400
},
/**
* The default easing to use when animating the bounce snap back.
*
* @attribute snapEasing
* @type String
* @default 'ease-out'
*/
snapEasing: {
value: 'ease-out'
},
/**
* The default easing used when animating the flick
*
* @attribute easing
* @type String
* @default 'cubic-bezier(0, 0.1, 0, 1.0)'
*/
easing: {
value: 'cubic-bezier(0, 0.1, 0, 1.0)'
},
/**
* The interval (ms) used when animating the flick for JS-timer animations
*
* @attribute frameDuration
* @type Number
* @default 15
*/
frameDuration: {
value: 15
},
/**
* The default bounce distance in pixels
*
* @attribute bounceRange
* @type Number
* @default 150
*/
bounceRange: {
value: 150
}
},
/**
* List of class names used in the scrollview's DOM
*
* @property CLASS_NAMES
* @type Object
* @static
*/
CLASS_NAMES: CLASS_NAMES,
/**
* Flag used to source property changes initiated from the DOM
*
* @property UI_SRC
* @type String
* @static
* @default 'ui'
*/
UI_SRC: UI,
/**
* Object map of style property names used to set transition properties.
* Defaults to the vendor prefix established by the Transition module.
* The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and
* `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty").
*
* @property _TRANSITION
* @private
*/
_TRANSITION: {
DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),
PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')
},
/**
* The default bounce distance in pixels
*
* @property BOUNCE_RANGE
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
BOUNCE_RANGE: false,
/**
* The interval (ms) used when animating the flick
*
* @property FRAME_STEP
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
FRAME_STEP: false,
/**
* The default easing used when animating the flick
*
* @property EASING
* @type String
* @static
* @default false
* @deprecated (in 3.7.0)
*/
EASING: false,
/**
* The default easing to use when animating the bounce snap back.
*
* @property SNAP_EASING
* @type String
* @static
* @default false
* @deprecated (in 3.7.0)
*/
SNAP_EASING: false,
/**
* The default duration to use when animating the bounce snap back.
*
* @property SNAP_DURATION
* @type Number
* @static
* @default false
* @deprecated (in 3.7.0)
*/
SNAP_DURATION: false
// End static properties
});
}, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
|
blueprints/view/files/__root__/views/__name__View/__name__View.js | wardy/cool-story-bro | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
packages/netlify-cms-widget-code/src/SettingsPane.js | netlify/netlify-cms | import React from 'react';
import styled from '@emotion/styled';
import Select from 'react-select';
import isHotkey from 'is-hotkey';
import { text, shadows, zIndex } from 'netlify-cms-ui-default';
import SettingsButton from './SettingsButton';
import languageSelectStyles from './languageSelectStyles';
const SettingsPaneContainer = styled.div`
position: absolute;
right: 0;
width: 200px;
z-index: ${zIndex.zIndex10};
height: 100%;
background-color: #fff;
overflow: hidden;
overflow-y: scroll;
padding: 12px;
border-radius: 0 3px 3px 0;
${shadows.drop};
`;
const SettingsFieldLabel = styled.label`
${text.fieldLabel};
font-size: 11px;
display: block;
margin-top: 8px;
margin-bottom: 2px;
`;
const SettingsSectionTitle = styled.h3`
font-size: 14px;
margin-top: 14px;
margin-bottom: 0;
&:first-of-type {
margin-top: 4px;
}
`;
function SettingsSelect({ value, options, onChange, forID, type, autoFocus }) {
return (
<Select
inputId={`${forID}-select-${type}`}
styles={languageSelectStyles}
value={value}
options={options}
onChange={opt => onChange(opt.value)}
menuPlacement="auto"
captureMenuScroll={false}
autoFocus={autoFocus}
/>
);
}
function SettingsPane({
hideSettings,
forID,
modes,
mode,
theme,
themes,
keyMap,
keyMaps,
allowLanguageSelection,
onChangeLang,
onChangeTheme,
onChangeKeyMap,
}) {
return (
<SettingsPaneContainer onKeyDown={e => isHotkey('esc', e) && hideSettings()}>
<SettingsButton onClick={hideSettings} showClose={true} />
{allowLanguageSelection && (
<>
<SettingsSectionTitle>Field Settings</SettingsSectionTitle>
<SettingsFieldLabel htmlFor={`${forID}-select-mode`}>Mode</SettingsFieldLabel>
<SettingsSelect
type="mode"
forID={forID}
value={mode}
options={modes}
onChange={onChangeLang}
autoFocus
/>
</>
)}
<>
<SettingsSectionTitle>Global Settings</SettingsSectionTitle>
{themes && (
<>
<SettingsFieldLabel htmlFor={`${forID}-select-theme`}>Theme</SettingsFieldLabel>
<SettingsSelect
type="theme"
forID={forID}
value={{ value: theme, label: theme }}
options={themes.map(t => ({ value: t, label: t }))}
onChange={onChangeTheme}
autoFocus={!allowLanguageSelection}
/>
</>
)}
<SettingsFieldLabel htmlFor={`${forID}-select-keymap`}>KeyMap</SettingsFieldLabel>
<SettingsSelect
type="keymap"
forID={forID}
value={keyMap}
options={keyMaps}
onChange={onChangeKeyMap}
/>
</>
</SettingsPaneContainer>
);
}
export default SettingsPane;
|
src/components/DefaultBlockType.js | vigetlabs/colonel-kurtz | import React from 'react'
export default class DefaultBlockType extends React.Component {
render() {
return <div>{this.props.children}</div>
}
}
|
src/components/searchbar.js | tgundavelli/React_Udemy | import React, { Component } from 'react';
//const SearchBar = () => {
// return <input />;
//};
// each class based object has a state object
// if state of search bar is changed then the render function is reran
class SearchBar extends Component{
// this is how we initialize state in a class based component
// constructor is used for initializing state
// component has a constructor function and we are calling the parent constructor
constructor(props) {
super(props);
// we initialize state by defining a new object and passing it to this.state
// we want to update term to be whatever this.state is
// this is the only time state looks like
this.state = { term : ''};
}
render(){
// we will be changing state in the render function
// always manipulate state with this.setState
return (
<div>
<input value = {this.state.term}
onChange = {event => this.setState({term : event.target.value})} />
</div>
//Value of input : {this.state.term}
//always wrap a variable around {}
);
} // every class must have a render function
// this is how we put values into our search bar!!
}
export default SearchBar; |
themes/frontend/assets/reactjs/process/js/1SearchCarPage.js | fonea/velon | import React from 'react';
import CarFilterResults from './CarFilterResults';
import SearchCarPager from './SearchCarPager';
import SearchCarDisplayController from './SearchCarDisplayController';
import _ from 'lodash';
import cookie from 'react-cookie';
import queryString from 'query-string';
import VelonCircularProgress from './VelonCircularProgress';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import SearchCarVelonDrawer from './SearchCarVelonDrawer';
import config from './config';
import VelonChips from './VelonChips';
export default class SearchCarPage extends React.Component {
constructor(props) {
super(props);
this.getResults = this.getResults.bind(this);
this.mode = this.mode.bind(this);
this.getMoreRows = this.getMoreRows.bind(this);
this.setCarSearchMakeId = this.setCarSearchMakeId.bind(this);
this.setCarSearchModelId = this.setCarSearchModelId.bind(this);
var makeID = null;
var makeLabel = null;
const getParamsRaw = window.location.search;
const getParams = queryString.parse(getParamsRaw);
var currentPage;
var getPageParam = false;
if (!_.isEmpty(getParams)) {
if (_.has(getParams, 'page')) {
currentPage = getParams.page;
getPageParam = true;
}
if (_.has(getParams, 'makeID')) {
makeID = getParams.makeID;
}
if (_.has(getParams, 'makeLabel')) {
makeLabel = getParams.makeLabel;
}
}
if (_.isUndefined(currentPage)) {
currentPage = cookie.load('velonCarSearchPage');
}
if (_.isUndefined(currentPage)) {
currentPage = 0;
}
currentPage = parseInt(currentPage);
if (currentPage && !getPageParam) {
getParams.page = currentPage;
window.location.href = window.location.pathname + '?' + queryString.stringify(getParams);
}
this.state = {
rows: [],
mode: 'list',
currentPage: currentPage,
isLoading: false,
filters: {
make: {
id: makeID,
label: makeLabel
},
model: {
id: makeID,
label: makeLabel
}
}
};
}
// componentDidUpdate(prevProps, prevState) {
// // this.getResults();
// console.log(prevProps);
// console.log(prevState);
// }
componentWillMount() {
this.getResults();
}
setCarSearchMakeId(mID, mLabel) {
this.setState({
filters: {
make: {
id: mID,
label: mLabel
}
}
});
}
setCarSearchModelId(mID, mLabel) {
this.setState({
filters: {
model: {
id: mID,
label: mLabel
}
}
});
}
getMoreRows(p) {
var currentPage = this.state.currentPage;
var more;
if (_.isUndefined(p)) {
currentPage = parseInt(currentPage + 1);
more = true;
}
else {
more = false;
if (parseInt(p) < 0) {
currentPage--;
}
else {
if (parseInt(p) == 0) {
currentPage = 0;
}
else {
currentPage++;
}
}
}
cookie.save('velonCarSearchPage', currentPage);
this.setState({
currentPage: currentPage
}, function() {
if (more) {
this.getResults();
}
else {
var getParamsRaw = window.location.search;
var getParams = queryString.parse(getParamsRaw);
getParams.page = currentPage;
window.location.href = window.location.pathname + '?' + queryString.stringify(getParams);
}
}
);
}
getResults() {
// console.log('#xx');
var currentPage = this.state.currentPage;
var requestPath = '/car-json?page='+currentPage;
this.setState({
isLoading:true
});
return {};
// fetch(requestPath, {
// method: 'GET',
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// }
// }).then(function (response) {
// response.json().then(function (object) {
//
// this.setState({
// isLoading:false
// });
// // console.log(object);
// if (object) {
// var results = this.state.rows;
//
// results = results.concat(object.results);
// this.setState({
// rows: results
// });
// }
// return;
// }.bind(this))
// }.bind(this))
// .catch(function (error) {
// return error;
// });
}
mode(value) {
this.setState({
mode: value
});
}
render() {
var rawRows = this.state.rows;
// console.log(config);
// let isLoadingWidget = null;
// if (this.state.isLoading) {
// isLoadingWidget = <VelonCircularProgress />;
// }
// console.log(this.state.filters['make']);
// var filters = [];
// this.state.filters.map(function (v) {
// console.log(v);
//
// if (_.has(v, 'make')) {
// filters.push(v.make);
// }
// });
return (<div>
<MuiThemeProvider>
<div>
<div>
<SearchCarVelonDrawer
// setSearchMakeId={this.setCarSearchMakeId}
// setSearchModelId={this.setCarSearchModelId}
// makeCarId={this.state.filters['make'].id}
// setModels={this.setModels}
// carFilters={this.state.filters}
/>
</div>
<div>
{/*<VelonChips*/}
{/*// carFilters={this.state.filters}*/}
{/*/>*/}
</div>
{/*<div>*/}
{/*{isLoadingWidget}*/}
{/*</div>*/}
{/*<div className="carFilters">filters</div>*/}
{/*<div className="carDisplayProcessor">*/}
{/*<SearchCarDisplayController*/}
{/*mode = {this.mode}*/}
{/*/>*/}
{/*</div>*/}
{/*<div className="carFilterResults">*/}
{/*<CarFilterResults*/}
{/*rows={this.state.rows}*/}
{/*mode={this.state.mode}*/}
{/*/>*/}
{/*</div>*/}
{/*<div className="carPager">*/}
{/*<SearchCarPager*/}
{/*handleRows={this.getMoreRows}*/}
{/*currentPage={this.state.currentPage}*/}
{/*/>*/}
{/*</div>*/}
</div>
</MuiThemeProvider>
</div>
);
}
}; |
node_modules/react-icons/md/local-bar.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const MdLocalBar = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m12.4 11.6h15.2l2.9-3.2h-21z m22.6-3.2l-13.4 15v8.2h8.4v3.4h-20v-3.4h8.4v-8.2l-13.4-15v-3.4h30v3.4z"/></g>
</Icon>
)
export default MdLocalBar
|
src/lib/Row.js | maheshsenni/react-treelist | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import '../css/row.css';
import RowCell from './RowCell';
import { getClassName } from './util/TreeUtils'
class Row extends Component {
constructor(props) {
super(props);
this.displayName = 'Row';
this.handleExpandToggle = this.handleExpandToggle.bind(this);
this.handleSelectRow = this.handleSelectRow.bind(this);
}
handleExpandToggle(e) {
e.stopPropagation();
this.props.onExpandToggle(this.props.data);
}
handleSelectRow(e) {
this.props.onSelect(this.props.data, e);
}
makeCells(columns, data, canExpand) {
// check if a column is specified to show
// expand collapse icon
let expandColumn = columns.filter((col) => {
return col.expand;
})[0];
// use first columns as default to show
// expand collapse icon
if (typeof expandColumn === 'undefined') {
expandColumn = columns[0];
}
return columns.map((col, index) => {
return (
<RowCell
key={this.props.reactKey + '-col-' + index}
reactKey={this.props.reactKey + '-col-' + index}
indent={this.props.level}
useIndent={expandColumn.field === col.field}
data={data[col.field]}
rowData={data}
type={col.type}
format={col.format}
formatter={col.formatter}
className={col.class}
showExpandCollapse={canExpand && (expandColumn.field === col.field)}
isExpanded={this.props.expanded}
onExpandToggle={this.handleExpandToggle}
></RowCell>
);
});
}
render() {
const { columns, data, canExpand, selected } = this.props;
const cells = this.makeCells(columns, data, canExpand);
const selectedClassName = selected ? "row-selected" : "";
const className = [selectedClassName, getClassName(this.props.className, this.props.data)].join(' ');
return (
<tr className={className} onClick={this.handleSelectRow}>{cells}</tr>
);
}
}
Row.propTypes = {
reactKey: PropTypes.string.isRequired,
columns: PropTypes.array.isRequired,
data: PropTypes.object.isRequired,
level: PropTypes.number.isRequired,
canExpand: PropTypes.bool.isRequired,
expanded: PropTypes.bool,
selected: PropTypes.bool,
onExpandToggle: PropTypes.func,
onSelect: PropTypes.func,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
};
const createRow = function(data, level, columns, idField, canExpand, expanded, onExpandToggleHandler, onSelectToggleHandler, selected, rowClass) {
return (<Row
key={'row-' + data[idField]}
reactKey={'row-' + data[idField]}
columns={columns}
data={data}
level={level}
canExpand={canExpand}
expanded={expanded}
onExpandToggle={onExpandToggleHandler}
onSelect={onSelectToggleHandler}
selected={selected}
className={rowClass}
></Row>);
}
export { Row, createRow };
|
examples/react-backbone/node_modules/react/dist/JSXTransformer.js | thebkbuffalo/todomvc | /**
* JSXTransformer v0.13.3
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSXTransformer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*/
/* jshint browser: true */
/* jslint evil: true */
/*eslint-disable no-eval */
/*eslint-disable block-scoped-var */
'use strict';
var ReactTools = _dereq_('../main');
var inlineSourceMap = _dereq_('./inline-source-map');
var headEl;
var dummyAnchor;
var inlineScriptCount = 0;
// The source-map library relies on Object.defineProperty, but IE8 doesn't
// support it fully even with es5-sham. Indeed, es5-sham's defineProperty
// throws when Object.prototype.__defineGetter__ is missing, so we skip building
// the source map in that case.
var supportsAccessors = Object.prototype.hasOwnProperty('__defineGetter__');
/**
* Run provided code through jstransform.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
* @return {object} object as returned from jstransform
*/
function transformReact(source, options) {
options = options || {};
// Force the sourcemaps option manually. We don't want to use it if it will
// break (see above note about supportsAccessors). We'll only override the
// value here if sourceMap was specified and is truthy. This guarantees that
// we won't override any user intent (since this method is exposed publicly).
if (options.sourceMap) {
options.sourceMap = supportsAccessors;
}
// Otherwise just pass all options straight through to react-tools.
return ReactTools.transformWithDetails(source, options);
}
/**
* Eval provided source after transforming it.
*
* @param {string} source Original source code
* @param {object?} options Options to pass to jstransform
*/
function exec(source, options) {
return eval(transformReact(source, options).code);
}
/**
* This method returns a nicely formated line of code pointing to the exact
* location of the error `e`. The line is limited in size so big lines of code
* are also shown in a readable way.
*
* Example:
* ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=" ...
* ^
*
* @param {string} code The full string of code
* @param {Error} e The error being thrown
* @return {string} formatted message
* @internal
*/
function createSourceCodeErrorMessage(code, e) {
var sourceLines = code.split('\n');
// e.lineNumber is non-standard so we can't depend on its availability. If
// we're in a browser where it isn't supported, don't even bother trying to
// format anything. We may also hit a case where the line number is reported
// incorrectly and is outside the bounds of the actual code. Handle that too.
if (!e.lineNumber || e.lineNumber > sourceLines.length) {
return '';
}
var erroneousLine = sourceLines[e.lineNumber - 1];
// Removes any leading indenting spaces and gets the number of
// chars indenting the `erroneousLine`
var indentation = 0;
erroneousLine = erroneousLine.replace(/^\s+/, function(leadingSpaces) {
indentation = leadingSpaces.length;
return '';
});
// Defines the number of characters that are going to show
// before and after the erroneous code
var LIMIT = 30;
var errorColumn = e.column - indentation;
if (errorColumn > LIMIT) {
erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT);
errorColumn = 4 + LIMIT;
}
if (erroneousLine.length - errorColumn > LIMIT) {
erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...';
}
var message = '\n\n' + erroneousLine + '\n';
message += new Array(errorColumn - 1).join(' ') + '^';
return message;
}
/**
* Actually transform the code.
*
* @param {string} code
* @param {string?} url
* @param {object?} options
* @return {string} The transformed code.
* @internal
*/
function transformCode(code, url, options) {
try {
var transformed = transformReact(code, options);
} catch(e) {
e.message += '\n at ';
if (url) {
if ('fileName' in e) {
// We set `fileName` if it's supported by this error object and
// a `url` was provided.
// The error will correctly point to `url` in Firefox.
e.fileName = url;
}
e.message += url + ':' + e.lineNumber + ':' + e.columnNumber;
} else {
e.message += location.href;
}
e.message += createSourceCodeErrorMessage(code, e);
throw e;
}
if (!transformed.sourceMap) {
return transformed.code;
}
var source;
if (url == null) {
source = 'Inline JSX script';
inlineScriptCount++;
if (inlineScriptCount > 1) {
source += ' (' + inlineScriptCount + ')';
}
} else if (dummyAnchor) {
// Firefox has problems when the sourcemap source is a proper URL with a
// protocol and hostname, so use the pathname. We could use just the
// filename, but hopefully using the full path will prevent potential
// issues where the same filename exists in multiple directories.
dummyAnchor.href = url;
source = dummyAnchor.pathname.substr(1);
}
return (
transformed.code +
'\n' +
inlineSourceMap(transformed.sourceMap, code, source)
);
}
/**
* Appends a script element at the end of the <head> with the content of code,
* after transforming it.
*
* @param {string} code The original source code
* @param {string?} url Where the code came from. null if inline
* @param {object?} options Options to pass to jstransform
* @internal
*/
function run(code, url, options) {
var scriptEl = document.createElement('script');
scriptEl.text = transformCode(code, url, options);
headEl.appendChild(scriptEl);
}
/**
* Load script from the provided url and pass the content to the callback.
*
* @param {string} url The location of the script src
* @param {function} callback Function to call with the content of url
* @internal
*/
function load(url, successCallback, errorCallback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// async, however scripts will be executed in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 0 || xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback();
throw new Error('Could not load ' + url);
}
}
};
return xhr.send(null);
}
/**
* Loop over provided script tags and get the content, via innerHTML if an
* inline script, or by using XHR. Transforms are applied if needed. The scripts
* are executed in the order they are found on the page.
*
* @param {array} scripts The <script> elements to load and run.
* @internal
*/
function loadScripts(scripts) {
var result = [];
var count = scripts.length;
function check() {
var script, i;
for (i = 0; i < count; i++) {
script = result[i];
if (script.loaded && !script.executed) {
script.executed = true;
run(script.content, script.url, script.options);
} else if (!script.loaded && !script.error && !script.async) {
break;
}
}
}
scripts.forEach(function(script, i) {
var options = {
sourceMap: true
};
if (/;harmony=true(;|$)/.test(script.type)) {
options.harmony = true;
}
if (/;stripTypes=true(;|$)/.test(script.type)) {
options.stripTypes = true;
}
// script.async is always true for non-javascript script tags
var async = script.hasAttribute('async');
if (script.src) {
result[i] = {
async: async,
error: false,
executed: false,
content: null,
loaded: false,
url: script.src,
options: options
};
load(script.src, function(content) {
result[i].loaded = true;
result[i].content = content;
check();
}, function() {
result[i].error = true;
check();
});
} else {
result[i] = {
async: async,
error: false,
executed: false,
content: script.innerHTML,
loaded: true,
url: null,
options: options
};
}
});
check();
}
/**
* Find and run all script tags with type="text/jsx".
*
* @internal
*/
function runScripts() {
var scripts = document.getElementsByTagName('script');
// Array.prototype.slice cannot be used on NodeList on IE8
var jsxScripts = [];
for (var i = 0; i < scripts.length; i++) {
if (/^text\/jsx(;|$)/.test(scripts.item(i).type)) {
jsxScripts.push(scripts.item(i));
}
}
if (jsxScripts.length < 1) {
return;
}
console.warn(
'You are using the in-browser JSX transformer. Be sure to precompile ' +
'your JSX for production - ' +
'http://facebook.github.io/react/docs/tooling-integration.html#jsx'
);
loadScripts(jsxScripts);
}
// Listen for load event if we're in a browser and then kick off finding and
// running of scripts.
if (typeof window !== 'undefined' && window !== null) {
headEl = document.getElementsByTagName('head')[0];
dummyAnchor = document.createElement('a');
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', runScripts, false);
} else {
window.attachEvent('onload', runScripts);
}
}
module.exports = {
transform: transformReact,
exec: exec
};
},{"../main":2,"./inline-source-map":41}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var visitors = _dereq_('./vendor/fbtransform/visitors');
var transform = _dereq_('jstransform').transform;
var typesSyntax = _dereq_('jstransform/visitors/type-syntax');
var inlineSourceMap = _dereq_('./vendor/inline-source-map');
module.exports = {
transform: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = output.code;
if (options.sourceMap) {
var map = inlineSourceMap(
output.sourceMap,
input,
options.filename
);
result += '\n' + map;
}
return result;
},
transformWithDetails: function(input, options) {
options = processOptions(options);
var output = innerTransform(input, options);
var result = {};
result.code = output.code;
if (options.sourceMap) {
result.sourceMap = output.sourceMap.toJSON();
}
if (options.filename) {
result.sourceMap.sources = [options.filename];
}
return result;
}
};
/**
* Only copy the values that we need. We'll do some preprocessing to account for
* converting command line flags to options that jstransform can actually use.
*/
function processOptions(opts) {
opts = opts || {};
var options = {};
options.harmony = opts.harmony;
options.stripTypes = opts.stripTypes;
options.sourceMap = opts.sourceMap;
options.filename = opts.sourceFilename;
if (opts.es6module) {
options.sourceType = 'module';
}
if (opts.nonStrictEs6module) {
options.sourceType = 'nonStrictModule';
}
// Instead of doing any fancy validation, only look for 'es3'. If we have
// that, then use it. Otherwise use 'es5'.
options.es3 = opts.target === 'es3';
options.es5 = !options.es3;
return options;
}
function innerTransform(input, options) {
var visitorSets = ['react'];
if (options.harmony) {
visitorSets.push('harmony');
}
if (options.es3) {
visitorSets.push('es3');
}
if (options.stripTypes) {
// Stripping types needs to happen before the other transforms
// unfortunately, due to bad interactions. For example,
// es6-rest-param-visitors conflict with stripping rest param type
// annotation
input = transform(typesSyntax.visitorList, input, options).code;
}
var visitorList = visitors.getVisitorsBySet(visitorSets);
return transform(visitorList, input, options);
}
},{"./vendor/fbtransform/visitors":40,"./vendor/inline-source-map":41,"jstransform":22,"jstransform/visitors/type-syntax":36}],3:[function(_dereq_,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var base64 = _dereq_('base64-js')
var ieee754 = _dereq_('ieee754')
var isArray = _dereq_('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
var rootParent = {}
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding) {
var self = this
if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
var type = typeof subject
var length
if (type === 'number') {
length = +subject
} else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) {
// assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
length = +subject.length
} else {
throw new TypeError('must start with number, buffer, array or string')
}
if (length > kMaxLength) {
throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
kMaxLength.toString(16) + ' bytes')
}
if (length < 0) length = 0
else length >>>= 0 // coerce to uint32
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
self.length = length
self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++) {
self[i] = subject.readUInt8(i)
}
} else {
for (i = 0; i < length; i++) {
self[i] = ((subject[i] % 256) + 256) % 256
}
}
} else if (type === 'string') {
self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
for (i = 0; i < length; i++) {
self[i] = 0
}
}
if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
return self
}
function SlowBuffer (subject, encoding) {
if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
var buf = new Buffer(subject, encoding)
delete buf.parent
return buf
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, totalLength) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function toString (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return 0
return Buffer.compare(this, b)
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
else if (byteOffset < -0x80000000) byteOffset = -0x80000000
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
if (val.length === 0) return -1 // special case: looking for empty string always fails
return String.prototype.indexOf.call(this, val, byteOffset)
}
if (Buffer.isBuffer(val)) {
return arrayIndexOf(this, val, byteOffset)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset)
}
function arrayIndexOf (arr, val, byteOffset) {
var foundIndex = -1
for (var i = 0; byteOffset + i < arr.length; i++) {
if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
} else {
foundIndex = -1
}
}
return -1
}
throw new TypeError('val must be string, number or Buffer')
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function set (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) throw new Error('Invalid hex string')
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
if (length < 0 || offset < 0 || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
if (newBuf.length) newBuf.parent = this.parent || this
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) >>> 0 & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = 0
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
var i = byteLength - 1
var mul = 1
var sub = value < 0 ? 1 : 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new RangeError('value is out of bounds')
if (offset + ext > buf.length) throw new RangeError('index out of range')
if (offset < 0) throw new RangeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, target_start, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (target_start < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - target_start < end - start) {
end = target.length - target_start + start
}
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
return len
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function fill (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new RangeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function _augment (arr) {
arr.constructor = Buffer
arr._isBuffer = true
// save reference to original Uint8Array set method before overwriting
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.indexOf = BP.indexOf
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUIntLE = BP.readUIntLE
arr.readUIntBE = BP.readUIntBE
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readIntLE = BP.readIntLE
arr.readIntBE = BP.readIntBE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUIntLE = BP.writeUIntLE
arr.writeUIntBE = BP.writeUIntBE
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeIntLE = BP.writeIntLE
arr.writeIntBE = BP.writeIntBE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
var i = 0
for (; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (leadSurrogate) {
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
} else {
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
leadSurrogate = null
}
} else {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else {
// valid lead
leadSurrogate = codePoint
continue
}
}
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = null
}
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x200000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":4,"ieee754":5,"is-array":6}],4:[function(_dereq_,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],5:[function(_dereq_,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],6:[function(_dereq_,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],7:[function(_dereq_,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,_dereq_('_process'))
},{"_process":8}],8:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
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');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],9:[function(_dereq_,module,exports){
/*
Copyright (C) 2013 Ariya Hidayat <[email protected]>
Copyright (C) 2013 Thaddee Tyl <[email protected]>
Copyright (C) 2012 Ariya Hidayat <[email protected]>
Copyright (C) 2012 Mathias Bynens <[email protected]>
Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]>
Copyright (C) 2012 Kris Kowal <[email protected]>
Copyright (C) 2012 Yusuke Suzuki <[email protected]>
Copyright (C) 2012 Arpad Borsos <[email protected]>
Copyright (C) 2011 Ariya Hidayat <[email protected]>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (root, factory) {
'use strict';
// Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
// Rhino, and plain browser loading.
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.esprima = {}));
}
}(this, function (exports) {
'use strict';
var Token,
TokenName,
FnExprTokens,
Syntax,
PropertyKind,
Messages,
Regex,
SyntaxTreeDelegate,
XHTMLEntities,
ClassPropertyType,
source,
strict,
index,
lineNumber,
lineStart,
length,
delegate,
lookahead,
state,
extra;
Token = {
BooleanLiteral: 1,
EOF: 2,
Identifier: 3,
Keyword: 4,
NullLiteral: 5,
NumericLiteral: 6,
Punctuator: 7,
StringLiteral: 8,
RegularExpression: 9,
Template: 10,
JSXIdentifier: 11,
JSXText: 12
};
TokenName = {};
TokenName[Token.BooleanLiteral] = 'Boolean';
TokenName[Token.EOF] = '<end>';
TokenName[Token.Identifier] = 'Identifier';
TokenName[Token.Keyword] = 'Keyword';
TokenName[Token.NullLiteral] = 'Null';
TokenName[Token.NumericLiteral] = 'Numeric';
TokenName[Token.Punctuator] = 'Punctuator';
TokenName[Token.StringLiteral] = 'String';
TokenName[Token.JSXIdentifier] = 'JSXIdentifier';
TokenName[Token.JSXText] = 'JSXText';
TokenName[Token.RegularExpression] = 'RegularExpression';
// A function following one of those tokens is an expression.
FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
'return', 'case', 'delete', 'throw', 'void',
// assignment operators
'=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=',
'&=', '|=', '^=', ',',
// binary/unary operators
'+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
'|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
'<=', '<', '>', '!=', '!=='];
Syntax = {
AnyTypeAnnotation: 'AnyTypeAnnotation',
ArrayExpression: 'ArrayExpression',
ArrayPattern: 'ArrayPattern',
ArrayTypeAnnotation: 'ArrayTypeAnnotation',
ArrowFunctionExpression: 'ArrowFunctionExpression',
AssignmentExpression: 'AssignmentExpression',
BinaryExpression: 'BinaryExpression',
BlockStatement: 'BlockStatement',
BooleanTypeAnnotation: 'BooleanTypeAnnotation',
BreakStatement: 'BreakStatement',
CallExpression: 'CallExpression',
CatchClause: 'CatchClause',
ClassBody: 'ClassBody',
ClassDeclaration: 'ClassDeclaration',
ClassExpression: 'ClassExpression',
ClassImplements: 'ClassImplements',
ClassProperty: 'ClassProperty',
ComprehensionBlock: 'ComprehensionBlock',
ComprehensionExpression: 'ComprehensionExpression',
ConditionalExpression: 'ConditionalExpression',
ContinueStatement: 'ContinueStatement',
DebuggerStatement: 'DebuggerStatement',
DeclareClass: 'DeclareClass',
DeclareFunction: 'DeclareFunction',
DeclareModule: 'DeclareModule',
DeclareVariable: 'DeclareVariable',
DoWhileStatement: 'DoWhileStatement',
EmptyStatement: 'EmptyStatement',
ExportDeclaration: 'ExportDeclaration',
ExportBatchSpecifier: 'ExportBatchSpecifier',
ExportSpecifier: 'ExportSpecifier',
ExpressionStatement: 'ExpressionStatement',
ForInStatement: 'ForInStatement',
ForOfStatement: 'ForOfStatement',
ForStatement: 'ForStatement',
FunctionDeclaration: 'FunctionDeclaration',
FunctionExpression: 'FunctionExpression',
FunctionTypeAnnotation: 'FunctionTypeAnnotation',
FunctionTypeParam: 'FunctionTypeParam',
GenericTypeAnnotation: 'GenericTypeAnnotation',
Identifier: 'Identifier',
IfStatement: 'IfStatement',
ImportDeclaration: 'ImportDeclaration',
ImportDefaultSpecifier: 'ImportDefaultSpecifier',
ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
ImportSpecifier: 'ImportSpecifier',
InterfaceDeclaration: 'InterfaceDeclaration',
InterfaceExtends: 'InterfaceExtends',
IntersectionTypeAnnotation: 'IntersectionTypeAnnotation',
LabeledStatement: 'LabeledStatement',
Literal: 'Literal',
LogicalExpression: 'LogicalExpression',
MemberExpression: 'MemberExpression',
MethodDefinition: 'MethodDefinition',
ModuleSpecifier: 'ModuleSpecifier',
NewExpression: 'NewExpression',
NullableTypeAnnotation: 'NullableTypeAnnotation',
NumberTypeAnnotation: 'NumberTypeAnnotation',
ObjectExpression: 'ObjectExpression',
ObjectPattern: 'ObjectPattern',
ObjectTypeAnnotation: 'ObjectTypeAnnotation',
ObjectTypeCallProperty: 'ObjectTypeCallProperty',
ObjectTypeIndexer: 'ObjectTypeIndexer',
ObjectTypeProperty: 'ObjectTypeProperty',
Program: 'Program',
Property: 'Property',
QualifiedTypeIdentifier: 'QualifiedTypeIdentifier',
ReturnStatement: 'ReturnStatement',
SequenceExpression: 'SequenceExpression',
SpreadElement: 'SpreadElement',
SpreadProperty: 'SpreadProperty',
StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation',
StringTypeAnnotation: 'StringTypeAnnotation',
SwitchCase: 'SwitchCase',
SwitchStatement: 'SwitchStatement',
TaggedTemplateExpression: 'TaggedTemplateExpression',
TemplateElement: 'TemplateElement',
TemplateLiteral: 'TemplateLiteral',
ThisExpression: 'ThisExpression',
ThrowStatement: 'ThrowStatement',
TupleTypeAnnotation: 'TupleTypeAnnotation',
TryStatement: 'TryStatement',
TypeAlias: 'TypeAlias',
TypeAnnotation: 'TypeAnnotation',
TypeCastExpression: 'TypeCastExpression',
TypeofTypeAnnotation: 'TypeofTypeAnnotation',
TypeParameterDeclaration: 'TypeParameterDeclaration',
TypeParameterInstantiation: 'TypeParameterInstantiation',
UnaryExpression: 'UnaryExpression',
UnionTypeAnnotation: 'UnionTypeAnnotation',
UpdateExpression: 'UpdateExpression',
VariableDeclaration: 'VariableDeclaration',
VariableDeclarator: 'VariableDeclarator',
VoidTypeAnnotation: 'VoidTypeAnnotation',
WhileStatement: 'WhileStatement',
WithStatement: 'WithStatement',
JSXIdentifier: 'JSXIdentifier',
JSXNamespacedName: 'JSXNamespacedName',
JSXMemberExpression: 'JSXMemberExpression',
JSXEmptyExpression: 'JSXEmptyExpression',
JSXExpressionContainer: 'JSXExpressionContainer',
JSXElement: 'JSXElement',
JSXClosingElement: 'JSXClosingElement',
JSXOpeningElement: 'JSXOpeningElement',
JSXAttribute: 'JSXAttribute',
JSXSpreadAttribute: 'JSXSpreadAttribute',
JSXText: 'JSXText',
YieldExpression: 'YieldExpression',
AwaitExpression: 'AwaitExpression'
};
PropertyKind = {
Data: 1,
Get: 2,
Set: 4
};
ClassPropertyType = {
'static': 'static',
prototype: 'prototype'
};
// Error messages should be identical to V8.
Messages = {
UnexpectedToken: 'Unexpected token %0',
UnexpectedNumber: 'Unexpected number',
UnexpectedString: 'Unexpected string',
UnexpectedIdentifier: 'Unexpected identifier',
UnexpectedReserved: 'Unexpected reserved word',
UnexpectedTemplate: 'Unexpected quasi %0',
UnexpectedEOS: 'Unexpected end of input',
NewlineAfterThrow: 'Illegal newline after throw',
InvalidRegExp: 'Invalid regular expression',
UnterminatedRegExp: 'Invalid regular expression: missing /',
InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
InvalidLHSInFormalsList: 'Invalid left-hand side in formals list',
InvalidLHSInForIn: 'Invalid left-hand side in for-in',
MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
NoCatchOrFinally: 'Missing catch or finally after try',
UnknownLabel: 'Undefined label \'%0\'',
Redeclaration: '%0 \'%1\' has already been declared',
IllegalContinue: 'Illegal continue statement',
IllegalBreak: 'Illegal break statement',
IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition',
IllegalClassConstructorProperty: 'Illegal constructor property in class definition',
IllegalReturn: 'Illegal return statement',
IllegalSpread: 'Illegal spread element',
StrictModeWith: 'Strict mode code may not include a with statement',
StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
StrictVarName: 'Variable name may not be eval or arguments in strict mode',
StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list',
DefaultRestParameter: 'Rest parameter can not have a default value',
ElementAfterSpreadElement: 'Spread must be the final element of an element list',
PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal',
ObjectPatternAsRestParameter: 'Invalid rest parameter',
ObjectPatternAsSpread: 'Invalid spread argument',
StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
StrictDelete: 'Delete of an unqualified identifier in strict mode.',
StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
StrictReservedWord: 'Use of future reserved word in strict mode',
MissingFromClause: 'Missing from clause',
NoAsAfterImportNamespace: 'Missing as after import *',
InvalidModuleSpecifier: 'Invalid module specifier',
IllegalImportDeclaration: 'Illegal import declaration',
IllegalExportDeclaration: 'Illegal export declaration',
NoUninitializedConst: 'Const must be initialized',
ComprehensionRequiresBlock: 'Comprehension must have at least one block',
ComprehensionError: 'Comprehension Error',
EachNotAllowed: 'Each is not supported',
InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text',
ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0',
AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag',
ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' +
'you are trying to write a function type, but you ended up ' +
'writing a grouped type followed by an =>, which is a syntax ' +
'error. Remember, function type parameters are named so function ' +
'types look like (name1: type1, name2: type2) => returnType. You ' +
'probably wrote (type1) => returnType'
};
// See also tools/generate-unicode-regex.py.
Regex = {
NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
LeadingZeros: new RegExp('^0+(?!$)')
};
// Ensure the condition is true, otherwise throw an error.
// This is only to have a better contract semantic, i.e. another safety net
// to catch a logic error. The condition shall be fulfilled in normal case.
// Do NOT use this to enforce a certain condition on any user input.
function assert(condition, message) {
/* istanbul ignore if */
if (!condition) {
throw new Error('ASSERT: ' + message);
}
}
function StringMap() {
this.$data = {};
}
StringMap.prototype.get = function (key) {
key = '$' + key;
return this.$data[key];
};
StringMap.prototype.set = function (key, value) {
key = '$' + key;
this.$data[key] = value;
return this;
};
StringMap.prototype.has = function (key) {
key = '$' + key;
return Object.prototype.hasOwnProperty.call(this.$data, key);
};
StringMap.prototype["delete"] = function (key) {
key = '$' + key;
return delete this.$data[key];
};
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0..9
}
function isHexDigit(ch) {
return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
}
function isOctalDigit(ch) {
return '01234567'.indexOf(ch) >= 0;
}
// 7.2 White Space
function isWhiteSpace(ch) {
return (ch === 32) || // space
(ch === 9) || // tab
(ch === 0xB) ||
(ch === 0xC) ||
(ch === 0xA0) ||
(ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0);
}
// 7.3 Line Terminators
function isLineTerminator(ch) {
return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029);
}
// 7.6 Identifier Names and Identifiers
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch)));
}
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore)
(ch >= 65 && ch <= 90) || // A..Z
(ch >= 97 && ch <= 122) || // a..z
(ch >= 48 && ch <= 57) || // 0..9
(ch === 92) || // \ (backslash)
((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch)));
}
// 7.6.1.2 Future Reserved Words
function isFutureReservedWord(id) {
switch (id) {
case 'class':
case 'enum':
case 'export':
case 'extends':
case 'import':
case 'super':
return true;
default:
return false;
}
}
function isStrictModeReservedWord(id) {
switch (id) {
case 'implements':
case 'interface':
case 'package':
case 'private':
case 'protected':
case 'public':
case 'static':
case 'yield':
case 'let':
return true;
default:
return false;
}
}
function isRestrictedWord(id) {
return id === 'eval' || id === 'arguments';
}
// 7.6.1.1 Keywords
function isKeyword(id) {
if (strict && isStrictModeReservedWord(id)) {
return true;
}
// 'const' is specialized as Keyword in V8.
// 'yield' is only treated as a keyword in strict mode.
// 'let' is for compatiblity with SpiderMonkey and ES.next.
// Some others are from future reserved words.
switch (id.length) {
case 2:
return (id === 'if') || (id === 'in') || (id === 'do');
case 3:
return (id === 'var') || (id === 'for') || (id === 'new') ||
(id === 'try') || (id === 'let');
case 4:
return (id === 'this') || (id === 'else') || (id === 'case') ||
(id === 'void') || (id === 'with') || (id === 'enum');
case 5:
return (id === 'while') || (id === 'break') || (id === 'catch') ||
(id === 'throw') || (id === 'const') ||
(id === 'class') || (id === 'super');
case 6:
return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
(id === 'switch') || (id === 'export') || (id === 'import');
case 7:
return (id === 'default') || (id === 'finally') || (id === 'extends');
case 8:
return (id === 'function') || (id === 'continue') || (id === 'debugger');
case 10:
return (id === 'instanceof');
default:
return false;
}
}
// 7.4 Comments
function addComment(type, value, start, end, loc) {
var comment;
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (state.lastCommentStart >= start) {
return;
}
state.lastCommentStart = start;
comment = {
type: type,
value: value
};
if (extra.range) {
comment.range = [start, end];
}
if (extra.loc) {
comment.loc = loc;
}
extra.comments.push(comment);
if (extra.attachComment) {
extra.leadingComments.push(comment);
extra.trailingComments.push(comment);
}
}
function skipSingleLineComment() {
var start, loc, ch, comment;
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
while (index < length) {
ch = source.charCodeAt(index);
++index;
if (isLineTerminator(ch)) {
if (extra.comments) {
comment = source.slice(start + 2, index - 1);
loc.end = {
line: lineNumber,
column: index - lineStart - 1
};
addComment('Line', comment, start, index - 1, loc);
}
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
return;
}
}
if (extra.comments) {
comment = source.slice(start + 2, index);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Line', comment, start, index, loc);
}
}
function skipMultiLineComment() {
var start, loc, ch, comment;
if (extra.comments) {
start = index - 2;
loc = {
start: {
line: lineNumber,
column: index - lineStart - 2
}
};
}
while (index < length) {
ch = source.charCodeAt(index);
if (isLineTerminator(ch)) {
if (ch === 13 && source.charCodeAt(index + 1) === 10) {
++index;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else if (ch === 42) {
// Block comment ends with '*/' (char #42, char #47).
if (source.charCodeAt(index + 1) === 47) {
++index;
++index;
if (extra.comments) {
comment = source.slice(start + 2, index - 2);
loc.end = {
line: lineNumber,
column: index - lineStart
};
addComment('Block', comment, start, index, loc);
}
return;
}
++index;
} else {
++index;
}
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
function skipComment() {
var ch;
while (index < length) {
ch = source.charCodeAt(index);
if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === 13 && source.charCodeAt(index) === 10) {
++index;
}
++lineNumber;
lineStart = index;
} else if (ch === 47) { // 47 is '/'
ch = source.charCodeAt(index + 1);
if (ch === 47) {
++index;
++index;
skipSingleLineComment();
} else if (ch === 42) { // 42 is '*'
++index;
++index;
skipMultiLineComment();
} else {
break;
}
} else {
break;
}
}
}
function scanHexEscape(prefix) {
var i, len, ch, code = 0;
len = (prefix === 'u') ? 4 : 2;
for (i = 0; i < len; ++i) {
if (index < length && isHexDigit(source[index])) {
ch = source[index++];
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
} else {
return '';
}
}
return String.fromCharCode(code);
}
function scanUnicodeCodePointEscape() {
var ch, code, cu1, cu2;
ch = source[index];
code = 0;
// At least, one hex digit is required.
if (ch === '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
while (index < length) {
ch = source[index++];
if (!isHexDigit(ch)) {
break;
}
code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
}
if (code > 0x10FFFF || ch !== '}') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// UTF-16 Encoding
if (code <= 0xFFFF) {
return String.fromCharCode(code);
}
cu1 = ((code - 0x10000) >> 10) + 0xD800;
cu2 = ((code - 0x10000) & 1023) + 0xDC00;
return String.fromCharCode(cu1, cu2);
}
function getEscapedIdentifier() {
var ch, id;
ch = source.charCodeAt(index++);
id = String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id = ch;
}
while (index < length) {
ch = source.charCodeAt(index);
if (!isIdentifierPart(ch)) {
break;
}
++index;
id += String.fromCharCode(ch);
// '\u' (char #92, char #117) denotes an escaped character.
if (ch === 92) {
id = id.substr(0, id.length - 1);
if (source.charCodeAt(index) !== 117) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
ch = scanHexEscape('u');
if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
id += ch;
}
}
return id;
}
function getIdentifier() {
var start, ch;
start = index++;
while (index < length) {
ch = source.charCodeAt(index);
if (ch === 92) {
// Blackslash (char #92) marks Unicode escape sequence.
index = start;
return getEscapedIdentifier();
}
if (isIdentifierPart(ch)) {
++index;
} else {
break;
}
}
return source.slice(start, index);
}
function scanIdentifier() {
var start, id, type;
start = index;
// Backslash (char #92) starts an escaped character.
id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier();
// There is no keyword or literal with only one character.
// Thus, it must be an identifier.
if (id.length === 1) {
type = Token.Identifier;
} else if (isKeyword(id)) {
type = Token.Keyword;
} else if (id === 'null') {
type = Token.NullLiteral;
} else if (id === 'true' || id === 'false') {
type = Token.BooleanLiteral;
} else {
type = Token.Identifier;
}
return {
type: type,
value: id,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.7 Punctuators
function scanPunctuator() {
var start = index,
code = source.charCodeAt(index),
code2,
ch1 = source[index],
ch2,
ch3,
ch4;
if (state.inJSXTag || state.inJSXChild) {
// Don't need to check for '{' and '}' as it's already handled
// correctly by default.
switch (code) {
case 60: // <
case 62: // >
++index;
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
switch (code) {
// Check for most common single-character punctuators.
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
++index;
if (extra.tokenize) {
if (code === 40) {
extra.openParenToken = extra.tokens.length;
} else if (code === 123) {
extra.openCurlyToken = extra.tokens.length;
}
}
return {
type: Token.Punctuator,
value: String.fromCharCode(code),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
code2 = source.charCodeAt(index + 1);
// '=' (char #61) marks an assignment or comparison operator.
if (code2 === 61) {
switch (code) {
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
index += 2;
return {
type: Token.Punctuator,
value: String.fromCharCode(code) + String.fromCharCode(code2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
case 33: // !
case 61: // =
index += 2;
// !== and ===
if (source.charCodeAt(index) === 61) {
++index;
}
return {
type: Token.Punctuator,
value: source.slice(start, index),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
default:
break;
}
}
break;
}
// Peek more characters.
ch2 = source[index + 1];
ch3 = source[index + 2];
ch4 = source[index + 3];
// 4-character punctuator: >>>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
if (ch4 === '=') {
index += 4;
return {
type: Token.Punctuator,
value: '>>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
}
// 3-character punctuators: === !== >>> <<= >>=
if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) {
index += 3;
return {
type: Token.Punctuator,
value: '>>>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '<<=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
index += 3;
return {
type: Token.Punctuator,
value: '>>=',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.' && ch2 === '.' && ch3 === '.') {
index += 3;
return {
type: Token.Punctuator,
value: '...',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// Other 2-character punctuators: ++ -- << >> && ||
// Don't match these tokens if we're in a type, since they never can
// occur and can mess up types like Map<string, Array<string>>
if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) {
index += 2;
return {
type: Token.Punctuator,
value: ch1 + ch2,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '=' && ch2 === '>') {
index += 2;
return {
type: Token.Punctuator,
value: '=>',
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
if (ch1 === '.') {
++index;
return {
type: Token.Punctuator,
value: ch1,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
// 7.8.3 Numeric Literals
function scanHexLiteral(start) {
var number = '';
while (index < length) {
if (!isHexDigit(source[index])) {
break;
}
number += source[index++];
}
if (number.length === 0) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt('0x' + number, 16),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanBinaryLiteral(start) {
var ch, number;
number = '';
while (index < length) {
ch = source[index];
if (ch !== '0' && ch !== '1') {
break;
}
number += source[index++];
}
if (number.length === 0) {
// only 0b or 0B
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (index < length) {
ch = source.charCodeAt(index);
/* istanbul ignore else */
if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 2),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanOctalLiteral(prefix, start) {
var number, octal;
if (isOctalDigit(prefix)) {
octal = true;
number = '0' + source[index++];
} else {
octal = false;
++index;
number = '';
}
while (index < length) {
if (!isOctalDigit(source[index])) {
break;
}
number += source[index++];
}
if (!octal && number.length === 0) {
// only 0o or 0O
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseInt(number, 8),
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanNumericLiteral() {
var number, start, ch;
ch = source[index];
assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'),
'Numeric literal must start with a decimal digit or a decimal point');
start = index;
number = '';
if (ch !== '.') {
number = source[index++];
ch = source[index];
// Hex number starts with '0x'.
// Octal number starts with '0'.
// Octal number in ES6 starts with '0o'.
// Binary number in ES6 starts with '0b'.
if (number === '0') {
if (ch === 'x' || ch === 'X') {
++index;
return scanHexLiteral(start);
}
if (ch === 'b' || ch === 'B') {
++index;
return scanBinaryLiteral(start);
}
if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
return scanOctalLiteral(ch, start);
}
// decimal number starts with '0' such as '09' is illegal.
if (ch && isDecimalDigit(ch.charCodeAt(0))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === '.') {
number += source[index++];
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
ch = source[index];
}
if (ch === 'e' || ch === 'E') {
number += source[index++];
ch = source[index];
if (ch === '+' || ch === '-') {
number += source[index++];
}
if (isDecimalDigit(source.charCodeAt(index))) {
while (isDecimalDigit(source.charCodeAt(index))) {
number += source[index++];
}
} else {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
}
if (isIdentifierStart(source.charCodeAt(index))) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.NumericLiteral,
value: parseFloat(number),
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
// 7.8.4 String Literals
function scanStringLiteral() {
var str = '', quote, start, ch, code, unescaped, restore, octal = false;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === quote) {
quote = '';
break;
} else if (ch === '\\') {
ch = source[index++];
if (!ch || !isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
str += '\n';
break;
case 'r':
str += '\r';
break;
case 't':
str += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
str += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
str += unescaped;
} else {
index = restore;
str += ch;
}
}
break;
case 'b':
str += '\b';
break;
case 'f':
str += '\f';
break;
case 'v':
str += '\x0B';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
str += String.fromCharCode(code);
} else {
str += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
break;
} else {
str += ch;
}
}
if (quote !== '') {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.StringLiteral,
value: str,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplate() {
var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal;
terminated = false;
tail = false;
start = index;
++index;
while (index < length) {
ch = source[index++];
if (ch === '`') {
tail = true;
terminated = true;
break;
} else if (ch === '$') {
if (source[index] === '{') {
++index;
terminated = true;
break;
}
cooked += ch;
} else if (ch === '\\') {
ch = source[index++];
if (!isLineTerminator(ch.charCodeAt(0))) {
switch (ch) {
case 'n':
cooked += '\n';
break;
case 'r':
cooked += '\r';
break;
case 't':
cooked += '\t';
break;
case 'u':
case 'x':
if (source[index] === '{') {
++index;
cooked += scanUnicodeCodePointEscape();
} else {
restore = index;
unescaped = scanHexEscape(ch);
if (unescaped) {
cooked += unescaped;
} else {
index = restore;
cooked += ch;
}
}
break;
case 'b':
cooked += '\b';
break;
case 'f':
cooked += '\f';
break;
case 'v':
cooked += '\v';
break;
default:
if (isOctalDigit(ch)) {
code = '01234567'.indexOf(ch);
// \0 is not octal escape sequence
if (code !== 0) {
octal = true;
}
/* istanbul ignore else */
if (index < length && isOctalDigit(source[index])) {
octal = true;
code = code * 8 + '01234567'.indexOf(source[index++]);
// 3 digits are only allowed when string starts
// with 0, 1, 2, 3
if ('0123'.indexOf(ch) >= 0 &&
index < length &&
isOctalDigit(source[index])) {
code = code * 8 + '01234567'.indexOf(source[index++]);
}
}
cooked += String.fromCharCode(code);
} else {
cooked += ch;
}
break;
}
} else {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
}
} else if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
if (ch === '\r' && source[index] === '\n') {
++index;
}
lineStart = index;
cooked += '\n';
} else {
cooked += ch;
}
}
if (!terminated) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
return {
type: Token.Template,
value: {
cooked: cooked,
raw: source.slice(start + 1, index - ((tail) ? 1 : 2))
},
tail: tail,
octal: octal,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanTemplateElement(option) {
var startsWith, template;
lookahead = null;
skipComment();
startsWith = (option.head) ? '`' : '}';
if (source[index] !== startsWith) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
template = scanTemplate();
peek();
return template;
}
function testRegExp(pattern, flags) {
var tmp = pattern,
value;
if (flags.indexOf('u') >= 0) {
// Replace each astral symbol and every Unicode code point
// escape sequence with a single ASCII symbol to avoid throwing on
// regular expressions that are only valid in combination with the
// `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it
// would be replaced by `[x-b]` which throws an error.
tmp = tmp
.replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) {
if (parseInt($1, 16) <= 0x10FFFF) {
return 'x';
}
throwError({}, Messages.InvalidRegExp);
})
.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x');
}
// First, detect invalid regular expressions.
try {
value = new RegExp(tmp);
} catch (e) {
throwError({}, Messages.InvalidRegExp);
}
// Return a regular expression object for this pattern-flag pair, or
// `null` in case the current environment doesn't support the flags it
// uses.
try {
return new RegExp(pattern, flags);
} catch (exception) {
return null;
}
}
function scanRegExpBody() {
var ch, str, classMarker, terminated, body;
ch = source[index];
assert(ch === '/', 'Regular expression literal must start with a slash');
str = source[index++];
classMarker = false;
terminated = false;
while (index < length) {
ch = source[index++];
str += ch;
if (ch === '\\') {
ch = source[index++];
// ECMA-262 7.8.5
if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
}
str += ch;
} else if (isLineTerminator(ch.charCodeAt(0))) {
throwError({}, Messages.UnterminatedRegExp);
} else if (classMarker) {
if (ch === ']') {
classMarker = false;
}
} else {
if (ch === '/') {
terminated = true;
break;
} else if (ch === '[') {
classMarker = true;
}
}
}
if (!terminated) {
throwError({}, Messages.UnterminatedRegExp);
}
// Exclude leading and trailing slash.
body = str.substr(1, str.length - 2);
return {
value: body,
literal: str
};
}
function scanRegExpFlags() {
var ch, str, flags, restore;
str = '';
flags = '';
while (index < length) {
ch = source[index];
if (!isIdentifierPart(ch.charCodeAt(0))) {
break;
}
++index;
if (ch === '\\' && index < length) {
ch = source[index];
if (ch === 'u') {
++index;
restore = index;
ch = scanHexEscape('u');
if (ch) {
flags += ch;
for (str += '\\u'; restore < index; ++restore) {
str += source[restore];
}
} else {
index = restore;
flags += 'u';
str += '\\u';
}
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
} else {
str += '\\';
throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
flags += ch;
str += ch;
}
}
return {
value: flags,
literal: str
};
}
function scanRegExp() {
var start, body, flags, value;
lookahead = null;
skipComment();
start = index;
body = scanRegExpBody();
flags = scanRegExpFlags();
value = testRegExp(body.value, flags.value);
if (extra.tokenize) {
return {
type: Token.RegularExpression,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
return {
literal: body.literal + flags.literal,
value: value,
regex: {
pattern: body.value,
flags: flags.value
},
range: [start, index]
};
}
function isIdentifierName(token) {
return token.type === Token.Identifier ||
token.type === Token.Keyword ||
token.type === Token.BooleanLiteral ||
token.type === Token.NullLiteral;
}
function advanceSlash() {
var prevToken,
checkToken;
// Using the following algorithm:
// https://github.com/mozilla/sweet.js/wiki/design
prevToken = extra.tokens[extra.tokens.length - 1];
if (!prevToken) {
// Nothing before that: it cannot be a division.
return scanRegExp();
}
if (prevToken.type === 'Punctuator') {
if (prevToken.value === ')') {
checkToken = extra.tokens[extra.openParenToken - 1];
if (checkToken &&
checkToken.type === 'Keyword' &&
(checkToken.value === 'if' ||
checkToken.value === 'while' ||
checkToken.value === 'for' ||
checkToken.value === 'with')) {
return scanRegExp();
}
return scanPunctuator();
}
if (prevToken.value === '}') {
// Dividing a function by anything makes little sense,
// but we have to check for that.
if (extra.tokens[extra.openCurlyToken - 3] &&
extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') {
// Anonymous function.
checkToken = extra.tokens[extra.openCurlyToken - 4];
if (!checkToken) {
return scanPunctuator();
}
} else if (extra.tokens[extra.openCurlyToken - 4] &&
extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') {
// Named function.
checkToken = extra.tokens[extra.openCurlyToken - 5];
if (!checkToken) {
return scanRegExp();
}
} else {
return scanPunctuator();
}
// checkToken determines whether the function is
// a declaration or an expression.
if (FnExprTokens.indexOf(checkToken.value) >= 0) {
// It is an expression.
return scanPunctuator();
}
// It is a declaration.
return scanRegExp();
}
return scanRegExp();
}
if (prevToken.type === 'Keyword' && prevToken.value !== 'this') {
return scanRegExp();
}
return scanPunctuator();
}
function advance() {
var ch;
if (!state.inJSXChild) {
skipComment();
}
if (index >= length) {
return {
type: Token.EOF,
lineNumber: lineNumber,
lineStart: lineStart,
range: [index, index]
};
}
if (state.inJSXChild) {
return advanceJSXChild();
}
ch = source.charCodeAt(index);
// Very common: ( and ) and ;
if (ch === 40 || ch === 41 || ch === 58) {
return scanPunctuator();
}
// String literal starts with single quote (#39) or double quote (#34).
if (ch === 39 || ch === 34) {
if (state.inJSXTag) {
return scanJSXStringLiteral();
}
return scanStringLiteral();
}
if (state.inJSXTag && isJSXIdentifierStart(ch)) {
return scanJSXIdentifier();
}
if (ch === 96) {
return scanTemplate();
}
if (isIdentifierStart(ch)) {
return scanIdentifier();
}
// Dot (.) char #46 can also start a floating-point number, hence the need
// to check the next character.
if (ch === 46) {
if (isDecimalDigit(source.charCodeAt(index + 1))) {
return scanNumericLiteral();
}
return scanPunctuator();
}
if (isDecimalDigit(ch)) {
return scanNumericLiteral();
}
// Slash (/) char #47 can also start a regex.
if (extra.tokenize && ch === 47) {
return advanceSlash();
}
return scanPunctuator();
}
function lex() {
var token;
token = lookahead;
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = advance();
index = token.range[1];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
return token;
}
function peek() {
var pos, line, start;
pos = index;
line = lineNumber;
start = lineStart;
lookahead = advance();
index = pos;
lineNumber = line;
lineStart = start;
}
function lookahead2() {
var adv, pos, line, start, result;
// If we are collecting the tokens, don't grab the next one yet.
/* istanbul ignore next */
adv = (typeof extra.advance === 'function') ? extra.advance : advance;
pos = index;
line = lineNumber;
start = lineStart;
// Scan for the next immediate token.
/* istanbul ignore if */
if (lookahead === null) {
lookahead = adv();
}
index = lookahead.range[1];
lineNumber = lookahead.lineNumber;
lineStart = lookahead.lineStart;
// Grab the token right after.
result = adv();
index = pos;
lineNumber = line;
lineStart = start;
return result;
}
function rewind(token) {
index = token.range[0];
lineNumber = token.lineNumber;
lineStart = token.lineStart;
lookahead = token;
}
function markerCreate() {
if (!extra.loc && !extra.range) {
return undefined;
}
skipComment();
return {offset: index, line: lineNumber, col: index - lineStart};
}
function markerCreatePreserveWhitespace() {
if (!extra.loc && !extra.range) {
return undefined;
}
return {offset: index, line: lineNumber, col: index - lineStart};
}
function processComment(node) {
var lastChild,
trailingComments,
bottomRight = extra.bottomRightStack,
last = bottomRight[bottomRight.length - 1];
if (node.type === Syntax.Program) {
/* istanbul ignore else */
if (node.body.length > 0) {
return;
}
}
if (extra.trailingComments.length > 0) {
if (extra.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = extra.trailingComments;
extra.trailingComments = [];
} else {
extra.trailingComments.length = 0;
}
} else {
if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) {
trailingComments = last.trailingComments;
delete last.trailingComments;
}
}
// Eating the stack.
if (last) {
while (last && last.range[0] >= node.range[0]) {
lastChild = last;
last = bottomRight.pop();
}
}
if (lastChild) {
if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = lastChild.leadingComments;
delete lastChild.leadingComments;
}
} else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) {
node.leadingComments = extra.leadingComments;
extra.leadingComments = [];
}
if (trailingComments) {
node.trailingComments = trailingComments;
}
bottomRight.push(node);
}
function markerApply(marker, node) {
if (extra.range) {
node.range = [marker.offset, index];
}
if (extra.loc) {
node.loc = {
start: {
line: marker.line,
column: marker.col
},
end: {
line: lineNumber,
column: index - lineStart
}
};
node = delegate.postProcess(node);
}
if (extra.attachComment) {
processComment(node);
}
return node;
}
SyntaxTreeDelegate = {
name: 'SyntaxTree',
postProcess: function (node) {
return node;
},
createArrayExpression: function (elements) {
return {
type: Syntax.ArrayExpression,
elements: elements
};
},
createAssignmentExpression: function (operator, left, right) {
return {
type: Syntax.AssignmentExpression,
operator: operator,
left: left,
right: right
};
},
createBinaryExpression: function (operator, left, right) {
var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression :
Syntax.BinaryExpression;
return {
type: type,
operator: operator,
left: left,
right: right
};
},
createBlockStatement: function (body) {
return {
type: Syntax.BlockStatement,
body: body
};
},
createBreakStatement: function (label) {
return {
type: Syntax.BreakStatement,
label: label
};
},
createCallExpression: function (callee, args) {
return {
type: Syntax.CallExpression,
callee: callee,
'arguments': args
};
},
createCatchClause: function (param, body) {
return {
type: Syntax.CatchClause,
param: param,
body: body
};
},
createConditionalExpression: function (test, consequent, alternate) {
return {
type: Syntax.ConditionalExpression,
test: test,
consequent: consequent,
alternate: alternate
};
},
createContinueStatement: function (label) {
return {
type: Syntax.ContinueStatement,
label: label
};
},
createDebuggerStatement: function () {
return {
type: Syntax.DebuggerStatement
};
},
createDoWhileStatement: function (body, test) {
return {
type: Syntax.DoWhileStatement,
body: body,
test: test
};
},
createEmptyStatement: function () {
return {
type: Syntax.EmptyStatement
};
},
createExpressionStatement: function (expression) {
return {
type: Syntax.ExpressionStatement,
expression: expression
};
},
createForStatement: function (init, test, update, body) {
return {
type: Syntax.ForStatement,
init: init,
test: test,
update: update,
body: body
};
},
createForInStatement: function (left, right, body) {
return {
type: Syntax.ForInStatement,
left: left,
right: right,
body: body,
each: false
};
},
createForOfStatement: function (left, right, body) {
return {
type: Syntax.ForOfStatement,
left: left,
right: right,
body: body
};
},
createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funDecl = {
type: Syntax.FunctionDeclaration,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funDecl.async = true;
}
return funDecl;
},
createFunctionExpression: function (id, params, defaults, body, rest, generator, expression,
isAsync, returnType, typeParameters) {
var funExpr = {
type: Syntax.FunctionExpression,
id: id,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: generator,
expression: expression,
returnType: returnType,
typeParameters: typeParameters
};
if (isAsync) {
funExpr.async = true;
}
return funExpr;
},
createIdentifier: function (name) {
return {
type: Syntax.Identifier,
name: name,
// Only here to initialize the shape of the object to ensure
// that the 'typeAnnotation' key is ordered before others that
// are added later (like 'loc' and 'range'). This just helps
// keep the shape of Identifier nodes consistent with everything
// else.
typeAnnotation: undefined,
optional: undefined
};
},
createTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.TypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createTypeCast: function (expression, typeAnnotation) {
return {
type: Syntax.TypeCastExpression,
expression: expression,
typeAnnotation: typeAnnotation
};
},
createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) {
return {
type: Syntax.FunctionTypeAnnotation,
params: params,
returnType: returnType,
rest: rest,
typeParameters: typeParameters
};
},
createFunctionTypeParam: function (name, typeAnnotation, optional) {
return {
type: Syntax.FunctionTypeParam,
name: name,
typeAnnotation: typeAnnotation,
optional: optional
};
},
createNullableTypeAnnotation: function (typeAnnotation) {
return {
type: Syntax.NullableTypeAnnotation,
typeAnnotation: typeAnnotation
};
},
createArrayTypeAnnotation: function (elementType) {
return {
type: Syntax.ArrayTypeAnnotation,
elementType: elementType
};
},
createGenericTypeAnnotation: function (id, typeParameters) {
return {
type: Syntax.GenericTypeAnnotation,
id: id,
typeParameters: typeParameters
};
},
createQualifiedTypeIdentifier: function (qualification, id) {
return {
type: Syntax.QualifiedTypeIdentifier,
qualification: qualification,
id: id
};
},
createTypeParameterDeclaration: function (params) {
return {
type: Syntax.TypeParameterDeclaration,
params: params
};
},
createTypeParameterInstantiation: function (params) {
return {
type: Syntax.TypeParameterInstantiation,
params: params
};
},
createAnyTypeAnnotation: function () {
return {
type: Syntax.AnyTypeAnnotation
};
},
createBooleanTypeAnnotation: function () {
return {
type: Syntax.BooleanTypeAnnotation
};
},
createNumberTypeAnnotation: function () {
return {
type: Syntax.NumberTypeAnnotation
};
},
createStringTypeAnnotation: function () {
return {
type: Syntax.StringTypeAnnotation
};
},
createStringLiteralTypeAnnotation: function (token) {
return {
type: Syntax.StringLiteralTypeAnnotation,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createVoidTypeAnnotation: function () {
return {
type: Syntax.VoidTypeAnnotation
};
},
createTypeofTypeAnnotation: function (argument) {
return {
type: Syntax.TypeofTypeAnnotation,
argument: argument
};
},
createTupleTypeAnnotation: function (types) {
return {
type: Syntax.TupleTypeAnnotation,
types: types
};
},
createObjectTypeAnnotation: function (properties, indexers, callProperties) {
return {
type: Syntax.ObjectTypeAnnotation,
properties: properties,
indexers: indexers,
callProperties: callProperties
};
},
createObjectTypeIndexer: function (id, key, value, isStatic) {
return {
type: Syntax.ObjectTypeIndexer,
id: id,
key: key,
value: value,
"static": isStatic
};
},
createObjectTypeCallProperty: function (value, isStatic) {
return {
type: Syntax.ObjectTypeCallProperty,
value: value,
"static": isStatic
};
},
createObjectTypeProperty: function (key, value, optional, isStatic) {
return {
type: Syntax.ObjectTypeProperty,
key: key,
value: value,
optional: optional,
"static": isStatic
};
},
createUnionTypeAnnotation: function (types) {
return {
type: Syntax.UnionTypeAnnotation,
types: types
};
},
createIntersectionTypeAnnotation: function (types) {
return {
type: Syntax.IntersectionTypeAnnotation,
types: types
};
},
createTypeAlias: function (id, typeParameters, right) {
return {
type: Syntax.TypeAlias,
id: id,
typeParameters: typeParameters,
right: right
};
},
createInterface: function (id, typeParameters, body, extended) {
return {
type: Syntax.InterfaceDeclaration,
id: id,
typeParameters: typeParameters,
body: body,
"extends": extended
};
},
createInterfaceExtends: function (id, typeParameters) {
return {
type: Syntax.InterfaceExtends,
id: id,
typeParameters: typeParameters
};
},
createDeclareFunction: function (id) {
return {
type: Syntax.DeclareFunction,
id: id
};
},
createDeclareVariable: function (id) {
return {
type: Syntax.DeclareVariable,
id: id
};
},
createDeclareModule: function (id, body) {
return {
type: Syntax.DeclareModule,
id: id,
body: body
};
},
createJSXAttribute: function (name, value) {
return {
type: Syntax.JSXAttribute,
name: name,
value: value || null
};
},
createJSXSpreadAttribute: function (argument) {
return {
type: Syntax.JSXSpreadAttribute,
argument: argument
};
},
createJSXIdentifier: function (name) {
return {
type: Syntax.JSXIdentifier,
name: name
};
},
createJSXNamespacedName: function (namespace, name) {
return {
type: Syntax.JSXNamespacedName,
namespace: namespace,
name: name
};
},
createJSXMemberExpression: function (object, property) {
return {
type: Syntax.JSXMemberExpression,
object: object,
property: property
};
},
createJSXElement: function (openingElement, closingElement, children) {
return {
type: Syntax.JSXElement,
openingElement: openingElement,
closingElement: closingElement,
children: children
};
},
createJSXEmptyExpression: function () {
return {
type: Syntax.JSXEmptyExpression
};
},
createJSXExpressionContainer: function (expression) {
return {
type: Syntax.JSXExpressionContainer,
expression: expression
};
},
createJSXOpeningElement: function (name, attributes, selfClosing) {
return {
type: Syntax.JSXOpeningElement,
name: name,
selfClosing: selfClosing,
attributes: attributes
};
},
createJSXClosingElement: function (name) {
return {
type: Syntax.JSXClosingElement,
name: name
};
},
createIfStatement: function (test, consequent, alternate) {
return {
type: Syntax.IfStatement,
test: test,
consequent: consequent,
alternate: alternate
};
},
createLabeledStatement: function (label, body) {
return {
type: Syntax.LabeledStatement,
label: label,
body: body
};
},
createLiteral: function (token) {
var object = {
type: Syntax.Literal,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
if (token.regex) {
object.regex = token.regex;
}
return object;
},
createMemberExpression: function (accessor, object, property) {
return {
type: Syntax.MemberExpression,
computed: accessor === '[',
object: object,
property: property
};
},
createNewExpression: function (callee, args) {
return {
type: Syntax.NewExpression,
callee: callee,
'arguments': args
};
},
createObjectExpression: function (properties) {
return {
type: Syntax.ObjectExpression,
properties: properties
};
},
createPostfixExpression: function (operator, argument) {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: false
};
},
createProgram: function (body) {
return {
type: Syntax.Program,
body: body
};
},
createProperty: function (kind, key, value, method, shorthand, computed) {
return {
type: Syntax.Property,
key: key,
value: value,
kind: kind,
method: method,
shorthand: shorthand,
computed: computed
};
},
createReturnStatement: function (argument) {
return {
type: Syntax.ReturnStatement,
argument: argument
};
},
createSequenceExpression: function (expressions) {
return {
type: Syntax.SequenceExpression,
expressions: expressions
};
},
createSwitchCase: function (test, consequent) {
return {
type: Syntax.SwitchCase,
test: test,
consequent: consequent
};
},
createSwitchStatement: function (discriminant, cases) {
return {
type: Syntax.SwitchStatement,
discriminant: discriminant,
cases: cases
};
},
createThisExpression: function () {
return {
type: Syntax.ThisExpression
};
},
createThrowStatement: function (argument) {
return {
type: Syntax.ThrowStatement,
argument: argument
};
},
createTryStatement: function (block, guardedHandlers, handlers, finalizer) {
return {
type: Syntax.TryStatement,
block: block,
guardedHandlers: guardedHandlers,
handlers: handlers,
finalizer: finalizer
};
},
createUnaryExpression: function (operator, argument) {
if (operator === '++' || operator === '--') {
return {
type: Syntax.UpdateExpression,
operator: operator,
argument: argument,
prefix: true
};
}
return {
type: Syntax.UnaryExpression,
operator: operator,
argument: argument,
prefix: true
};
},
createVariableDeclaration: function (declarations, kind) {
return {
type: Syntax.VariableDeclaration,
declarations: declarations,
kind: kind
};
},
createVariableDeclarator: function (id, init) {
return {
type: Syntax.VariableDeclarator,
id: id,
init: init
};
},
createWhileStatement: function (test, body) {
return {
type: Syntax.WhileStatement,
test: test,
body: body
};
},
createWithStatement: function (object, body) {
return {
type: Syntax.WithStatement,
object: object,
body: body
};
},
createTemplateElement: function (value, tail) {
return {
type: Syntax.TemplateElement,
value: value,
tail: tail
};
},
createTemplateLiteral: function (quasis, expressions) {
return {
type: Syntax.TemplateLiteral,
quasis: quasis,
expressions: expressions
};
},
createSpreadElement: function (argument) {
return {
type: Syntax.SpreadElement,
argument: argument
};
},
createSpreadProperty: function (argument) {
return {
type: Syntax.SpreadProperty,
argument: argument
};
},
createTaggedTemplateExpression: function (tag, quasi) {
return {
type: Syntax.TaggedTemplateExpression,
tag: tag,
quasi: quasi
};
},
createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) {
var arrowExpr = {
type: Syntax.ArrowFunctionExpression,
id: null,
params: params,
defaults: defaults,
body: body,
rest: rest,
generator: false,
expression: expression
};
if (isAsync) {
arrowExpr.async = true;
}
return arrowExpr;
},
createMethodDefinition: function (propertyType, kind, key, value, computed) {
return {
type: Syntax.MethodDefinition,
key: key,
value: value,
kind: kind,
'static': propertyType === ClassPropertyType["static"],
computed: computed
};
},
createClassProperty: function (key, typeAnnotation, computed, isStatic) {
return {
type: Syntax.ClassProperty,
key: key,
typeAnnotation: typeAnnotation,
computed: computed,
"static": isStatic
};
},
createClassBody: function (body) {
return {
type: Syntax.ClassBody,
body: body
};
},
createClassImplements: function (id, typeParameters) {
return {
type: Syntax.ClassImplements,
id: id,
typeParameters: typeParameters
};
},
createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassExpression,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) {
return {
type: Syntax.ClassDeclaration,
id: id,
superClass: superClass,
body: body,
typeParameters: typeParameters,
superTypeParameters: superTypeParameters,
"implements": implemented
};
},
createModuleSpecifier: function (token) {
return {
type: Syntax.ModuleSpecifier,
value: token.value,
raw: source.slice(token.range[0], token.range[1])
};
},
createExportSpecifier: function (id, name) {
return {
type: Syntax.ExportSpecifier,
id: id,
name: name
};
},
createExportBatchSpecifier: function () {
return {
type: Syntax.ExportBatchSpecifier
};
},
createImportDefaultSpecifier: function (id) {
return {
type: Syntax.ImportDefaultSpecifier,
id: id
};
},
createImportNamespaceSpecifier: function (id) {
return {
type: Syntax.ImportNamespaceSpecifier,
id: id
};
},
createExportDeclaration: function (isDefault, declaration, specifiers, src) {
return {
type: Syntax.ExportDeclaration,
'default': !!isDefault,
declaration: declaration,
specifiers: specifiers,
source: src
};
},
createImportSpecifier: function (id, name) {
return {
type: Syntax.ImportSpecifier,
id: id,
name: name
};
},
createImportDeclaration: function (specifiers, src, isType) {
return {
type: Syntax.ImportDeclaration,
specifiers: specifiers,
source: src,
isType: isType
};
},
createYieldExpression: function (argument, dlg) {
return {
type: Syntax.YieldExpression,
argument: argument,
delegate: dlg
};
},
createAwaitExpression: function (argument) {
return {
type: Syntax.AwaitExpression,
argument: argument
};
},
createComprehensionExpression: function (filter, blocks, body) {
return {
type: Syntax.ComprehensionExpression,
filter: filter,
blocks: blocks,
body: body
};
}
};
// Return true if there is a line terminator before the next token.
function peekLineTerminator() {
var pos, line, start, found;
pos = index;
line = lineNumber;
start = lineStart;
skipComment();
found = lineNumber !== line;
index = pos;
lineNumber = line;
lineStart = start;
return found;
}
// Throw an exception
function throwError(token, messageFormat) {
var error,
args = Array.prototype.slice.call(arguments, 2),
msg = messageFormat.replace(
/%(\d)/g,
function (whole, idx) {
assert(idx < args.length, 'Message reference must be in range');
return args[idx];
}
);
if (typeof token.lineNumber === 'number') {
error = new Error('Line ' + token.lineNumber + ': ' + msg);
error.index = token.range[0];
error.lineNumber = token.lineNumber;
error.column = token.range[0] - lineStart + 1;
} else {
error = new Error('Line ' + lineNumber + ': ' + msg);
error.index = index;
error.lineNumber = lineNumber;
error.column = index - lineStart + 1;
}
error.description = msg;
throw error;
}
function throwErrorTolerant() {
try {
throwError.apply(null, arguments);
} catch (e) {
if (extra.errors) {
extra.errors.push(e);
} else {
throw e;
}
}
}
// Throw an exception because of the token.
function throwUnexpected(token) {
if (token.type === Token.EOF) {
throwError(token, Messages.UnexpectedEOS);
}
if (token.type === Token.NumericLiteral) {
throwError(token, Messages.UnexpectedNumber);
}
if (token.type === Token.StringLiteral || token.type === Token.JSXText) {
throwError(token, Messages.UnexpectedString);
}
if (token.type === Token.Identifier) {
throwError(token, Messages.UnexpectedIdentifier);
}
if (token.type === Token.Keyword) {
if (isFutureReservedWord(token.value)) {
throwError(token, Messages.UnexpectedReserved);
} else if (strict && isStrictModeReservedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictReservedWord);
return;
}
throwError(token, Messages.UnexpectedToken, token.value);
}
if (token.type === Token.Template) {
throwError(token, Messages.UnexpectedTemplate, token.value.raw);
}
// BooleanLiteral, NullLiteral, or Punctuator.
throwError(token, Messages.UnexpectedToken, token.value);
}
// Expect the next token to match the specified punctuator.
// If not, an exception will be thrown.
function expect(value) {
var token = lex();
if (token.type !== Token.Punctuator || token.value !== value) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified keyword.
// If not, an exception will be thrown.
function expectKeyword(keyword, contextual) {
var token = lex();
if (token.type !== (contextual ? Token.Identifier : Token.Keyword) ||
token.value !== keyword) {
throwUnexpected(token);
}
}
// Expect the next token to match the specified contextual keyword.
// If not, an exception will be thrown.
function expectContextualKeyword(keyword) {
return expectKeyword(keyword, true);
}
// Return true if the next token matches the specified punctuator.
function match(value) {
return lookahead.type === Token.Punctuator && lookahead.value === value;
}
// Return true if the next token matches the specified keyword
function matchKeyword(keyword, contextual) {
var expectedType = contextual ? Token.Identifier : Token.Keyword;
return lookahead.type === expectedType && lookahead.value === keyword;
}
// Return true if the next token matches the specified contextual keyword
function matchContextualKeyword(keyword) {
return matchKeyword(keyword, true);
}
// Return true if the next token is an assignment operator
function matchAssign() {
var op;
if (lookahead.type !== Token.Punctuator) {
return false;
}
op = lookahead.value;
return op === '=' ||
op === '*=' ||
op === '/=' ||
op === '%=' ||
op === '+=' ||
op === '-=' ||
op === '<<=' ||
op === '>>=' ||
op === '>>>=' ||
op === '&=' ||
op === '^=' ||
op === '|=';
}
// Note that 'yield' is treated as a keyword in strict mode, but a
// contextual keyword (identifier) in non-strict mode, so we need to
// use matchKeyword('yield', false) and matchKeyword('yield', true)
// (i.e. matchContextualKeyword) appropriately.
function matchYield() {
return state.yieldAllowed && matchKeyword('yield', !strict);
}
function matchAsync() {
var backtrackToken = lookahead, matches = false;
if (matchContextualKeyword('async')) {
lex(); // Make sure peekLineTerminator() starts after 'async'.
matches = !peekLineTerminator();
rewind(backtrackToken); // Revert the lex().
}
return matches;
}
function matchAwait() {
return state.awaitAllowed && matchContextualKeyword('await');
}
function consumeSemicolon() {
var line, oldIndex = index, oldLineNumber = lineNumber,
oldLineStart = lineStart, oldLookahead = lookahead;
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
return;
}
line = lineNumber;
skipComment();
if (lineNumber !== line) {
index = oldIndex;
lineNumber = oldLineNumber;
lineStart = oldLineStart;
lookahead = oldLookahead;
return;
}
if (match(';')) {
lex();
return;
}
if (lookahead.type !== Token.EOF && !match('}')) {
throwUnexpected(lookahead);
}
}
// Return true if provided expression is LeftHandSideExpression
function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
}
function isAssignableLeftHandSide(expr) {
return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
}
// 11.1.4 Array Initialiser
function parseArrayInitialiser() {
var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true,
marker = markerCreate();
expect('[');
while (!match(']')) {
if (lookahead.value === 'for' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
matchKeyword('for');
tmp = parseForStatement({ignoreBody: true});
tmp.of = tmp.type === Syntax.ForOfStatement;
tmp.type = Syntax.ComprehensionBlock;
if (tmp.left.kind) { // can't be let or const
throwError({}, Messages.ComprehensionError);
}
blocks.push(tmp);
} else if (lookahead.value === 'if' &&
lookahead.type === Token.Keyword) {
if (!possiblecomprehension) {
throwError({}, Messages.ComprehensionError);
}
expectKeyword('if');
expect('(');
filter = parseExpression();
expect(')');
} else if (lookahead.value === ',' &&
lookahead.type === Token.Punctuator) {
possiblecomprehension = false; // no longer allowed.
lex();
elements.push(null);
} else {
tmp = parseSpreadOrAssignmentExpression();
elements.push(tmp);
if (tmp && tmp.type === Syntax.SpreadElement) {
if (!match(']')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
} else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) {
expect(','); // this lexes.
possiblecomprehension = false;
}
}
}
expect(']');
if (filter && !blocks.length) {
throwError({}, Messages.ComprehensionRequiresBlock);
}
if (blocks.length) {
if (elements.length !== 1) {
throwError({}, Messages.ComprehensionError);
}
return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0]));
}
return markerApply(marker, delegate.createArrayExpression(elements));
}
// 11.1.5 Object Initialiser
function parsePropertyFunction(options) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed,
params, defaults, body, marker = markerCreate();
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = options.generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = options.async;
params = options.params || [];
defaults = options.defaults || [];
body = parseConciseBody();
if (options.name && strict && isRestrictedWord(params[0].name)) {
throwErrorTolerant(options.name, Messages.StrictParamName);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createFunctionExpression(
null,
params,
defaults,
body,
options.rest || null,
options.generator,
body.type !== Syntax.BlockStatement,
options.async,
options.returnType,
options.typeParameters
));
}
function parsePropertyMethodFunction(options) {
var previousStrict, tmp, method;
previousStrict = strict;
strict = true;
tmp = parseParams();
if (tmp.stricted) {
throwErrorTolerant(tmp.stricted, tmp.message);
}
method = parsePropertyFunction({
params: tmp.params,
defaults: tmp.defaults,
rest: tmp.rest,
generator: options.generator,
async: options.async,
returnType: tmp.returnType,
typeParameters: options.typeParameters
});
strict = previousStrict;
return method;
}
function parseObjectPropertyKey() {
var marker = markerCreate(),
token = lex(),
propertyKey,
result;
// Note: This function is called only from parseObjectProperty(), where
// EOF and Punctuator tokens are already filtered out.
if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
if (strict && token.octal) {
throwErrorTolerant(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createLiteral(token));
}
if (token.type === Token.Punctuator && token.value === '[') {
// For computed properties we should skip the [ and ], and
// capture in marker only the assignment expression itself.
marker = markerCreate();
propertyKey = parseAssignmentExpression();
result = markerApply(marker, propertyKey);
expect(']');
return result;
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseObjectProperty() {
var token, key, id, param, computed,
marker = markerCreate(), returnType, typeParameters;
token = lookahead;
computed = (token.value === '[' && token.type === Token.Punctuator);
if (token.type === Token.Identifier || computed || matchAsync()) {
id = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parseAssignmentExpression(),
false,
false,
computed
)
);
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: false,
async: false,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
// Property Assignment: Getter and Setter.
if (token.value === 'get') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'get',
key,
parsePropertyFunction({
generator: false,
async: false,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'set') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return markerApply(
marker,
delegate.createProperty(
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
async: false,
name: token,
returnType: returnType
}),
false,
false,
computed
)
);
}
if (token.value === 'async') {
computed = (lookahead.value === '[');
key = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(
marker,
delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
async: true,
typeParameters: typeParameters
}),
true,
false,
computed
)
);
}
if (computed) {
// Computed properties can only be used with full notation.
throwUnexpected(lookahead);
}
return markerApply(
marker,
delegate.createProperty('init', id, id, false, true, false)
);
}
if (token.type === Token.EOF || token.type === Token.Punctuator) {
if (!match('*')) {
throwUnexpected(token);
}
lex();
computed = (lookahead.type === Token.Punctuator && lookahead.value === '[');
id = parseObjectPropertyKey();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (!match('(')) {
throwUnexpected(lex());
}
return markerApply(marker, delegate.createProperty(
'init',
id,
parsePropertyMethodFunction({
generator: true,
typeParameters: typeParameters
}),
true,
false,
computed
));
}
key = parseObjectPropertyKey();
if (match(':')) {
lex();
return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false));
}
if (match('(') || match('<')) {
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
return markerApply(marker, delegate.createProperty(
'init',
key,
parsePropertyMethodFunction({
generator: false,
typeParameters: typeParameters
}),
true,
false,
false
));
}
throwUnexpected(lex());
}
function parseObjectSpreadProperty() {
var marker = markerCreate();
expect('...');
return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression()));
}
function getFieldName(key) {
var toString = String;
if (key.type === Syntax.Identifier) {
return key.name;
}
return toString(key.value);
}
function parseObjectInitialiser() {
var properties = [], property, name, kind, storedKind, map = new StringMap(),
marker = markerCreate(), toString = String;
expect('{');
while (!match('}')) {
if (match('...')) {
property = parseObjectSpreadProperty();
} else {
property = parseObjectProperty();
if (property.key.type === Syntax.Identifier) {
name = property.key.name;
} else {
name = toString(property.key.value);
}
kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
if (map.has(name)) {
storedKind = map.get(name);
if (storedKind === PropertyKind.Data) {
if (strict && kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.StrictDuplicateProperty);
} else if (kind !== PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
}
} else {
if (kind === PropertyKind.Data) {
throwErrorTolerant({}, Messages.AccessorDataProperty);
} else if (storedKind & kind) {
throwErrorTolerant({}, Messages.AccessorGetSet);
}
}
map.set(name, storedKind | kind);
} else {
map.set(name, kind);
}
}
properties.push(property);
if (!match('}')) {
expect(',');
}
}
expect('}');
return markerApply(marker, delegate.createObjectExpression(properties));
}
function parseTemplateElement(option) {
var marker = markerCreate(),
token = scanTemplateElement(option);
if (strict && token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail));
}
function parseTemplateLiteral() {
var quasi, quasis, expressions, marker = markerCreate();
quasi = parseTemplateElement({ head: true });
quasis = [ quasi ];
expressions = [];
while (!quasi.tail) {
expressions.push(parseExpression());
quasi = parseTemplateElement({ head: false });
quasis.push(quasi);
}
return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions));
}
// 11.1.6 The Grouping Operator
function parseGroupExpression() {
var expr, marker, typeAnnotation;
expect('(');
++state.parenthesizedCount;
marker = markerCreate();
expr = parseExpression();
if (match(':')) {
typeAnnotation = parseTypeAnnotation();
expr = markerApply(marker, delegate.createTypeCast(
expr,
typeAnnotation
));
}
expect(')');
return expr;
}
function matchAsyncFuncExprOrDecl() {
var token;
if (matchAsync()) {
token = lookahead2();
if (token.type === Token.Keyword && token.value === 'function') {
return true;
}
}
return false;
}
// 11.1 Primary Expressions
function parsePrimaryExpression() {
var marker, type, token, expr;
type = lookahead.type;
if (type === Token.Identifier) {
marker = markerCreate();
return markerApply(marker, delegate.createIdentifier(lex().value));
}
if (type === Token.StringLiteral || type === Token.NumericLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
marker = markerCreate();
return markerApply(marker, delegate.createLiteral(lex()));
}
if (type === Token.Keyword) {
if (matchKeyword('this')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createThisExpression());
}
if (matchKeyword('function')) {
return parseFunctionExpression();
}
if (matchKeyword('class')) {
return parseClassExpression();
}
if (matchKeyword('super')) {
marker = markerCreate();
lex();
return markerApply(marker, delegate.createIdentifier('super'));
}
}
if (type === Token.BooleanLiteral) {
marker = markerCreate();
token = lex();
token.value = (token.value === 'true');
return markerApply(marker, delegate.createLiteral(token));
}
if (type === Token.NullLiteral) {
marker = markerCreate();
token = lex();
token.value = null;
return markerApply(marker, delegate.createLiteral(token));
}
if (match('[')) {
return parseArrayInitialiser();
}
if (match('{')) {
return parseObjectInitialiser();
}
if (match('(')) {
return parseGroupExpression();
}
if (match('/') || match('/=')) {
marker = markerCreate();
expr = delegate.createLiteral(scanRegExp());
peek();
return markerApply(marker, expr);
}
if (type === Token.Template) {
return parseTemplateLiteral();
}
if (match('<')) {
return parseJSXElement();
}
throwUnexpected(lex());
}
// 11.2 Left-Hand-Side Expressions
function parseArguments() {
var args = [], arg;
expect('(');
if (!match(')')) {
while (index < length) {
arg = parseSpreadOrAssignmentExpression();
args.push(arg);
if (match(')')) {
break;
} else if (arg.type === Syntax.SpreadElement) {
throwError({}, Messages.ElementAfterSpreadElement);
}
expect(',');
}
}
expect(')');
return args;
}
function parseSpreadOrAssignmentExpression() {
if (match('...')) {
var marker = markerCreate();
lex();
return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression()));
}
return parseAssignmentExpression();
}
function parseNonComputedProperty() {
var marker = markerCreate(),
token = lex();
if (!isIdentifierName(token)) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseNonComputedMember() {
expect('.');
return parseNonComputedProperty();
}
function parseComputedMember() {
var expr;
expect('[');
expr = parseExpression();
expect(']');
return expr;
}
function parseNewExpression() {
var callee, args, marker = markerCreate();
expectKeyword('new');
callee = parseLeftHandSideExpression();
args = match('(') ? parseArguments() : [];
return markerApply(marker, delegate.createNewExpression(callee, args));
}
function parseLeftHandSideExpressionAllowCall() {
var expr, args, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) {
if (match('(')) {
args = parseArguments();
expr = markerApply(marker, delegate.createCallExpression(expr, args));
} else if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
function parseLeftHandSideExpression() {
var expr, marker = markerCreate();
expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
while (match('.') || match('[') || lookahead.type === Token.Template) {
if (match('[')) {
expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember()));
} else if (match('.')) {
expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember()));
} else {
expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()));
}
}
return expr;
}
// 11.3 Postfix Expressions
function parsePostfixExpression() {
var marker = markerCreate(),
expr = parseLeftHandSideExpressionAllowCall(),
token;
if (lookahead.type !== Token.Punctuator) {
return expr;
}
if ((match('++') || match('--')) && !peekLineTerminator()) {
// 11.3.1, 11.3.2
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPostfix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
token = lex();
expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr));
}
return expr;
}
// 11.4 Unary Operators
function parseUnaryExpression() {
var marker, token, expr;
if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) {
return parsePostfixExpression();
}
if (match('++') || match('--')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
// 11.4.4, 11.4.5
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant({}, Messages.StrictLHSPrefix);
}
if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (match('+') || match('-') || match('~') || match('!')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
return markerApply(marker, delegate.createUnaryExpression(token.value, expr));
}
if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
marker = markerCreate();
token = lex();
expr = parseUnaryExpression();
expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr));
if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
throwErrorTolerant({}, Messages.StrictDelete);
}
return expr;
}
return parsePostfixExpression();
}
function binaryPrecedence(token, allowIn) {
var prec = 0;
if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
return 0;
}
switch (token.value) {
case '||':
prec = 1;
break;
case '&&':
prec = 2;
break;
case '|':
prec = 3;
break;
case '^':
prec = 4;
break;
case '&':
prec = 5;
break;
case '==':
case '!=':
case '===':
case '!==':
prec = 6;
break;
case '<':
case '>':
case '<=':
case '>=':
case 'instanceof':
prec = 7;
break;
case 'in':
prec = allowIn ? 7 : 0;
break;
case '<<':
case '>>':
case '>>>':
prec = 8;
break;
case '+':
case '-':
prec = 9;
break;
case '*':
case '/':
case '%':
prec = 11;
break;
default:
break;
}
return prec;
}
// 11.5 Multiplicative Operators
// 11.6 Additive Operators
// 11.7 Bitwise Shift Operators
// 11.8 Relational Operators
// 11.9 Equality Operators
// 11.10 Binary Bitwise Operators
// 11.11 Binary Logical Operators
function parseBinaryExpression() {
var expr, token, prec, previousAllowIn, stack, right, operator, left, i,
marker, markers;
previousAllowIn = state.allowIn;
state.allowIn = true;
marker = markerCreate();
left = parseUnaryExpression();
token = lookahead;
prec = binaryPrecedence(token, previousAllowIn);
if (prec === 0) {
return left;
}
token.prec = prec;
lex();
markers = [marker, markerCreate()];
right = parseUnaryExpression();
stack = [left, token, right];
while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) {
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
operator = stack.pop().value;
left = stack.pop();
expr = delegate.createBinaryExpression(operator, left, right);
markers.pop();
marker = markers.pop();
markerApply(marker, expr);
stack.push(expr);
markers.push(marker);
}
// Shift.
token = lex();
token.prec = prec;
stack.push(token);
markers.push(markerCreate());
expr = parseUnaryExpression();
stack.push(expr);
}
state.allowIn = previousAllowIn;
// Final reduce to clean-up the stack.
i = stack.length - 1;
expr = stack[i];
markers.pop();
while (i > 1) {
expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr);
i -= 2;
marker = markers.pop();
markerApply(marker, expr);
}
return expr;
}
// 11.12 Conditional Operator
function parseConditionalExpression() {
var expr, previousAllowIn, consequent, alternate, marker = markerCreate();
expr = parseBinaryExpression();
if (match('?')) {
lex();
previousAllowIn = state.allowIn;
state.allowIn = true;
consequent = parseAssignmentExpression();
state.allowIn = previousAllowIn;
expect(':');
alternate = parseAssignmentExpression();
expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate));
}
return expr;
}
// 11.13 Assignment Operators
// 12.14.5 AssignmentPattern
function reinterpretAsAssignmentBindingPattern(expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsAssignmentBindingPattern(property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInAssignment);
}
reinterpretAsAssignmentBindingPattern(property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
/* istanbul ignore else */
if (element) {
reinterpretAsAssignmentBindingPattern(element);
}
}
} else if (expr.type === Syntax.Identifier) {
if (isRestrictedWord(expr.name)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
} else if (expr.type === Syntax.SpreadElement) {
reinterpretAsAssignmentBindingPattern(expr.argument);
if (expr.argument.type === Syntax.ObjectPattern) {
throwError({}, Messages.ObjectPatternAsSpread);
}
} else {
/* istanbul ignore else */
if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
throwError({}, Messages.InvalidLHSInAssignment);
}
}
}
// 13.2.3 BindingPattern
function reinterpretAsDestructuredParameter(options, expr) {
var i, len, property, element;
if (expr.type === Syntax.ObjectExpression) {
expr.type = Syntax.ObjectPattern;
for (i = 0, len = expr.properties.length; i < len; i += 1) {
property = expr.properties[i];
if (property.type === Syntax.SpreadProperty) {
if (i < len - 1) {
throwError({}, Messages.PropertyAfterSpreadProperty);
}
reinterpretAsDestructuredParameter(options, property.argument);
} else {
if (property.kind !== 'init') {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, property.value);
}
}
} else if (expr.type === Syntax.ArrayExpression) {
expr.type = Syntax.ArrayPattern;
for (i = 0, len = expr.elements.length; i < len; i += 1) {
element = expr.elements[i];
if (element) {
reinterpretAsDestructuredParameter(options, element);
}
}
} else if (expr.type === Syntax.Identifier) {
validateParam(options, expr, expr.name);
} else if (expr.type === Syntax.SpreadElement) {
// BindingRestElement only allows BindingIdentifier
if (expr.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
validateParam(options, expr.argument, expr.argument.name);
} else {
throwError({}, Messages.InvalidLHSInFormalsList);
}
}
function reinterpretAsCoverFormalsList(expressions) {
var i, len, param, params, defaults, defaultCount, options, rest;
params = [];
defaults = [];
defaultCount = 0;
rest = null;
options = {
paramSet: new StringMap()
};
for (i = 0, len = expressions.length; i < len; i += 1) {
param = expressions[i];
if (param.type === Syntax.Identifier) {
params.push(param);
defaults.push(null);
validateParam(options, param, param.name);
} else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) {
reinterpretAsDestructuredParameter(options, param);
params.push(param);
defaults.push(null);
} else if (param.type === Syntax.SpreadElement) {
assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression');
if (param.argument.type !== Syntax.Identifier) {
throwError({}, Messages.InvalidLHSInFormalsList);
}
reinterpretAsDestructuredParameter(options, param.argument);
rest = param.argument;
} else if (param.type === Syntax.AssignmentExpression) {
params.push(param.left);
defaults.push(param.right);
++defaultCount;
validateParam(options, param.left, param.left.name);
} else {
return null;
}
}
if (options.message === Messages.StrictParamDupe) {
throwError(
strict ? options.stricted : options.firstRestricted,
options.message
);
}
if (defaultCount === 0) {
defaults = [];
}
return {
params: params,
defaults: defaults,
rest: rest,
stricted: options.stricted,
firstRestricted: options.firstRestricted,
message: options.message
};
}
function parseArrowFunctionExpression(options, marker) {
var previousStrict, previousYieldAllowed, previousAwaitAllowed, body;
expect('=>');
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = !!options.async;
body = parseConciseBody();
if (strict && options.firstRestricted) {
throwError(options.firstRestricted, options.message);
}
if (strict && options.stricted) {
throwErrorTolerant(options.stricted, options.message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(marker, delegate.createArrowFunctionExpression(
options.params,
options.defaults,
body,
options.rest,
body.type !== Syntax.BlockStatement,
!!options.async
));
}
function parseAssignmentExpression() {
var marker, expr, token, params, oldParenthesizedCount,
startsWithParen = false, backtrackToken = lookahead,
possiblyAsync = false;
if (matchYield()) {
return parseYieldExpression();
}
if (matchAwait()) {
return parseAwaitExpression();
}
oldParenthesizedCount = state.parenthesizedCount;
marker = markerCreate();
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionExpression();
}
if (matchAsync()) {
// We can't be completely sure that this 'async' token is
// actually a contextual keyword modifying a function
// expression, so we might have to un-lex() it later by
// calling rewind(backtrackToken).
possiblyAsync = true;
lex();
}
if (match('(')) {
token = lookahead2();
if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') {
params = parseParams();
if (!match('=>')) {
throwUnexpected(lex());
}
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
startsWithParen = true;
}
token = lookahead;
// If the 'async' keyword is not followed by a '(' character or an
// identifier, then it can't be an arrow function modifier, and we
// should interpret it as a normal identifer.
if (possiblyAsync && !match('(') && token.type !== Token.Identifier) {
possiblyAsync = false;
rewind(backtrackToken);
}
expr = parseConditionalExpression();
if (match('=>') &&
(state.parenthesizedCount === oldParenthesizedCount ||
state.parenthesizedCount === (oldParenthesizedCount + 1))) {
if (expr.type === Syntax.Identifier) {
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.AssignmentExpression ||
expr.type === Syntax.ArrayExpression ||
expr.type === Syntax.ObjectExpression) {
if (!startsWithParen) {
throwUnexpected(lex());
}
params = reinterpretAsCoverFormalsList([ expr ]);
} else if (expr.type === Syntax.SequenceExpression) {
params = reinterpretAsCoverFormalsList(expr.expressions);
}
if (params) {
params.async = possiblyAsync;
return parseArrowFunctionExpression(params, marker);
}
}
// If we haven't returned by now, then the 'async' keyword was not
// a function modifier, and we should rewind and interpret it as a
// normal identifier.
if (possiblyAsync) {
possiblyAsync = false;
rewind(backtrackToken);
expr = parseConditionalExpression();
}
if (matchAssign()) {
// 11.13.1
if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
throwErrorTolerant(token, Messages.StrictLHSAssignment);
}
// ES.next draf 11.13 Runtime Semantics step 1
if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
reinterpretAsAssignmentBindingPattern(expr);
} else if (!isLeftHandSide(expr)) {
throwError({}, Messages.InvalidLHSInAssignment);
}
expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()));
}
return expr;
}
// 11.14 Comma Operator
function parseExpression() {
var marker, expr, expressions, sequence, spreadFound;
marker = markerCreate();
expr = parseAssignmentExpression();
expressions = [ expr ];
if (match(',')) {
while (index < length) {
if (!match(',')) {
break;
}
lex();
expr = parseSpreadOrAssignmentExpression();
expressions.push(expr);
if (expr.type === Syntax.SpreadElement) {
spreadFound = true;
if (!match(')')) {
throwError({}, Messages.ElementAfterSpreadElement);
}
break;
}
}
sequence = markerApply(marker, delegate.createSequenceExpression(expressions));
}
if (spreadFound && lookahead2().value !== '=>') {
throwError({}, Messages.IllegalSpread);
}
return sequence || expr;
}
// 12.1 Block
function parseStatementList() {
var list = [],
statement;
while (index < length) {
if (match('}')) {
break;
}
statement = parseSourceElement();
if (typeof statement === 'undefined') {
break;
}
list.push(statement);
}
return list;
}
function parseBlock() {
var block, marker = markerCreate();
expect('{');
block = parseStatementList();
expect('}');
return markerApply(marker, delegate.createBlockStatement(block));
}
// 12.2 Variable Statement
function parseTypeParameterDeclaration() {
var marker = markerCreate(), paramTypes = [];
expect('<');
while (!match('>')) {
paramTypes.push(parseTypeAnnotatableIdentifier());
if (!match('>')) {
expect(',');
}
}
expect('>');
return markerApply(marker, delegate.createTypeParameterDeclaration(
paramTypes
));
}
function parseTypeParameterInstantiation() {
var marker = markerCreate(), oldInType = state.inType, paramTypes = [];
state.inType = true;
expect('<');
while (!match('>')) {
paramTypes.push(parseType());
if (!match('>')) {
expect(',');
}
}
expect('>');
state.inType = oldInType;
return markerApply(marker, delegate.createTypeParameterInstantiation(
paramTypes
));
}
function parseObjectTypeIndexer(marker, isStatic) {
var id, key, value;
expect('[');
id = parseObjectPropertyKey();
expect(':');
key = parseType();
expect(']');
expect(':');
value = parseType();
return markerApply(marker, delegate.createObjectTypeIndexer(
id,
key,
value,
isStatic
));
}
function parseObjectTypeMethodish(marker) {
var params = [], rest = null, returnType, typeParameters = null;
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
while (lookahead.type === Token.Identifier) {
params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
rest = parseFunctionTypeParam();
}
expect(')');
expect(':');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
}
function parseObjectTypeMethod(marker, isStatic, key) {
var optional = false, value;
value = parseObjectTypeMethodish(marker);
return markerApply(marker, delegate.createObjectTypeProperty(
key,
value,
optional,
isStatic
));
}
function parseObjectTypeCallProperty(marker, isStatic) {
var valueMarker = markerCreate();
return markerApply(marker, delegate.createObjectTypeCallProperty(
parseObjectTypeMethodish(valueMarker),
isStatic
));
}
function parseObjectType(allowStatic) {
var callProperties = [], indexers = [], marker, optional = false,
properties = [], propertyKey, propertyTypeAnnotation,
token, isStatic, matchStatic;
expect('{');
while (!match('}')) {
marker = markerCreate();
matchStatic =
strict
? matchKeyword('static')
: matchContextualKeyword('static');
if (allowStatic && matchStatic) {
token = lex();
isStatic = true;
}
if (match('[')) {
indexers.push(parseObjectTypeIndexer(marker, isStatic));
} else if (match('(') || match('<')) {
callProperties.push(parseObjectTypeCallProperty(marker, allowStatic));
} else {
if (isStatic && match(':')) {
propertyKey = markerApply(marker, delegate.createIdentifier(token));
throwErrorTolerant(token, Messages.StrictReservedWord);
} else {
propertyKey = parseObjectPropertyKey();
}
if (match('<') || match('(')) {
// This is a method property
properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey));
} else {
if (match('?')) {
lex();
optional = true;
}
expect(':');
propertyTypeAnnotation = parseType();
properties.push(markerApply(marker, delegate.createObjectTypeProperty(
propertyKey,
propertyTypeAnnotation,
optional,
isStatic
)));
}
}
if (match(';')) {
lex();
} else if (!match('}')) {
throwUnexpected(lookahead);
}
}
expect('}');
return delegate.createObjectTypeAnnotation(
properties,
indexers,
callProperties
);
}
function parseGenericType() {
var marker = markerCreate(),
typeParameters = null, typeIdentifier;
typeIdentifier = parseVariableIdentifier();
while (match('.')) {
expect('.');
typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier(
typeIdentifier,
parseVariableIdentifier()
));
}
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createGenericTypeAnnotation(
typeIdentifier,
typeParameters
));
}
function parseVoidType() {
var marker = markerCreate();
expectKeyword('void');
return markerApply(marker, delegate.createVoidTypeAnnotation());
}
function parseTypeofType() {
var argument, marker = markerCreate();
expectKeyword('typeof');
argument = parsePrimaryType();
return markerApply(marker, delegate.createTypeofTypeAnnotation(
argument
));
}
function parseTupleType() {
var marker = markerCreate(), types = [];
expect('[');
// We allow trailing commas
while (index < length && !match(']')) {
types.push(parseType());
if (match(']')) {
break;
}
expect(',');
}
expect(']');
return markerApply(marker, delegate.createTupleTypeAnnotation(
types
));
}
function parseFunctionTypeParam() {
var marker = markerCreate(), name, optional = false, typeAnnotation;
name = parseVariableIdentifier();
if (match('?')) {
lex();
optional = true;
}
expect(':');
typeAnnotation = parseType();
return markerApply(marker, delegate.createFunctionTypeParam(
name,
typeAnnotation,
optional
));
}
function parseFunctionTypeParams() {
var ret = { params: [], rest: null };
while (lookahead.type === Token.Identifier) {
ret.params.push(parseFunctionTypeParam());
if (!match(')')) {
expect(',');
}
}
if (match('...')) {
lex();
ret.rest = parseFunctionTypeParam();
}
return ret;
}
// The parsing of types roughly parallels the parsing of expressions, and
// primary types are kind of like primary expressions...they're the
// primitives with which other types are constructed.
function parsePrimaryType() {
var params = null, returnType = null,
marker = markerCreate(), rest = null, tmp,
typeParameters, token, type, isGroupedType = false;
switch (lookahead.type) {
case Token.Identifier:
switch (lookahead.value) {
case 'any':
lex();
return markerApply(marker, delegate.createAnyTypeAnnotation());
case 'bool': // fallthrough
case 'boolean':
lex();
return markerApply(marker, delegate.createBooleanTypeAnnotation());
case 'number':
lex();
return markerApply(marker, delegate.createNumberTypeAnnotation());
case 'string':
lex();
return markerApply(marker, delegate.createStringTypeAnnotation());
}
return markerApply(marker, parseGenericType());
case Token.Punctuator:
switch (lookahead.value) {
case '{':
return markerApply(marker, parseObjectType());
case '[':
return parseTupleType();
case '<':
typeParameters = parseTypeParameterDeclaration();
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
case '(':
lex();
// Check to see if this is actually a grouped type
if (!match(')') && !match('...')) {
if (lookahead.type === Token.Identifier) {
token = lookahead2();
isGroupedType = token.value !== '?' && token.value !== ':';
} else {
isGroupedType = true;
}
}
if (isGroupedType) {
type = parseType();
expect(')');
// If we see a => next then someone was probably confused about
// function types, so we can provide a better error message
if (match('=>')) {
throwError({}, Messages.ConfusedAboutFunctionType);
}
return type;
}
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect('=>');
returnType = parseType();
return markerApply(marker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
null /* typeParameters */
));
}
break;
case Token.Keyword:
switch (lookahead.value) {
case 'void':
return markerApply(marker, parseVoidType());
case 'typeof':
return markerApply(marker, parseTypeofType());
}
break;
case Token.StringLiteral:
token = lex();
if (token.octal) {
throwError(token, Messages.StrictOctalLiteral);
}
return markerApply(marker, delegate.createStringLiteralTypeAnnotation(
token
));
}
throwUnexpected(lookahead);
}
function parsePostfixType() {
var marker = markerCreate(), t = parsePrimaryType();
if (match('[')) {
expect('[');
expect(']');
return markerApply(marker, delegate.createArrayTypeAnnotation(t));
}
return t;
}
function parsePrefixType() {
var marker = markerCreate();
if (match('?')) {
lex();
return markerApply(marker, delegate.createNullableTypeAnnotation(
parsePrefixType()
));
}
return parsePostfixType();
}
function parseIntersectionType() {
var marker = markerCreate(), type, types;
type = parsePrefixType();
types = [type];
while (match('&')) {
lex();
types.push(parsePrefixType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createIntersectionTypeAnnotation(
types
));
}
function parseUnionType() {
var marker = markerCreate(), type, types;
type = parseIntersectionType();
types = [type];
while (match('|')) {
lex();
types.push(parseIntersectionType());
}
return types.length === 1 ?
type :
markerApply(marker, delegate.createUnionTypeAnnotation(
types
));
}
function parseType() {
var oldInType = state.inType, type;
state.inType = true;
type = parseUnionType();
state.inType = oldInType;
return type;
}
function parseTypeAnnotation() {
var marker = markerCreate(), type;
expect(':');
type = parseType();
return markerApply(marker, delegate.createTypeAnnotation(type));
}
function parseVariableIdentifier() {
var marker = markerCreate(),
token = lex();
if (token.type !== Token.Identifier) {
throwUnexpected(token);
}
return markerApply(marker, delegate.createIdentifier(token.value));
}
function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) {
var marker = markerCreate(),
ident = parseVariableIdentifier(),
isOptionalParam = false;
if (canBeOptionalParam && match('?')) {
expect('?');
isOptionalParam = true;
}
if (requireTypeAnnotation || match(':')) {
ident.typeAnnotation = parseTypeAnnotation();
ident = markerApply(marker, ident);
}
if (isOptionalParam) {
ident.optional = true;
ident = markerApply(marker, ident);
}
return ident;
}
function parseVariableDeclaration(kind) {
var id,
marker = markerCreate(),
init = null,
typeAnnotationMarker = markerCreate();
if (match('{')) {
id = parseObjectInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else if (match('[')) {
id = parseArrayInitialiser();
reinterpretAsAssignmentBindingPattern(id);
if (match(':')) {
id.typeAnnotation = parseTypeAnnotation();
markerApply(typeAnnotationMarker, id);
}
} else {
/* istanbul ignore next */
id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier();
// 12.2.1
if (strict && isRestrictedWord(id.name)) {
throwErrorTolerant({}, Messages.StrictVarName);
}
}
if (kind === 'const') {
if (!match('=')) {
throwError({}, Messages.NoUninitializedConst);
}
expect('=');
init = parseAssignmentExpression();
} else if (match('=')) {
lex();
init = parseAssignmentExpression();
}
return markerApply(marker, delegate.createVariableDeclarator(id, init));
}
function parseVariableDeclarationList(kind) {
var list = [];
do {
list.push(parseVariableDeclaration(kind));
if (!match(',')) {
break;
}
lex();
} while (index < length);
return list;
}
function parseVariableStatement() {
var declarations, marker = markerCreate();
expectKeyword('var');
declarations = parseVariableDeclarationList();
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var'));
}
// kind may be `const` or `let`
// Both are experimental and not in the specification yet.
// see http://wiki.ecmascript.org/doku.php?id=harmony:const
// and http://wiki.ecmascript.org/doku.php?id=harmony:let
function parseConstLetDeclaration(kind) {
var declarations, marker = markerCreate();
expectKeyword(kind);
declarations = parseVariableDeclarationList(kind);
consumeSemicolon();
return markerApply(marker, delegate.createVariableDeclaration(declarations, kind));
}
// people.mozilla.org/~jorendorff/es6-draft.html
function parseModuleSpecifier() {
var marker = markerCreate(),
specifier;
if (lookahead.type !== Token.StringLiteral) {
throwError({}, Messages.InvalidModuleSpecifier);
}
specifier = delegate.createModuleSpecifier(lookahead);
lex();
return markerApply(marker, specifier);
}
function parseExportBatchSpecifier() {
var marker = markerCreate();
expect('*');
return markerApply(marker, delegate.createExportBatchSpecifier());
}
function parseExportSpecifier() {
var id, name = null, marker = markerCreate(), from;
if (matchKeyword('default')) {
lex();
id = markerApply(marker, delegate.createIdentifier('default'));
// export {default} from "something";
} else {
id = parseVariableIdentifier();
}
if (matchContextualKeyword('as')) {
lex();
name = parseNonComputedProperty();
}
return markerApply(marker, delegate.createExportSpecifier(id, name));
}
function parseExportDeclaration() {
var declaration = null,
possibleIdentifierToken, sourceElement,
isExportFromIdentifier,
src = null, specifiers = [],
marker = markerCreate();
expectKeyword('export');
if (matchKeyword('default')) {
// covers:
// export default ...
lex();
if (matchKeyword('function') || matchKeyword('class')) {
possibleIdentifierToken = lookahead2();
if (isIdentifierName(possibleIdentifierToken)) {
// covers:
// export default function foo () {}
// export default class foo {}
sourceElement = parseSourceElement();
return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null));
}
// covers:
// export default function () {}
// export default class {}
switch (lookahead.value) {
case 'class':
return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null));
case 'function':
return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null));
}
}
if (matchContextualKeyword('from')) {
throwError({}, Messages.UnexpectedToken, lookahead.value);
}
// covers:
// export default {};
// export default [];
if (match('{')) {
declaration = parseObjectInitialiser();
} else if (match('[')) {
declaration = parseArrayInitialiser();
} else {
declaration = parseAssignmentExpression();
}
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null));
}
// non-default export
if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) {
// covers:
// export var f = 1;
switch (lookahead.value) {
case 'type':
case 'let':
case 'const':
case 'var':
case 'class':
case 'function':
return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null));
}
}
if (match('*')) {
// covers:
// export * from "foo";
specifiers.push(parseExportBatchSpecifier());
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src));
}
expect('{');
if (!match('}')) {
do {
isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default');
specifiers.push(parseExportSpecifier());
} while (match(',') && lex());
}
expect('}');
if (matchContextualKeyword('from')) {
// covering:
// export {default} from "foo";
// export {foo} from "foo";
lex();
src = parseModuleSpecifier();
consumeSemicolon();
} else if (isExportFromIdentifier) {
// covering:
// export {default}; // missing fromClause
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
} else {
// cover
// export {foo};
consumeSemicolon();
}
return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src));
}
function parseImportSpecifier() {
// import {<foo as bar>} ...;
var id, name = null, marker = markerCreate();
id = parseNonComputedProperty();
if (matchContextualKeyword('as')) {
lex();
name = parseVariableIdentifier();
}
return markerApply(marker, delegate.createImportSpecifier(id, name));
}
function parseNamedImports() {
var specifiers = [];
// {foo, bar as bas}
expect('{');
if (!match('}')) {
do {
specifiers.push(parseImportSpecifier());
} while (match(',') && lex());
}
expect('}');
return specifiers;
}
function parseImportDefaultSpecifier() {
// import <foo> ...;
var id, marker = markerCreate();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportDefaultSpecifier(id));
}
function parseImportNamespaceSpecifier() {
// import <* as foo> ...;
var id, marker = markerCreate();
expect('*');
if (!matchContextualKeyword('as')) {
throwError({}, Messages.NoAsAfterImportNamespace);
}
lex();
id = parseNonComputedProperty();
return markerApply(marker, delegate.createImportNamespaceSpecifier(id));
}
function parseImportDeclaration() {
var specifiers, src, marker = markerCreate(), isType = false, token2;
expectKeyword('import');
if (matchContextualKeyword('type')) {
token2 = lookahead2();
if ((token2.type === Token.Identifier && token2.value !== 'from') ||
(token2.type === Token.Punctuator &&
(token2.value === '{' || token2.value === '*'))) {
isType = true;
lex();
}
}
specifiers = [];
if (lookahead.type === Token.StringLiteral) {
// covers:
// import "foo";
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
if (!matchKeyword('default') && isIdentifierName(lookahead)) {
// covers:
// import foo
// import foo, ...
specifiers.push(parseImportDefaultSpecifier());
if (match(',')) {
lex();
}
}
if (match('*')) {
// covers:
// import foo, * as foo
// import * as foo
specifiers.push(parseImportNamespaceSpecifier());
} else if (match('{')) {
// covers:
// import foo, {bar}
// import {bar}
specifiers = specifiers.concat(parseNamedImports());
}
if (!matchContextualKeyword('from')) {
throwError({}, lookahead.value ?
Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value);
}
lex();
src = parseModuleSpecifier();
consumeSemicolon();
return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType));
}
// 12.3 Empty Statement
function parseEmptyStatement() {
var marker = markerCreate();
expect(';');
return markerApply(marker, delegate.createEmptyStatement());
}
// 12.4 Expression Statement
function parseExpressionStatement() {
var marker = markerCreate(), expr = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 12.5 If statement
function parseIfStatement() {
var test, consequent, alternate, marker = markerCreate();
expectKeyword('if');
expect('(');
test = parseExpression();
expect(')');
consequent = parseStatement();
if (matchKeyword('else')) {
lex();
alternate = parseStatement();
} else {
alternate = null;
}
return markerApply(marker, delegate.createIfStatement(test, consequent, alternate));
}
// 12.6 Iteration Statements
function parseDoWhileStatement() {
var body, test, oldInIteration, marker = markerCreate();
expectKeyword('do');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
if (match(';')) {
lex();
}
return markerApply(marker, delegate.createDoWhileStatement(body, test));
}
function parseWhileStatement() {
var test, body, oldInIteration, marker = markerCreate();
expectKeyword('while');
expect('(');
test = parseExpression();
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
body = parseStatement();
state.inIteration = oldInIteration;
return markerApply(marker, delegate.createWhileStatement(test, body));
}
function parseForVariableDeclaration() {
var marker = markerCreate(),
token = lex(),
declarations = parseVariableDeclarationList();
return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value));
}
function parseForStatement(opts) {
var init, test, update, left, right, body, operator, oldInIteration,
marker = markerCreate();
init = test = update = null;
expectKeyword('for');
// http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each
if (matchContextualKeyword('each')) {
throwError({}, Messages.EachNotAllowed);
}
expect('(');
if (match(';')) {
lex();
} else {
if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
state.allowIn = false;
init = parseForVariableDeclaration();
state.allowIn = true;
if (init.declarations.length === 1) {
if (matchKeyword('in') || matchContextualKeyword('of')) {
operator = lookahead;
if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
lex();
left = init;
right = parseExpression();
init = null;
}
}
}
} else {
state.allowIn = false;
init = parseExpression();
state.allowIn = true;
if (matchContextualKeyword('of')) {
operator = lex();
left = init;
right = parseExpression();
init = null;
} else if (matchKeyword('in')) {
// LeftHandSideExpression
if (!isAssignableLeftHandSide(init)) {
throwError({}, Messages.InvalidLHSInForIn);
}
operator = lex();
left = init;
right = parseExpression();
init = null;
}
}
if (typeof left === 'undefined') {
expect(';');
}
}
if (typeof left === 'undefined') {
if (!match(';')) {
test = parseExpression();
}
expect(';');
if (!match(')')) {
update = parseExpression();
}
}
expect(')');
oldInIteration = state.inIteration;
state.inIteration = true;
if (!(opts !== undefined && opts.ignoreBody)) {
body = parseStatement();
}
state.inIteration = oldInIteration;
if (typeof left === 'undefined') {
return markerApply(marker, delegate.createForStatement(init, test, update, body));
}
if (operator.value === 'in') {
return markerApply(marker, delegate.createForInStatement(left, right, body));
}
return markerApply(marker, delegate.createForOfStatement(left, right, body));
}
// 12.7 The continue statement
function parseContinueStatement() {
var label = null, marker = markerCreate();
expectKeyword('continue');
// Optimize the most common form: 'continue;'.
if (source.charCodeAt(index) === 59) {
lex();
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (peekLineTerminator()) {
if (!state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !state.inIteration) {
throwError({}, Messages.IllegalContinue);
}
return markerApply(marker, delegate.createContinueStatement(label));
}
// 12.8 The break statement
function parseBreakStatement() {
var label = null, marker = markerCreate();
expectKeyword('break');
// Catch the very common case first: immediately a semicolon (char #59).
if (source.charCodeAt(index) === 59) {
lex();
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (peekLineTerminator()) {
if (!(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(null));
}
if (lookahead.type === Token.Identifier) {
label = parseVariableIdentifier();
if (!state.labelSet.has(label.name)) {
throwError({}, Messages.UnknownLabel, label.name);
}
}
consumeSemicolon();
if (label === null && !(state.inIteration || state.inSwitch)) {
throwError({}, Messages.IllegalBreak);
}
return markerApply(marker, delegate.createBreakStatement(label));
}
// 12.9 The return statement
function parseReturnStatement() {
var argument = null, marker = markerCreate();
expectKeyword('return');
if (!state.inFunctionBody) {
throwErrorTolerant({}, Messages.IllegalReturn);
}
// 'return' followed by a space and an identifier is very common.
if (source.charCodeAt(index) === 32) {
if (isIdentifierStart(source.charCodeAt(index + 1))) {
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
}
if (peekLineTerminator()) {
return markerApply(marker, delegate.createReturnStatement(null));
}
if (!match(';')) {
if (!match('}') && lookahead.type !== Token.EOF) {
argument = parseExpression();
}
}
consumeSemicolon();
return markerApply(marker, delegate.createReturnStatement(argument));
}
// 12.10 The with statement
function parseWithStatement() {
var object, body, marker = markerCreate();
if (strict) {
throwErrorTolerant({}, Messages.StrictModeWith);
}
expectKeyword('with');
expect('(');
object = parseExpression();
expect(')');
body = parseStatement();
return markerApply(marker, delegate.createWithStatement(object, body));
}
// 12.10 The swith statement
function parseSwitchCase() {
var test,
consequent = [],
sourceElement,
marker = markerCreate();
if (matchKeyword('default')) {
lex();
test = null;
} else {
expectKeyword('case');
test = parseExpression();
}
expect(':');
while (index < length) {
if (match('}') || matchKeyword('default') || matchKeyword('case')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
consequent.push(sourceElement);
}
return markerApply(marker, delegate.createSwitchCase(test, consequent));
}
function parseSwitchStatement() {
var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate();
expectKeyword('switch');
expect('(');
discriminant = parseExpression();
expect(')');
expect('{');
cases = [];
if (match('}')) {
lex();
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
oldInSwitch = state.inSwitch;
state.inSwitch = true;
defaultFound = false;
while (index < length) {
if (match('}')) {
break;
}
clause = parseSwitchCase();
if (clause.test === null) {
if (defaultFound) {
throwError({}, Messages.MultipleDefaultsInSwitch);
}
defaultFound = true;
}
cases.push(clause);
}
state.inSwitch = oldInSwitch;
expect('}');
return markerApply(marker, delegate.createSwitchStatement(discriminant, cases));
}
// 12.13 The throw statement
function parseThrowStatement() {
var argument, marker = markerCreate();
expectKeyword('throw');
if (peekLineTerminator()) {
throwError({}, Messages.NewlineAfterThrow);
}
argument = parseExpression();
consumeSemicolon();
return markerApply(marker, delegate.createThrowStatement(argument));
}
// 12.14 The try statement
function parseCatchClause() {
var param, body, marker = markerCreate();
expectKeyword('catch');
expect('(');
if (match(')')) {
throwUnexpected(lookahead);
}
param = parseExpression();
// 12.14.1
if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
throwErrorTolerant({}, Messages.StrictCatchVariable);
}
expect(')');
body = parseBlock();
return markerApply(marker, delegate.createCatchClause(param, body));
}
function parseTryStatement() {
var block, handlers = [], finalizer = null, marker = markerCreate();
expectKeyword('try');
block = parseBlock();
if (matchKeyword('catch')) {
handlers.push(parseCatchClause());
}
if (matchKeyword('finally')) {
lex();
finalizer = parseBlock();
}
if (handlers.length === 0 && !finalizer) {
throwError({}, Messages.NoCatchOrFinally);
}
return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer));
}
// 12.15 The debugger statement
function parseDebuggerStatement() {
var marker = markerCreate();
expectKeyword('debugger');
consumeSemicolon();
return markerApply(marker, delegate.createDebuggerStatement());
}
// 12 Statements
function parseStatement() {
var type = lookahead.type,
marker,
expr,
labeledBody;
if (type === Token.EOF) {
throwUnexpected(lookahead);
}
if (type === Token.Punctuator) {
switch (lookahead.value) {
case ';':
return parseEmptyStatement();
case '{':
return parseBlock();
case '(':
return parseExpressionStatement();
default:
break;
}
}
if (type === Token.Keyword) {
switch (lookahead.value) {
case 'break':
return parseBreakStatement();
case 'continue':
return parseContinueStatement();
case 'debugger':
return parseDebuggerStatement();
case 'do':
return parseDoWhileStatement();
case 'for':
return parseForStatement();
case 'function':
return parseFunctionDeclaration();
case 'class':
return parseClassDeclaration();
case 'if':
return parseIfStatement();
case 'return':
return parseReturnStatement();
case 'switch':
return parseSwitchStatement();
case 'throw':
return parseThrowStatement();
case 'try':
return parseTryStatement();
case 'var':
return parseVariableStatement();
case 'while':
return parseWhileStatement();
case 'with':
return parseWithStatement();
default:
break;
}
}
if (matchAsyncFuncExprOrDecl()) {
return parseFunctionDeclaration();
}
marker = markerCreate();
expr = parseExpression();
// 12.12 Labelled Statements
if ((expr.type === Syntax.Identifier) && match(':')) {
lex();
if (state.labelSet.has(expr.name)) {
throwError({}, Messages.Redeclaration, 'Label', expr.name);
}
state.labelSet.set(expr.name, true);
labeledBody = parseStatement();
state.labelSet["delete"](expr.name);
return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody));
}
consumeSemicolon();
return markerApply(marker, delegate.createExpressionStatement(expr));
}
// 13 Function Definition
function parseConciseBody() {
if (match('{')) {
return parseFunctionSourceElements();
}
return parseAssignmentExpression();
}
function parseFunctionSourceElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted,
oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount,
marker = markerCreate();
expect('{');
while (index < length) {
if (lookahead.type !== Token.StringLiteral) {
break;
}
token = lookahead;
sourceElement = parseSourceElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
oldLabelSet = state.labelSet;
oldInIteration = state.inIteration;
oldInSwitch = state.inSwitch;
oldInFunctionBody = state.inFunctionBody;
oldParenthesizedCount = state.parenthesizedCount;
state.labelSet = new StringMap();
state.inIteration = false;
state.inSwitch = false;
state.inFunctionBody = true;
state.parenthesizedCount = 0;
while (index < length) {
if (match('}')) {
break;
}
sourceElement = parseSourceElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
expect('}');
state.labelSet = oldLabelSet;
state.inIteration = oldInIteration;
state.inSwitch = oldInSwitch;
state.inFunctionBody = oldInFunctionBody;
state.parenthesizedCount = oldParenthesizedCount;
return markerApply(marker, delegate.createBlockStatement(sourceElements));
}
function validateParam(options, param, name) {
if (strict) {
if (isRestrictedWord(name)) {
options.stricted = param;
options.message = Messages.StrictParamName;
}
if (options.paramSet.has(name)) {
options.stricted = param;
options.message = Messages.StrictParamDupe;
}
} else if (!options.firstRestricted) {
if (isRestrictedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamName;
} else if (isStrictModeReservedWord(name)) {
options.firstRestricted = param;
options.message = Messages.StrictReservedWord;
} else if (options.paramSet.has(name)) {
options.firstRestricted = param;
options.message = Messages.StrictParamDupe;
}
}
options.paramSet.set(name, true);
}
function parseParam(options) {
var marker, token, rest, param, def;
token = lookahead;
if (token.value === '...') {
token = lex();
rest = true;
}
if (match('[')) {
marker = markerCreate();
param = parseArrayInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else if (match('{')) {
marker = markerCreate();
if (rest) {
throwError({}, Messages.ObjectPatternAsRestParameter);
}
param = parseObjectInitialiser();
reinterpretAsDestructuredParameter(options, param);
if (match(':')) {
param.typeAnnotation = parseTypeAnnotation();
markerApply(marker, param);
}
} else {
param =
rest
? parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
false /* canBeOptionalParam */
)
: parseTypeAnnotatableIdentifier(
false, /* requireTypeAnnotation */
true /* canBeOptionalParam */
);
validateParam(options, token, token.value);
}
if (match('=')) {
if (rest) {
throwErrorTolerant(lookahead, Messages.DefaultRestParameter);
}
lex();
def = parseAssignmentExpression();
++options.defaultCount;
}
if (rest) {
if (!match(')')) {
throwError({}, Messages.ParameterAfterRestParameter);
}
options.rest = param;
return false;
}
options.params.push(param);
options.defaults.push(def);
return !match(')');
}
function parseParams(firstRestricted) {
var options, marker = markerCreate();
options = {
params: [],
defaultCount: 0,
defaults: [],
rest: null,
firstRestricted: firstRestricted
};
expect('(');
if (!match(')')) {
options.paramSet = new StringMap();
while (index < length) {
if (!parseParam(options)) {
break;
}
expect(',');
}
}
expect(')');
if (options.defaultCount === 0) {
options.defaults = [];
}
if (match(':')) {
options.returnType = parseTypeAnnotation();
}
return markerApply(marker, options);
}
function parseFunctionDeclaration() {
var id, body, token, tmp, firstRestricted, message, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
token = lookahead;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionDeclaration(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseFunctionExpression() {
var token, id = null, firstRestricted, message, tmp, body, generator, isAsync,
previousStrict, previousYieldAllowed, previousAwaitAllowed,
marker = markerCreate(), typeParameters;
isAsync = false;
if (matchAsync()) {
lex();
isAsync = true;
}
expectKeyword('function');
generator = false;
if (match('*')) {
lex();
generator = true;
}
if (!match('(')) {
if (!match('<')) {
token = lookahead;
id = parseVariableIdentifier();
if (strict) {
if (isRestrictedWord(token.value)) {
throwErrorTolerant(token, Messages.StrictFunctionName);
}
} else {
if (isRestrictedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictFunctionName;
} else if (isStrictModeReservedWord(token.value)) {
firstRestricted = token;
message = Messages.StrictReservedWord;
}
}
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
}
tmp = parseParams(firstRestricted);
firstRestricted = tmp.firstRestricted;
if (tmp.message) {
message = tmp.message;
}
previousStrict = strict;
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = generator;
previousAwaitAllowed = state.awaitAllowed;
state.awaitAllowed = isAsync;
body = parseFunctionSourceElements();
if (strict && firstRestricted) {
throwError(firstRestricted, message);
}
if (strict && tmp.stricted) {
throwErrorTolerant(tmp.stricted, message);
}
strict = previousStrict;
state.yieldAllowed = previousYieldAllowed;
state.awaitAllowed = previousAwaitAllowed;
return markerApply(
marker,
delegate.createFunctionExpression(
id,
tmp.params,
tmp.defaults,
body,
tmp.rest,
generator,
false,
isAsync,
tmp.returnType,
typeParameters
)
);
}
function parseYieldExpression() {
var delegateFlag, expr, marker = markerCreate();
expectKeyword('yield', !strict);
delegateFlag = false;
if (match('*')) {
lex();
delegateFlag = true;
}
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag));
}
function parseAwaitExpression() {
var expr, marker = markerCreate();
expectContextualKeyword('await');
expr = parseAssignmentExpression();
return markerApply(marker, delegate.createAwaitExpression(expr));
}
// 14 Functions and classes
// 14.1 Functions is defined above (13 in ES5)
// 14.2 Arrow Functions Definitions is defined in (7.3 assignments)
// 14.3 Method Definitions
// 14.3.7
function specialMethod(methodDefinition) {
return methodDefinition.kind === 'get' ||
methodDefinition.kind === 'set' ||
methodDefinition.value.generator;
}
function parseMethodDefinition(key, isStatic, generator, computed) {
var token, param, propType,
isAsync, typeParameters, tokenValue, returnType;
propType = isStatic ? ClassPropertyType["static"] : ClassPropertyType.prototype;
if (generator) {
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({ generator: true }),
computed
);
}
tokenValue = key.type === 'Identifier' && key.name;
if (tokenValue === 'get' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'get',
key,
parsePropertyFunction({ generator: false, returnType: returnType }),
computed
);
}
if (tokenValue === 'set' && !match('(')) {
key = parseObjectPropertyKey();
expect('(');
token = lookahead;
param = [ parseTypeAnnotatableIdentifier() ];
expect(')');
if (match(':')) {
returnType = parseTypeAnnotation();
}
return delegate.createMethodDefinition(
propType,
'set',
key,
parsePropertyFunction({
params: param,
generator: false,
name: token,
returnType: returnType
}),
computed
);
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
isAsync = tokenValue === 'async' && !match('(');
if (isAsync) {
key = parseObjectPropertyKey();
}
return delegate.createMethodDefinition(
propType,
'',
key,
parsePropertyMethodFunction({
generator: false,
async: isAsync,
typeParameters: typeParameters
}),
computed
);
}
function parseClassProperty(key, computed, isStatic) {
var typeAnnotation;
typeAnnotation = parseTypeAnnotation();
expect(';');
return delegate.createClassProperty(
key,
typeAnnotation,
computed,
isStatic
);
}
function parseClassElement() {
var computed = false, generator = false, key, marker = markerCreate(),
isStatic = false, possiblyOpenBracketToken;
if (match(';')) {
lex();
return undefined;
}
if (lookahead.value === 'static') {
lex();
isStatic = true;
}
if (match('*')) {
lex();
generator = true;
}
possiblyOpenBracketToken = lookahead;
if (matchContextualKeyword('get') || matchContextualKeyword('set')) {
possiblyOpenBracketToken = lookahead2();
}
if (possiblyOpenBracketToken.type === Token.Punctuator
&& possiblyOpenBracketToken.value === '[') {
computed = true;
}
key = parseObjectPropertyKey();
if (!generator && lookahead.value === ':') {
return markerApply(marker, parseClassProperty(key, computed, isStatic));
}
return markerApply(marker, parseMethodDefinition(
key,
isStatic,
generator,
computed
));
}
function parseClassBody() {
var classElement, classElements = [], existingProps = {},
marker = markerCreate(), propName, propType;
existingProps[ClassPropertyType["static"]] = new StringMap();
existingProps[ClassPropertyType.prototype] = new StringMap();
expect('{');
while (index < length) {
if (match('}')) {
break;
}
classElement = parseClassElement(existingProps);
if (typeof classElement !== 'undefined') {
classElements.push(classElement);
propName = !classElement.computed && getFieldName(classElement.key);
if (propName !== false) {
propType = classElement["static"] ?
ClassPropertyType["static"] :
ClassPropertyType.prototype;
if (classElement.type === Syntax.MethodDefinition) {
if (propName === 'constructor' && !classElement["static"]) {
if (specialMethod(classElement)) {
throwError(classElement, Messages.IllegalClassConstructorProperty);
}
if (existingProps[ClassPropertyType.prototype].has('constructor')) {
throwError(classElement.key, Messages.IllegalDuplicateClassProperty);
}
}
existingProps[propType].set(propName, true);
}
}
}
}
expect('}');
return markerApply(marker, delegate.createClassBody(classElements));
}
function parseClassImplements() {
var id, implemented = [], marker, typeParameters;
if (strict) {
expectKeyword('implements');
} else {
expectContextualKeyword('implements');
}
while (index < length) {
marker = markerCreate();
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
} else {
typeParameters = null;
}
implemented.push(markerApply(marker, delegate.createClassImplements(
id,
typeParameters
)));
if (!match(',')) {
break;
}
expect(',');
}
return implemented;
}
function parseClassExpression() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters,
matchImplements;
expectKeyword('class');
matchImplements =
strict
? matchKeyword('implements')
: matchContextualKeyword('implements');
if (!matchKeyword('extends') && !matchImplements && !match('{')) {
id = parseVariableIdentifier();
}
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassExpression(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
function parseClassDeclaration() {
var id, implemented, previousYieldAllowed, superClass = null,
superTypeParameters, marker = markerCreate(), typeParameters;
expectKeyword('class');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
previousYieldAllowed = state.yieldAllowed;
state.yieldAllowed = false;
superClass = parseLeftHandSideExpressionAllowCall();
if (match('<')) {
superTypeParameters = parseTypeParameterInstantiation();
}
state.yieldAllowed = previousYieldAllowed;
}
if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) {
implemented = parseClassImplements();
}
return markerApply(marker, delegate.createClassDeclaration(
id,
superClass,
parseClassBody(),
typeParameters,
superTypeParameters,
implemented
));
}
// 15 Program
function parseSourceElement() {
var token;
if (lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'const':
case 'let':
return parseConstLetDeclaration(lookahead.value);
case 'function':
return parseFunctionDeclaration();
case 'export':
throwErrorTolerant({}, Messages.IllegalExportDeclaration);
return parseExportDeclaration();
case 'import':
throwErrorTolerant({}, Messages.IllegalImportDeclaration);
return parseImportDeclaration();
case 'interface':
if (lookahead2().type === Token.Identifier) {
return parseInterface();
}
return parseStatement();
default:
return parseStatement();
}
}
if (matchContextualKeyword('type')
&& lookahead2().type === Token.Identifier) {
return parseTypeAlias();
}
if (matchContextualKeyword('interface')
&& lookahead2().type === Token.Identifier) {
return parseInterface();
}
if (matchContextualKeyword('declare')) {
token = lookahead2();
if (token.type === Token.Keyword) {
switch (token.value) {
case 'class':
return parseDeclareClass();
case 'function':
return parseDeclareFunction();
case 'var':
return parseDeclareVariable();
}
} else if (token.type === Token.Identifier
&& token.value === 'module') {
return parseDeclareModule();
}
}
if (lookahead.type !== Token.EOF) {
return parseStatement();
}
}
function parseProgramElement() {
var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule';
if (isModule && lookahead.type === Token.Keyword) {
switch (lookahead.value) {
case 'export':
return parseExportDeclaration();
case 'import':
return parseImportDeclaration();
}
}
return parseSourceElement();
}
function parseProgramElements() {
var sourceElement, sourceElements = [], token, directive, firstRestricted;
while (index < length) {
token = lookahead;
if (token.type !== Token.StringLiteral) {
break;
}
sourceElement = parseProgramElement();
sourceElements.push(sourceElement);
if (sourceElement.expression.type !== Syntax.Literal) {
// this is not directive
break;
}
directive = source.slice(token.range[0] + 1, token.range[1] - 1);
if (directive === 'use strict') {
strict = true;
if (firstRestricted) {
throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
}
} else {
if (!firstRestricted && token.octal) {
firstRestricted = token;
}
}
}
while (index < length) {
sourceElement = parseProgramElement();
if (typeof sourceElement === 'undefined') {
break;
}
sourceElements.push(sourceElement);
}
return sourceElements;
}
function parseProgram() {
var body, marker = markerCreate();
strict = extra.sourceType === 'module';
peek();
body = parseProgramElements();
return markerApply(marker, delegate.createProgram(body));
}
// 16 JSX
XHTMLEntities = {
quot: '\u0022',
amp: '&',
apos: '\u0027',
lt: '<',
gt: '>',
nbsp: '\u00A0',
iexcl: '\u00A1',
cent: '\u00A2',
pound: '\u00A3',
curren: '\u00A4',
yen: '\u00A5',
brvbar: '\u00A6',
sect: '\u00A7',
uml: '\u00A8',
copy: '\u00A9',
ordf: '\u00AA',
laquo: '\u00AB',
not: '\u00AC',
shy: '\u00AD',
reg: '\u00AE',
macr: '\u00AF',
deg: '\u00B0',
plusmn: '\u00B1',
sup2: '\u00B2',
sup3: '\u00B3',
acute: '\u00B4',
micro: '\u00B5',
para: '\u00B6',
middot: '\u00B7',
cedil: '\u00B8',
sup1: '\u00B9',
ordm: '\u00BA',
raquo: '\u00BB',
frac14: '\u00BC',
frac12: '\u00BD',
frac34: '\u00BE',
iquest: '\u00BF',
Agrave: '\u00C0',
Aacute: '\u00C1',
Acirc: '\u00C2',
Atilde: '\u00C3',
Auml: '\u00C4',
Aring: '\u00C5',
AElig: '\u00C6',
Ccedil: '\u00C7',
Egrave: '\u00C8',
Eacute: '\u00C9',
Ecirc: '\u00CA',
Euml: '\u00CB',
Igrave: '\u00CC',
Iacute: '\u00CD',
Icirc: '\u00CE',
Iuml: '\u00CF',
ETH: '\u00D0',
Ntilde: '\u00D1',
Ograve: '\u00D2',
Oacute: '\u00D3',
Ocirc: '\u00D4',
Otilde: '\u00D5',
Ouml: '\u00D6',
times: '\u00D7',
Oslash: '\u00D8',
Ugrave: '\u00D9',
Uacute: '\u00DA',
Ucirc: '\u00DB',
Uuml: '\u00DC',
Yacute: '\u00DD',
THORN: '\u00DE',
szlig: '\u00DF',
agrave: '\u00E0',
aacute: '\u00E1',
acirc: '\u00E2',
atilde: '\u00E3',
auml: '\u00E4',
aring: '\u00E5',
aelig: '\u00E6',
ccedil: '\u00E7',
egrave: '\u00E8',
eacute: '\u00E9',
ecirc: '\u00EA',
euml: '\u00EB',
igrave: '\u00EC',
iacute: '\u00ED',
icirc: '\u00EE',
iuml: '\u00EF',
eth: '\u00F0',
ntilde: '\u00F1',
ograve: '\u00F2',
oacute: '\u00F3',
ocirc: '\u00F4',
otilde: '\u00F5',
ouml: '\u00F6',
divide: '\u00F7',
oslash: '\u00F8',
ugrave: '\u00F9',
uacute: '\u00FA',
ucirc: '\u00FB',
uuml: '\u00FC',
yacute: '\u00FD',
thorn: '\u00FE',
yuml: '\u00FF',
OElig: '\u0152',
oelig: '\u0153',
Scaron: '\u0160',
scaron: '\u0161',
Yuml: '\u0178',
fnof: '\u0192',
circ: '\u02C6',
tilde: '\u02DC',
Alpha: '\u0391',
Beta: '\u0392',
Gamma: '\u0393',
Delta: '\u0394',
Epsilon: '\u0395',
Zeta: '\u0396',
Eta: '\u0397',
Theta: '\u0398',
Iota: '\u0399',
Kappa: '\u039A',
Lambda: '\u039B',
Mu: '\u039C',
Nu: '\u039D',
Xi: '\u039E',
Omicron: '\u039F',
Pi: '\u03A0',
Rho: '\u03A1',
Sigma: '\u03A3',
Tau: '\u03A4',
Upsilon: '\u03A5',
Phi: '\u03A6',
Chi: '\u03A7',
Psi: '\u03A8',
Omega: '\u03A9',
alpha: '\u03B1',
beta: '\u03B2',
gamma: '\u03B3',
delta: '\u03B4',
epsilon: '\u03B5',
zeta: '\u03B6',
eta: '\u03B7',
theta: '\u03B8',
iota: '\u03B9',
kappa: '\u03BA',
lambda: '\u03BB',
mu: '\u03BC',
nu: '\u03BD',
xi: '\u03BE',
omicron: '\u03BF',
pi: '\u03C0',
rho: '\u03C1',
sigmaf: '\u03C2',
sigma: '\u03C3',
tau: '\u03C4',
upsilon: '\u03C5',
phi: '\u03C6',
chi: '\u03C7',
psi: '\u03C8',
omega: '\u03C9',
thetasym: '\u03D1',
upsih: '\u03D2',
piv: '\u03D6',
ensp: '\u2002',
emsp: '\u2003',
thinsp: '\u2009',
zwnj: '\u200C',
zwj: '\u200D',
lrm: '\u200E',
rlm: '\u200F',
ndash: '\u2013',
mdash: '\u2014',
lsquo: '\u2018',
rsquo: '\u2019',
sbquo: '\u201A',
ldquo: '\u201C',
rdquo: '\u201D',
bdquo: '\u201E',
dagger: '\u2020',
Dagger: '\u2021',
bull: '\u2022',
hellip: '\u2026',
permil: '\u2030',
prime: '\u2032',
Prime: '\u2033',
lsaquo: '\u2039',
rsaquo: '\u203A',
oline: '\u203E',
frasl: '\u2044',
euro: '\u20AC',
image: '\u2111',
weierp: '\u2118',
real: '\u211C',
trade: '\u2122',
alefsym: '\u2135',
larr: '\u2190',
uarr: '\u2191',
rarr: '\u2192',
darr: '\u2193',
harr: '\u2194',
crarr: '\u21B5',
lArr: '\u21D0',
uArr: '\u21D1',
rArr: '\u21D2',
dArr: '\u21D3',
hArr: '\u21D4',
forall: '\u2200',
part: '\u2202',
exist: '\u2203',
empty: '\u2205',
nabla: '\u2207',
isin: '\u2208',
notin: '\u2209',
ni: '\u220B',
prod: '\u220F',
sum: '\u2211',
minus: '\u2212',
lowast: '\u2217',
radic: '\u221A',
prop: '\u221D',
infin: '\u221E',
ang: '\u2220',
and: '\u2227',
or: '\u2228',
cap: '\u2229',
cup: '\u222A',
'int': '\u222B',
there4: '\u2234',
sim: '\u223C',
cong: '\u2245',
asymp: '\u2248',
ne: '\u2260',
equiv: '\u2261',
le: '\u2264',
ge: '\u2265',
sub: '\u2282',
sup: '\u2283',
nsub: '\u2284',
sube: '\u2286',
supe: '\u2287',
oplus: '\u2295',
otimes: '\u2297',
perp: '\u22A5',
sdot: '\u22C5',
lceil: '\u2308',
rceil: '\u2309',
lfloor: '\u230A',
rfloor: '\u230B',
lang: '\u2329',
rang: '\u232A',
loz: '\u25CA',
spades: '\u2660',
clubs: '\u2663',
hearts: '\u2665',
diams: '\u2666'
};
function getQualifiedJSXName(object) {
if (object.type === Syntax.JSXIdentifier) {
return object.name;
}
if (object.type === Syntax.JSXNamespacedName) {
return object.namespace.name + ':' + object.name.name;
}
/* istanbul ignore else */
if (object.type === Syntax.JSXMemberExpression) {
return (
getQualifiedJSXName(object.object) + '.' +
getQualifiedJSXName(object.property)
);
}
/* istanbul ignore next */
throwUnexpected(object);
}
function isJSXIdentifierStart(ch) {
// exclude backslash (\)
return (ch !== 92) && isIdentifierStart(ch);
}
function isJSXIdentifierPart(ch) {
// exclude backslash (\) and add hyphen (-)
return (ch !== 92) && (ch === 45 || isIdentifierPart(ch));
}
function scanJSXIdentifier() {
var ch, start, value = '';
start = index;
while (index < length) {
ch = source.charCodeAt(index);
if (!isJSXIdentifierPart(ch)) {
break;
}
value += source[index++];
}
return {
type: Token.JSXIdentifier,
value: value,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXEntity() {
var ch, str = '', start = index, count = 0, code;
ch = source[index];
assert(ch === '&', 'Entity must start with an ampersand');
index++;
while (index < length && count++ < 10) {
ch = source[index++];
if (ch === ';') {
break;
}
str += ch;
}
// Well-formed entity (ending was found).
if (ch === ';') {
// Numeric entity.
if (str[0] === '#') {
if (str[1] === 'x') {
code = +('0' + str.substr(1));
} else {
// Removing leading zeros in order to avoid treating as octal in old browsers.
code = +str.substr(1).replace(Regex.LeadingZeros, '');
}
if (!isNaN(code)) {
return String.fromCharCode(code);
}
/* istanbul ignore else */
} else if (XHTMLEntities[str]) {
return XHTMLEntities[str];
}
}
// Treat non-entity sequences as regular text.
index = start + 1;
return '&';
}
function scanJSXText(stopChars) {
var ch, str = '', start;
start = index;
while (index < length) {
ch = source[index];
if (stopChars.indexOf(ch) !== -1) {
break;
}
if (ch === '&') {
str += scanJSXEntity();
} else {
index++;
if (ch === '\r' && source[index] === '\n') {
str += ch;
ch = source[index];
index++;
}
if (isLineTerminator(ch.charCodeAt(0))) {
++lineNumber;
lineStart = index;
}
str += ch;
}
}
return {
type: Token.JSXText,
value: str,
lineNumber: lineNumber,
lineStart: lineStart,
range: [start, index]
};
}
function scanJSXStringLiteral() {
var innerToken, quote, start;
quote = source[index];
assert((quote === '\'' || quote === '"'),
'String literal must starts with a quote');
start = index;
++index;
innerToken = scanJSXText([quote]);
if (quote !== source[index]) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
++index;
innerToken.range = [start, index];
return innerToken;
}
/**
* Between JSX opening and closing tags (e.g. <foo>HERE</foo>), anything that
* is not another JSX tag and is not an expression wrapped by {} is text.
*/
function advanceJSXChild() {
var ch = source.charCodeAt(index);
// '<' 60, '>' 62, '{' 123, '}' 125
if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) {
return scanJSXText(['<', '>', '{', '}']);
}
return scanPunctuator();
}
function parseJSXIdentifier() {
var token, marker = markerCreate();
if (lookahead.type !== Token.JSXIdentifier) {
throwUnexpected(lookahead);
}
token = lex();
return markerApply(marker, delegate.createJSXIdentifier(token.value));
}
function parseJSXNamespacedName() {
var namespace, name, marker = markerCreate();
namespace = parseJSXIdentifier();
expect(':');
name = parseJSXIdentifier();
return markerApply(marker, delegate.createJSXNamespacedName(namespace, name));
}
function parseJSXMemberExpression() {
var marker = markerCreate(),
expr = parseJSXIdentifier();
while (match('.')) {
lex();
expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier()));
}
return expr;
}
function parseJSXElementName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
if (lookahead2().value === '.') {
return parseJSXMemberExpression();
}
return parseJSXIdentifier();
}
function parseJSXAttributeName() {
if (lookahead2().value === ':') {
return parseJSXNamespacedName();
}
return parseJSXIdentifier();
}
function parseJSXAttributeValue() {
var value, marker;
if (match('{')) {
value = parseJSXExpressionContainer();
if (value.expression.type === Syntax.JSXEmptyExpression) {
throwError(
value,
'JSX attributes must only be assigned a non-empty ' +
'expression'
);
}
} else if (match('<')) {
value = parseJSXElement();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreate();
value = markerApply(marker, delegate.createLiteral(lex()));
} else {
throwError({}, Messages.InvalidJSXAttributeValue);
}
return value;
}
function parseJSXEmptyExpression() {
var marker = markerCreatePreserveWhitespace();
while (source.charAt(index) !== '}') {
index++;
}
return markerApply(marker, delegate.createJSXEmptyExpression());
}
function parseJSXExpressionContainer() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
if (match('}')) {
expression = parseJSXEmptyExpression();
} else {
expression = parseExpression();
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXExpressionContainer(expression));
}
function parseJSXSpreadAttribute() {
var expression, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = false;
expect('{');
expect('...');
expression = parseAssignmentExpression();
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('}');
return markerApply(marker, delegate.createJSXSpreadAttribute(expression));
}
function parseJSXAttribute() {
var name, marker;
if (match('{')) {
return parseJSXSpreadAttribute();
}
marker = markerCreate();
name = parseJSXAttributeName();
// HTML empty attribute
if (match('=')) {
lex();
return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue()));
}
return markerApply(marker, delegate.createJSXAttribute(name));
}
function parseJSXChild() {
var token, marker;
if (match('{')) {
token = parseJSXExpressionContainer();
} else if (lookahead.type === Token.JSXText) {
marker = markerCreatePreserveWhitespace();
token = markerApply(marker, delegate.createLiteral(lex()));
} else if (match('<')) {
token = parseJSXElement();
} else {
throwUnexpected(lookahead);
}
return token;
}
function parseJSXClosingElement() {
var name, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
expect('/');
name = parseJSXElementName();
// Because advance() (called by lex() called by expect()) expects there
// to be a valid token after >, it needs to know whether to look for a
// standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
expect('>');
return markerApply(marker, delegate.createJSXClosingElement(name));
}
function parseJSXOpeningElement() {
var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
state.inJSXChild = false;
state.inJSXTag = true;
expect('<');
name = parseJSXElementName();
while (index < length &&
lookahead.value !== '/' &&
lookahead.value !== '>') {
attributes.push(parseJSXAttribute());
}
state.inJSXTag = origInJSXTag;
if (lookahead.value === '/') {
expect('/');
// Because advance() (called by lex() called by expect()) expects
// there to be a valid token after >, it needs to know whether to
// look for a standard JS token or an JSX text node
state.inJSXChild = origInJSXChild;
expect('>');
selfClosing = true;
} else {
state.inJSXChild = true;
expect('>');
}
return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing));
}
function parseJSXElement() {
var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate();
origInJSXChild = state.inJSXChild;
origInJSXTag = state.inJSXTag;
openingElement = parseJSXOpeningElement();
if (!openingElement.selfClosing) {
while (index < length) {
state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because </ should not be considered in the child
if (lookahead.value === '<' && lookahead2().value === '/') {
break;
}
state.inJSXChild = true;
children.push(parseJSXChild());
}
state.inJSXChild = origInJSXChild;
state.inJSXTag = origInJSXTag;
closingElement = parseJSXClosingElement();
if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
throwError({}, Messages.ExpectedJSXClosingTag, getQualifiedJSXName(openingElement.name));
}
}
// When (erroneously) writing two adjacent tags like
//
// var x = <div>one</div><div>two</div>;
//
// the default error message is a bit incomprehensible. Since it's
// rarely (never?) useful to write a less-than sign after an JSX
// element, we disallow it here in the parser in order to provide a
// better error message. (In the rare case that the less-than operator
// was intended, the left tag can be wrapped in parentheses.)
if (!origInJSXChild && match('<')) {
throwError(lookahead, Messages.AdjacentJSXElements);
}
return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children));
}
function parseTypeAlias() {
var id, marker = markerCreate(), typeParameters = null, right;
expectContextualKeyword('type');
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('=');
right = parseType();
consumeSemicolon();
return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right));
}
function parseInterfaceExtends() {
var marker = markerCreate(), id, typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterInstantiation();
}
return markerApply(marker, delegate.createInterfaceExtends(
id,
typeParameters
));
}
function parseInterfaceish(marker, allowStatic) {
var body, bodyMarker, extended = [], id,
typeParameters = null;
id = parseVariableIdentifier();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
if (matchKeyword('extends')) {
expectKeyword('extends');
while (index < length) {
extended.push(parseInterfaceExtends());
if (!match(',')) {
break;
}
expect(',');
}
}
bodyMarker = markerCreate();
body = markerApply(bodyMarker, parseObjectType(allowStatic));
return markerApply(marker, delegate.createInterface(
id,
typeParameters,
body,
extended
));
}
function parseInterface() {
var marker = markerCreate();
if (strict) {
expectKeyword('interface');
} else {
expectContextualKeyword('interface');
}
return parseInterfaceish(marker, /* allowStatic */false);
}
function parseDeclareClass() {
var marker = markerCreate(), ret;
expectContextualKeyword('declare');
expectKeyword('class');
ret = parseInterfaceish(marker, /* allowStatic */true);
ret.type = Syntax.DeclareClass;
return ret;
}
function parseDeclareFunction() {
var id, idMarker,
marker = markerCreate(), params, returnType, rest, tmp,
typeParameters = null, value, valueMarker;
expectContextualKeyword('declare');
expectKeyword('function');
idMarker = markerCreate();
id = parseVariableIdentifier();
valueMarker = markerCreate();
if (match('<')) {
typeParameters = parseTypeParameterDeclaration();
}
expect('(');
tmp = parseFunctionTypeParams();
params = tmp.params;
rest = tmp.rest;
expect(')');
expect(':');
returnType = parseType();
value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation(
params,
returnType,
rest,
typeParameters
));
id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation(
value
));
markerApply(idMarker, id);
consumeSemicolon();
return markerApply(marker, delegate.createDeclareFunction(
id
));
}
function parseDeclareVariable() {
var id, marker = markerCreate();
expectContextualKeyword('declare');
expectKeyword('var');
id = parseTypeAnnotatableIdentifier();
consumeSemicolon();
return markerApply(marker, delegate.createDeclareVariable(
id
));
}
function parseDeclareModule() {
var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token;
expectContextualKeyword('declare');
expectContextualKeyword('module');
if (lookahead.type === Token.StringLiteral) {
if (strict && lookahead.octal) {
throwErrorTolerant(lookahead, Messages.StrictOctalLiteral);
}
idMarker = markerCreate();
id = markerApply(idMarker, delegate.createLiteral(lex()));
} else {
id = parseVariableIdentifier();
}
bodyMarker = markerCreate();
expect('{');
while (index < length && !match('}')) {
token = lookahead2();
switch (token.value) {
case 'class':
body.push(parseDeclareClass());
break;
case 'function':
body.push(parseDeclareFunction());
break;
case 'var':
body.push(parseDeclareVariable());
break;
default:
throwUnexpected(lookahead);
}
}
expect('}');
return markerApply(marker, delegate.createDeclareModule(
id,
markerApply(bodyMarker, delegate.createBlockStatement(body))
));
}
function collectToken() {
var loc, token, range, value, entry;
/* istanbul ignore else */
if (!state.inJSXChild) {
skipComment();
}
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
token = extra.advance();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (token.type !== Token.EOF) {
range = [token.range[0], token.range[1]];
value = source.slice(token.range[0], token.range[1]);
entry = {
type: TokenName[token.type],
value: value,
range: range,
loc: loc
};
if (token.regex) {
entry.regex = {
pattern: token.regex.pattern,
flags: token.regex.flags
};
}
extra.tokens.push(entry);
}
return token;
}
function collectRegex() {
var pos, loc, regex, token;
skipComment();
pos = index;
loc = {
start: {
line: lineNumber,
column: index - lineStart
}
};
regex = extra.scanRegExp();
loc.end = {
line: lineNumber,
column: index - lineStart
};
if (!extra.tokenize) {
/* istanbul ignore next */
// Pop the previous token, which is likely '/' or '/='
if (extra.tokens.length > 0) {
token = extra.tokens[extra.tokens.length - 1];
if (token.range[0] === pos && token.type === 'Punctuator') {
if (token.value === '/' || token.value === '/=') {
extra.tokens.pop();
}
}
}
extra.tokens.push({
type: 'RegularExpression',
value: regex.literal,
regex: regex.regex,
range: [pos, index],
loc: loc
});
}
return regex;
}
function filterTokenLocation() {
var i, entry, token, tokens = [];
for (i = 0; i < extra.tokens.length; ++i) {
entry = extra.tokens[i];
token = {
type: entry.type,
value: entry.value
};
if (entry.regex) {
token.regex = {
pattern: entry.regex.pattern,
flags: entry.regex.flags
};
}
if (extra.range) {
token.range = entry.range;
}
if (extra.loc) {
token.loc = entry.loc;
}
tokens.push(token);
}
extra.tokens = tokens;
}
function patch() {
if (typeof extra.tokens !== 'undefined') {
extra.advance = advance;
extra.scanRegExp = scanRegExp;
advance = collectToken;
scanRegExp = collectRegex;
}
}
function unpatch() {
if (typeof extra.scanRegExp === 'function') {
advance = extra.advance;
scanRegExp = extra.scanRegExp;
}
}
// This is used to modify the delegate.
function extend(object, properties) {
var entry, result = {};
for (entry in object) {
/* istanbul ignore else */
if (object.hasOwnProperty(entry)) {
result[entry] = object[entry];
}
}
for (entry in properties) {
/* istanbul ignore else */
if (properties.hasOwnProperty(entry)) {
result[entry] = properties[entry];
}
}
return result;
}
function tokenize(code, options) {
var toString,
token,
tokens;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: true,
allowIn: true,
labelSet: new StringMap(),
inFunctionBody: false,
inIteration: false,
inSwitch: false,
lastCommentStart: -1
};
extra = {};
// Options matching.
options = options || {};
// Of course we collect tokens here.
options.tokens = true;
extra.tokens = [];
extra.tokenize = true;
// The following two fields are necessary to compute the Regex tokens.
extra.openParenToken = -1;
extra.openCurlyToken = -1;
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
patch();
try {
peek();
if (lookahead.type === Token.EOF) {
return extra.tokens;
}
token = lex();
while (lookahead.type !== Token.EOF) {
try {
token = lex();
} catch (lexError) {
token = lookahead;
if (extra.errors) {
extra.errors.push(lexError);
// We have to break on the first error
// to avoid infinite loops.
break;
} else {
throw lexError;
}
}
}
filterTokenLocation();
tokens = extra.tokens;
if (typeof extra.comments !== 'undefined') {
tokens.comments = extra.comments;
}
if (typeof extra.errors !== 'undefined') {
tokens.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return tokens;
}
function parse(code, options) {
var program, toString;
toString = String;
if (typeof code !== 'string' && !(code instanceof String)) {
code = toString(code);
}
delegate = SyntaxTreeDelegate;
source = code;
index = 0;
lineNumber = (source.length > 0) ? 1 : 0;
lineStart = 0;
length = source.length;
lookahead = null;
state = {
allowKeyword: false,
allowIn: true,
labelSet: new StringMap(),
parenthesizedCount: 0,
inFunctionBody: false,
inIteration: false,
inSwitch: false,
inJSXChild: false,
inJSXTag: false,
inType: false,
lastCommentStart: -1,
yieldAllowed: false,
awaitAllowed: false
};
extra = {};
if (typeof options !== 'undefined') {
extra.range = (typeof options.range === 'boolean') && options.range;
extra.loc = (typeof options.loc === 'boolean') && options.loc;
extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment;
if (extra.loc && options.source !== null && options.source !== undefined) {
delegate = extend(delegate, {
'postProcess': function (node) {
node.loc.source = toString(options.source);
return node;
}
});
}
extra.sourceType = options.sourceType;
if (typeof options.tokens === 'boolean' && options.tokens) {
extra.tokens = [];
}
if (typeof options.comment === 'boolean' && options.comment) {
extra.comments = [];
}
if (typeof options.tolerant === 'boolean' && options.tolerant) {
extra.errors = [];
}
if (extra.attachComment) {
extra.range = true;
extra.comments = [];
extra.bottomRightStack = [];
extra.trailingComments = [];
extra.leadingComments = [];
}
}
patch();
try {
program = parseProgram();
if (typeof extra.comments !== 'undefined') {
program.comments = extra.comments;
}
if (typeof extra.tokens !== 'undefined') {
filterTokenLocation();
program.tokens = extra.tokens;
}
if (typeof extra.errors !== 'undefined') {
program.errors = extra.errors;
}
} catch (e) {
throw e;
} finally {
unpatch();
extra = {};
}
return program;
}
// Sync with *.json manifests.
exports.version = '13001.1001.0-dev-harmony-fb';
exports.tokenize = tokenize;
exports.parse = parse;
// Deep copy.
/* istanbul ignore next */
exports.Syntax = (function () {
var name, types = {};
if (typeof Object.create === 'function') {
types = Object.create(null);
}
for (name in Syntax) {
if (Syntax.hasOwnProperty(name)) {
types[name] = Syntax[name];
}
}
if (typeof Object.freeze === 'function') {
Object.freeze(types);
}
return types;
}());
}));
/* vim: set sw=4 ts=4 et tw=80 : */
},{}],10:[function(_dereq_,module,exports){
var Base62 = (function (my) {
my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
my.encode = function(i){
if (i === 0) {return '0'}
var s = ''
while (i > 0) {
s = this.chars[i % 62] + s
i = Math.floor(i/62)
}
return s
};
my.decode = function(a,b,c,d){
for (
b = c = (
a === (/\W|_|^$/.test(a += "") || a)
) - 1;
d = a.charCodeAt(c++);
)
b = b * 62 + d - [, 48, 29, 87][d >> 5];
return b
};
return my;
}({}));
module.exports = Base62
},{}],11:[function(_dereq_,module,exports){
/*
* Copyright 2009-2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE.txt or:
* http://opensource.org/licenses/BSD-3-Clause
*/
exports.SourceMapGenerator = _dereq_('./source-map/source-map-generator').SourceMapGenerator;
exports.SourceMapConsumer = _dereq_('./source-map/source-map-consumer').SourceMapConsumer;
exports.SourceNode = _dereq_('./source-map/source-node').SourceNode;
},{"./source-map/source-map-consumer":16,"./source-map/source-map-generator":17,"./source-map/source-node":18}],12:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
function ArraySet() {
this._array = [];
this._set = {};
}
/**
* Static method for creating ArraySet instances from an existing array.
*/
ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
var set = new ArraySet();
for (var i = 0, len = aArray.length; i < len; i++) {
set.add(aArray[i], aAllowDuplicates);
}
return set;
};
/**
* Add the given string to this set.
*
* @param String aStr
*/
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
var isDuplicate = this.has(aStr);
var idx = this._array.length;
if (!isDuplicate || aAllowDuplicates) {
this._array.push(aStr);
}
if (!isDuplicate) {
this._set[util.toSetString(aStr)] = idx;
}
};
/**
* Is the given string a member of this set?
*
* @param String aStr
*/
ArraySet.prototype.has = function ArraySet_has(aStr) {
return Object.prototype.hasOwnProperty.call(this._set,
util.toSetString(aStr));
};
/**
* What is the index of the given string in the array?
*
* @param String aStr
*/
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
if (this.has(aStr)) {
return this._set[util.toSetString(aStr)];
}
throw new Error('"' + aStr + '" is not in the set.');
};
/**
* What is the element at the given index?
*
* @param Number aIdx
*/
ArraySet.prototype.at = function ArraySet_at(aIdx) {
if (aIdx >= 0 && aIdx < this._array.length) {
return this._array[aIdx];
}
throw new Error('No element indexed by ' + aIdx);
};
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
ArraySet.prototype.toArray = function ArraySet_toArray() {
return this._array.slice();
};
exports.ArraySet = ArraySet;
});
},{"./util":19,"amdefine":20}],13:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*
* Based on the Base 64 VLQ implementation in Closure Compiler:
* https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
*
* Copyright 2011 The Closure Compiler Authors. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64 = _dereq_('./base64');
// A single base 64 digit can contain 6 bits of data. For the base 64 variable
// length quantities we use in the source map spec, the first bit is the sign,
// the next four bits are the actual value, and the 6th bit is the
// continuation bit. The continuation bit tells us whether there are more
// digits in this value following this digit.
//
// Continuation
// | Sign
// | |
// V V
// 101011
var VLQ_BASE_SHIFT = 5;
// binary: 100000
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
// binary: 011111
var VLQ_BASE_MASK = VLQ_BASE - 1;
// binary: 100000
var VLQ_CONTINUATION_BIT = VLQ_BASE;
/**
* Converts from a two-complement value to a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
* 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
*/
function toVLQSigned(aValue) {
return aValue < 0
? ((-aValue) << 1) + 1
: (aValue << 1) + 0;
}
/**
* Converts to a two-complement value from a value where the sign bit is
* is placed in the least significant bit. For example, as decimals:
* 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
* 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
*/
function fromVLQSigned(aValue) {
var isNegative = (aValue & 1) === 1;
var shifted = aValue >> 1;
return isNegative
? -shifted
: shifted;
}
/**
* Returns the base 64 VLQ encoded value.
*/
exports.encode = function base64VLQ_encode(aValue) {
var encoded = "";
var digit;
var vlq = toVLQSigned(aValue);
do {
digit = vlq & VLQ_BASE_MASK;
vlq >>>= VLQ_BASE_SHIFT;
if (vlq > 0) {
// There are still more digits in this value, so we must make sure the
// continuation bit is marked.
digit |= VLQ_CONTINUATION_BIT;
}
encoded += base64.encode(digit);
} while (vlq > 0);
return encoded;
};
/**
* Decodes the next base 64 VLQ value from the given string and returns the
* value and the rest of the string.
*/
exports.decode = function base64VLQ_decode(aStr) {
var i = 0;
var strLen = aStr.length;
var result = 0;
var shift = 0;
var continuation, digit;
do {
if (i >= strLen) {
throw new Error("Expected more digits in base 64 VLQ value.");
}
digit = base64.decode(aStr.charAt(i++));
continuation = !!(digit & VLQ_CONTINUATION_BIT);
digit &= VLQ_BASE_MASK;
result = result + (digit << shift);
shift += VLQ_BASE_SHIFT;
} while (continuation);
return {
value: fromVLQSigned(result),
rest: aStr.slice(i)
};
};
});
},{"./base64":14,"amdefine":20}],14:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var charToIntMap = {};
var intToCharMap = {};
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
.split('')
.forEach(function (ch, index) {
charToIntMap[ch] = index;
intToCharMap[index] = ch;
});
/**
* Encode an integer in the range of 0 to 63 to a single base 64 digit.
*/
exports.encode = function base64_encode(aNumber) {
if (aNumber in intToCharMap) {
return intToCharMap[aNumber];
}
throw new TypeError("Must be between 0 and 63: " + aNumber);
};
/**
* Decode a single base 64 digit to an integer.
*/
exports.decode = function base64_decode(aChar) {
if (aChar in charToIntMap) {
return charToIntMap[aChar];
}
throw new TypeError("Not a valid base 64 digit: " + aChar);
};
});
},{"amdefine":20}],15:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* Recursive implementation of binary search.
*
* @param aLow Indices here and lower do not contain the needle.
* @param aHigh Indices here and higher do not contain the needle.
* @param aNeedle The element being searched for.
* @param aHaystack The non-empty array being searched.
* @param aCompare Function which takes two elements and returns -1, 0, or 1.
*/
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
// This function terminates when one of the following is true:
//
// 1. We find the exact element we are looking for.
//
// 2. We did not find the exact element, but we can return the next
// closest element that is less than that element.
//
// 3. We did not find the exact element, and there is no next-closest
// element which is less than the one we are searching for, so we
// return null.
var mid = Math.floor((aHigh - aLow) / 2) + aLow;
var cmp = aCompare(aNeedle, aHaystack[mid], true);
if (cmp === 0) {
// Found the element we are looking for.
return aHaystack[mid];
}
else if (cmp > 0) {
// aHaystack[mid] is greater than our needle.
if (aHigh - mid > 1) {
// The element is in the upper half.
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
}
// We did not find an exact match, return the next closest one
// (termination case 2).
return aHaystack[mid];
}
else {
// aHaystack[mid] is less than our needle.
if (mid - aLow > 1) {
// The element is in the lower half.
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
}
// The exact needle element was not found in this haystack. Determine if
// we are in termination case (2) or (3) and return the appropriate thing.
return aLow < 0
? null
: aHaystack[aLow];
}
}
/**
* This is an implementation of binary search which will always try and return
* the next lowest value checked if there is no exact hit. This is because
* mappings between original and generated line/col pairs are single points,
* and there is an implicit region between each of them, so a miss just means
* that you aren't on the very start of a region.
*
* @param aNeedle The element you are looking for.
* @param aHaystack The array that is being searched.
* @param aCompare A function which takes the needle and an element in the
* array and returns -1, 0, or 1 depending on whether the needle is less
* than, equal to, or greater than the element, respectively.
*/
exports.search = function search(aNeedle, aHaystack, aCompare) {
return aHaystack.length > 0
? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
: null;
};
});
},{"amdefine":20}],16:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var util = _dereq_('./util');
var binarySearch = _dereq_('./binary-search');
var ArraySet = _dereq_('./array-set').ArraySet;
var base64VLQ = _dereq_('./base64-vlq');
/**
* A SourceMapConsumer instance represents a parsed source map which we can
* query for information about the original file positions by giving it a file
* position in the generated source.
*
* The only parameter is the raw source map (either as a JSON string, or
* already parsed to an object). According to the spec, source maps have the
* following attributes:
*
* - version: Which version of the source map spec this map is following.
* - sources: An array of URLs to the original source files.
* - names: An array of identifiers which can be referrenced by individual mappings.
* - sourceRoot: Optional. The URL root from which all sources are relative.
* - sourcesContent: Optional. An array of contents of the original source files.
* - mappings: A string of base64 VLQs which contain the actual mappings.
* - file: The generated file this source map is associated with.
*
* Here is an example source map, taken from the source map spec[0]:
*
* {
* version : 3,
* file: "out.js",
* sourceRoot : "",
* sources: ["foo.js", "bar.js"],
* names: ["src", "maps", "are", "fun"],
* mappings: "AA,AB;;ABCDE;"
* }
*
* [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
*/
function SourceMapConsumer(aSourceMap) {
var sourceMap = aSourceMap;
if (typeof aSourceMap === 'string') {
sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
}
var version = util.getArg(sourceMap, 'version');
var sources = util.getArg(sourceMap, 'sources');
// Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
// requires the array) to play nice here.
var names = util.getArg(sourceMap, 'names', []);
var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
var mappings = util.getArg(sourceMap, 'mappings');
var file = util.getArg(sourceMap, 'file', null);
// Once again, Sass deviates from the spec and supplies the version as a
// string rather than a number, so we use loose equality checking here.
if (version != this._version) {
throw new Error('Unsupported version: ' + version);
}
// Pass `true` below to allow duplicate names and sources. While source maps
// are intended to be compressed and deduplicated, the TypeScript compiler
// sometimes generates source maps with duplicates in them. See Github issue
// #72 and bugzil.la/889492.
this._names = ArraySet.fromArray(names, true);
this._sources = ArraySet.fromArray(sources, true);
this.sourceRoot = sourceRoot;
this.sourcesContent = sourcesContent;
this._mappings = mappings;
this.file = file;
}
/**
* Create a SourceMapConsumer from a SourceMapGenerator.
*
* @param SourceMapGenerator aSourceMap
* The source map that will be consumed.
* @returns SourceMapConsumer
*/
SourceMapConsumer.fromSourceMap =
function SourceMapConsumer_fromSourceMap(aSourceMap) {
var smc = Object.create(SourceMapConsumer.prototype);
smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
smc.sourceRoot = aSourceMap._sourceRoot;
smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
smc.sourceRoot);
smc.file = aSourceMap._file;
smc.__generatedMappings = aSourceMap._mappings.slice()
.sort(util.compareByGeneratedPositions);
smc.__originalMappings = aSourceMap._mappings.slice()
.sort(util.compareByOriginalPositions);
return smc;
};
/**
* The version of the source mapping spec that we are consuming.
*/
SourceMapConsumer.prototype._version = 3;
/**
* The list of original sources.
*/
Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
get: function () {
return this._sources.toArray().map(function (s) {
return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
}, this);
}
});
// `__generatedMappings` and `__originalMappings` are arrays that hold the
// parsed mapping coordinates from the source map's "mappings" attribute. They
// are lazily instantiated, accessed via the `_generatedMappings` and
// `_originalMappings` getters respectively, and we only parse the mappings
// and create these arrays once queried for a source location. We jump through
// these hoops because there can be many thousands of mappings, and parsing
// them is expensive, so we only want to do it if we must.
//
// Each object in the arrays is of the form:
//
// {
// generatedLine: The line number in the generated code,
// generatedColumn: The column number in the generated code,
// source: The path to the original source file that generated this
// chunk of code,
// originalLine: The line number in the original source that
// corresponds to this chunk of generated code,
// originalColumn: The column number in the original source that
// corresponds to this chunk of generated code,
// name: The name of the original symbol which generated this chunk of
// code.
// }
//
// All properties except for `generatedLine` and `generatedColumn` can be
// `null`.
//
// `_generatedMappings` is ordered by the generated positions.
//
// `_originalMappings` is ordered by the original positions.
SourceMapConsumer.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
get: function () {
if (!this.__generatedMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__generatedMappings;
}
});
SourceMapConsumer.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
get: function () {
if (!this.__originalMappings) {
this.__generatedMappings = [];
this.__originalMappings = [];
this._parseMappings(this._mappings, this.sourceRoot);
}
return this.__originalMappings;
}
});
/**
* Parse the mappings in a string in to a data structure which we can easily
* query (the ordered arrays in the `this.__generatedMappings` and
* `this.__originalMappings` properties).
*/
SourceMapConsumer.prototype._parseMappings =
function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
var generatedLine = 1;
var previousGeneratedColumn = 0;
var previousOriginalLine = 0;
var previousOriginalColumn = 0;
var previousSource = 0;
var previousName = 0;
var mappingSeparator = /^[,;]/;
var str = aStr;
var mapping;
var temp;
while (str.length > 0) {
if (str.charAt(0) === ';') {
generatedLine++;
str = str.slice(1);
previousGeneratedColumn = 0;
}
else if (str.charAt(0) === ',') {
str = str.slice(1);
}
else {
mapping = {};
mapping.generatedLine = generatedLine;
// Generated column.
temp = base64VLQ.decode(str);
mapping.generatedColumn = previousGeneratedColumn + temp.value;
previousGeneratedColumn = mapping.generatedColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original source.
temp = base64VLQ.decode(str);
mapping.source = this._sources.at(previousSource + temp.value);
previousSource += temp.value;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source, but no line and column');
}
// Original line.
temp = base64VLQ.decode(str);
mapping.originalLine = previousOriginalLine + temp.value;
previousOriginalLine = mapping.originalLine;
// Lines are stored 0-based
mapping.originalLine += 1;
str = temp.rest;
if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
throw new Error('Found a source and line, but no column');
}
// Original column.
temp = base64VLQ.decode(str);
mapping.originalColumn = previousOriginalColumn + temp.value;
previousOriginalColumn = mapping.originalColumn;
str = temp.rest;
if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
// Original name.
temp = base64VLQ.decode(str);
mapping.name = this._names.at(previousName + temp.value);
previousName += temp.value;
str = temp.rest;
}
}
this.__generatedMappings.push(mapping);
if (typeof mapping.originalLine === 'number') {
this.__originalMappings.push(mapping);
}
}
}
this.__originalMappings.sort(util.compareByOriginalPositions);
};
/**
* Find the mapping that best matches the hypothetical "needle" mapping that
* we are searching for in the given "haystack" of mappings.
*/
SourceMapConsumer.prototype._findMapping =
function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
aColumnName, aComparator) {
// To return the position we are searching for, we must first find the
// mapping for the given position and then return the opposite position it
// points to. Because the mappings are sorted, we can use binary search to
// find the best mapping.
if (aNeedle[aLineName] <= 0) {
throw new TypeError('Line must be greater than or equal to 1, got '
+ aNeedle[aLineName]);
}
if (aNeedle[aColumnName] < 0) {
throw new TypeError('Column must be greater than or equal to 0, got '
+ aNeedle[aColumnName]);
}
return binarySearch.search(aNeedle, aMappings, aComparator);
};
/**
* Returns the original source, line, and column information for the generated
* source's line and column positions provided. The only argument is an object
* with the following properties:
*
* - line: The line number in the generated source.
* - column: The column number in the generated source.
*
* and an object is returned with the following properties:
*
* - source: The original source file, or null.
* - line: The line number in the original source, or null.
* - column: The column number in the original source, or null.
* - name: The original identifier, or null.
*/
SourceMapConsumer.prototype.originalPositionFor =
function SourceMapConsumer_originalPositionFor(aArgs) {
var needle = {
generatedLine: util.getArg(aArgs, 'line'),
generatedColumn: util.getArg(aArgs, 'column')
};
var mapping = this._findMapping(needle,
this._generatedMappings,
"generatedLine",
"generatedColumn",
util.compareByGeneratedPositions);
if (mapping) {
var source = util.getArg(mapping, 'source', null);
if (source && this.sourceRoot) {
source = util.join(this.sourceRoot, source);
}
return {
source: source,
line: util.getArg(mapping, 'originalLine', null),
column: util.getArg(mapping, 'originalColumn', null),
name: util.getArg(mapping, 'name', null)
};
}
return {
source: null,
line: null,
column: null,
name: null
};
};
/**
* Returns the original source content. The only argument is the url of the
* original source file. Returns null if no original source content is
* availible.
*/
SourceMapConsumer.prototype.sourceContentFor =
function SourceMapConsumer_sourceContentFor(aSource) {
if (!this.sourcesContent) {
return null;
}
if (this.sourceRoot) {
aSource = util.relative(this.sourceRoot, aSource);
}
if (this._sources.has(aSource)) {
return this.sourcesContent[this._sources.indexOf(aSource)];
}
var url;
if (this.sourceRoot
&& (url = util.urlParse(this.sourceRoot))) {
// XXX: file:// URIs and absolute paths lead to unexpected behavior for
// many users. We can help them out when they expect file:// URIs to
// behave like it would if they were running a local HTTP server. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
if (url.scheme == "file"
&& this._sources.has(fileUriAbsPath)) {
return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
}
if ((!url.path || url.path == "/")
&& this._sources.has("/" + aSource)) {
return this.sourcesContent[this._sources.indexOf("/" + aSource)];
}
}
throw new Error('"' + aSource + '" is not in the SourceMap.');
};
/**
* Returns the generated line and column information for the original source,
* line, and column positions provided. The only argument is an object with
* the following properties:
*
* - source: The filename of the original source.
* - line: The line number in the original source.
* - column: The column number in the original source.
*
* and an object is returned with the following properties:
*
* - line: The line number in the generated source, or null.
* - column: The column number in the generated source, or null.
*/
SourceMapConsumer.prototype.generatedPositionFor =
function SourceMapConsumer_generatedPositionFor(aArgs) {
var needle = {
source: util.getArg(aArgs, 'source'),
originalLine: util.getArg(aArgs, 'line'),
originalColumn: util.getArg(aArgs, 'column')
};
if (this.sourceRoot) {
needle.source = util.relative(this.sourceRoot, needle.source);
}
var mapping = this._findMapping(needle,
this._originalMappings,
"originalLine",
"originalColumn",
util.compareByOriginalPositions);
if (mapping) {
return {
line: util.getArg(mapping, 'generatedLine', null),
column: util.getArg(mapping, 'generatedColumn', null)
};
}
return {
line: null,
column: null
};
};
SourceMapConsumer.GENERATED_ORDER = 1;
SourceMapConsumer.ORIGINAL_ORDER = 2;
/**
* Iterate over each mapping between an original source/line/column and a
* generated line/column in this source map.
*
* @param Function aCallback
* The function that is called with each mapping.
* @param Object aContext
* Optional. If specified, this object will be the value of `this` every
* time that `aCallback` is called.
* @param aOrder
* Either `SourceMapConsumer.GENERATED_ORDER` or
* `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
* iterate over the mappings sorted by the generated file's line/column
* order or the original's source/line/column order, respectively. Defaults to
* `SourceMapConsumer.GENERATED_ORDER`.
*/
SourceMapConsumer.prototype.eachMapping =
function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
var context = aContext || null;
var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
var mappings;
switch (order) {
case SourceMapConsumer.GENERATED_ORDER:
mappings = this._generatedMappings;
break;
case SourceMapConsumer.ORIGINAL_ORDER:
mappings = this._originalMappings;
break;
default:
throw new Error("Unknown order of iteration.");
}
var sourceRoot = this.sourceRoot;
mappings.map(function (mapping) {
var source = mapping.source;
if (source && sourceRoot) {
source = util.join(sourceRoot, source);
}
return {
source: source,
generatedLine: mapping.generatedLine,
generatedColumn: mapping.generatedColumn,
originalLine: mapping.originalLine,
originalColumn: mapping.originalColumn,
name: mapping.name
};
}).forEach(aCallback, context);
};
exports.SourceMapConsumer = SourceMapConsumer;
});
},{"./array-set":12,"./base64-vlq":13,"./binary-search":15,"./util":19,"amdefine":20}],17:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var base64VLQ = _dereq_('./base64-vlq');
var util = _dereq_('./util');
var ArraySet = _dereq_('./array-set').ArraySet;
/**
* An instance of the SourceMapGenerator represents a source map which is
* being built incrementally. To create a new one, you must pass an object
* with the following properties:
*
* - file: The filename of the generated source.
* - sourceRoot: An optional root for all URLs in this source map.
*/
function SourceMapGenerator(aArgs) {
this._file = util.getArg(aArgs, 'file');
this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
this._sources = new ArraySet();
this._names = new ArraySet();
this._mappings = [];
this._sourcesContents = null;
}
SourceMapGenerator.prototype._version = 3;
/**
* Creates a new SourceMapGenerator based on a SourceMapConsumer
*
* @param aSourceMapConsumer The SourceMap.
*/
SourceMapGenerator.fromSourceMap =
function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
var sourceRoot = aSourceMapConsumer.sourceRoot;
var generator = new SourceMapGenerator({
file: aSourceMapConsumer.file,
sourceRoot: sourceRoot
});
aSourceMapConsumer.eachMapping(function (mapping) {
var newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn
}
};
if (mapping.source) {
newMapping.source = mapping.source;
if (sourceRoot) {
newMapping.source = util.relative(sourceRoot, newMapping.source);
}
newMapping.original = {
line: mapping.originalLine,
column: mapping.originalColumn
};
if (mapping.name) {
newMapping.name = mapping.name;
}
}
generator.addMapping(newMapping);
});
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
generator.setSourceContent(sourceFile, content);
}
});
return generator;
};
/**
* Add a single mapping from original source line and column to the generated
* source's line and column for this source map being created. The mapping
* object should have the following properties:
*
* - generated: An object with the generated line and column positions.
* - original: An object with the original line and column positions.
* - source: The original source file (relative to the sourceRoot).
* - name: An optional original token name for this mapping.
*/
SourceMapGenerator.prototype.addMapping =
function SourceMapGenerator_addMapping(aArgs) {
var generated = util.getArg(aArgs, 'generated');
var original = util.getArg(aArgs, 'original', null);
var source = util.getArg(aArgs, 'source', null);
var name = util.getArg(aArgs, 'name', null);
this._validateMapping(generated, original, source, name);
if (source && !this._sources.has(source)) {
this._sources.add(source);
}
if (name && !this._names.has(name)) {
this._names.add(name);
}
this._mappings.push({
generatedLine: generated.line,
generatedColumn: generated.column,
originalLine: original != null && original.line,
originalColumn: original != null && original.column,
source: source,
name: name
});
};
/**
* Set the source content for a source file.
*/
SourceMapGenerator.prototype.setSourceContent =
function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
var source = aSourceFile;
if (this._sourceRoot) {
source = util.relative(this._sourceRoot, source);
}
if (aSourceContent !== null) {
// Add the source content to the _sourcesContents map.
// Create a new _sourcesContents map if the property is null.
if (!this._sourcesContents) {
this._sourcesContents = {};
}
this._sourcesContents[util.toSetString(source)] = aSourceContent;
} else {
// Remove the source file from the _sourcesContents map.
// If the _sourcesContents map is empty, set the property to null.
delete this._sourcesContents[util.toSetString(source)];
if (Object.keys(this._sourcesContents).length === 0) {
this._sourcesContents = null;
}
}
};
/**
* Applies the mappings of a sub-source-map for a specific source file to the
* source map being generated. Each mapping to the supplied source file is
* rewritten using the supplied source map. Note: The resolution for the
* resulting mappings is the minimium of this map and the supplied map.
*
* @param aSourceMapConsumer The source map to be applied.
* @param aSourceFile Optional. The filename of the source file.
* If omitted, SourceMapConsumer's file property will be used.
*/
SourceMapGenerator.prototype.applySourceMap =
function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
// If aSourceFile is omitted, we will use the file property of the SourceMap
if (!aSourceFile) {
aSourceFile = aSourceMapConsumer.file;
}
var sourceRoot = this._sourceRoot;
// Make "aSourceFile" relative if an absolute Url is passed.
if (sourceRoot) {
aSourceFile = util.relative(sourceRoot, aSourceFile);
}
// Applying the SourceMap can add and remove items from the sources and
// the names array.
var newSources = new ArraySet();
var newNames = new ArraySet();
// Find mappings for the "aSourceFile"
this._mappings.forEach(function (mapping) {
if (mapping.source === aSourceFile && mapping.originalLine) {
// Check if it can be mapped by the source map, then update the mapping.
var original = aSourceMapConsumer.originalPositionFor({
line: mapping.originalLine,
column: mapping.originalColumn
});
if (original.source !== null) {
// Copy mapping
if (sourceRoot) {
mapping.source = util.relative(sourceRoot, original.source);
} else {
mapping.source = original.source;
}
mapping.originalLine = original.line;
mapping.originalColumn = original.column;
if (original.name !== null && mapping.name !== null) {
// Only use the identifier name if it's an identifier
// in both SourceMaps
mapping.name = original.name;
}
}
}
var source = mapping.source;
if (source && !newSources.has(source)) {
newSources.add(source);
}
var name = mapping.name;
if (name && !newNames.has(name)) {
newNames.add(name);
}
}, this);
this._sources = newSources;
this._names = newNames;
// Copy sourcesContents of applied map.
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
if (sourceRoot) {
sourceFile = util.relative(sourceRoot, sourceFile);
}
this.setSourceContent(sourceFile, content);
}
}, this);
};
/**
* A mapping can have one of the three levels of data:
*
* 1. Just the generated position.
* 2. The Generated position, original position, and original source.
* 3. Generated and original position, original source, as well as a name
* token.
*
* To maintain consistency, we validate that any new mapping being added falls
* in to one of these categories.
*/
SourceMapGenerator.prototype._validateMapping =
function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
aName) {
if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aGenerated.line > 0 && aGenerated.column >= 0
&& !aOriginal && !aSource && !aName) {
// Case 1.
return;
}
else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
&& aOriginal && 'line' in aOriginal && 'column' in aOriginal
&& aGenerated.line > 0 && aGenerated.column >= 0
&& aOriginal.line > 0 && aOriginal.column >= 0
&& aSource) {
// Cases 2 and 3.
return;
}
else {
throw new Error('Invalid mapping: ' + JSON.stringify({
generated: aGenerated,
source: aSource,
orginal: aOriginal,
name: aName
}));
}
};
/**
* Serialize the accumulated mappings in to the stream of base 64 VLQs
* specified by the source map format.
*/
SourceMapGenerator.prototype._serializeMappings =
function SourceMapGenerator_serializeMappings() {
var previousGeneratedColumn = 0;
var previousGeneratedLine = 1;
var previousOriginalColumn = 0;
var previousOriginalLine = 0;
var previousName = 0;
var previousSource = 0;
var result = '';
var mapping;
// The mappings must be guaranteed to be in sorted order before we start
// serializing them or else the generated line numbers (which are defined
// via the ';' separators) will be all messed up. Note: it might be more
// performant to maintain the sorting as we insert them, rather than as we
// serialize them, but the big O is the same either way.
this._mappings.sort(util.compareByGeneratedPositions);
for (var i = 0, len = this._mappings.length; i < len; i++) {
mapping = this._mappings[i];
if (mapping.generatedLine !== previousGeneratedLine) {
previousGeneratedColumn = 0;
while (mapping.generatedLine !== previousGeneratedLine) {
result += ';';
previousGeneratedLine++;
}
}
else {
if (i > 0) {
if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
continue;
}
result += ',';
}
}
result += base64VLQ.encode(mapping.generatedColumn
- previousGeneratedColumn);
previousGeneratedColumn = mapping.generatedColumn;
if (mapping.source) {
result += base64VLQ.encode(this._sources.indexOf(mapping.source)
- previousSource);
previousSource = this._sources.indexOf(mapping.source);
// lines are stored 0-based in SourceMap spec version 3
result += base64VLQ.encode(mapping.originalLine - 1
- previousOriginalLine);
previousOriginalLine = mapping.originalLine - 1;
result += base64VLQ.encode(mapping.originalColumn
- previousOriginalColumn);
previousOriginalColumn = mapping.originalColumn;
if (mapping.name) {
result += base64VLQ.encode(this._names.indexOf(mapping.name)
- previousName);
previousName = this._names.indexOf(mapping.name);
}
}
}
return result;
};
SourceMapGenerator.prototype._generateSourcesContent =
function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
return aSources.map(function (source) {
if (!this._sourcesContents) {
return null;
}
if (aSourceRoot) {
source = util.relative(aSourceRoot, source);
}
var key = util.toSetString(source);
return Object.prototype.hasOwnProperty.call(this._sourcesContents,
key)
? this._sourcesContents[key]
: null;
}, this);
};
/**
* Externalize the source map.
*/
SourceMapGenerator.prototype.toJSON =
function SourceMapGenerator_toJSON() {
var map = {
version: this._version,
file: this._file,
sources: this._sources.toArray(),
names: this._names.toArray(),
mappings: this._serializeMappings()
};
if (this._sourceRoot) {
map.sourceRoot = this._sourceRoot;
}
if (this._sourcesContents) {
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
}
return map;
};
/**
* Render the source map being generated to a string.
*/
SourceMapGenerator.prototype.toString =
function SourceMapGenerator_toString() {
return JSON.stringify(this);
};
exports.SourceMapGenerator = SourceMapGenerator;
});
},{"./array-set":12,"./base64-vlq":13,"./util":19,"amdefine":20}],18:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
var SourceMapGenerator = _dereq_('./source-map-generator').SourceMapGenerator;
var util = _dereq_('./util');
/**
* SourceNodes provide a way to abstract over interpolating/concatenating
* snippets of generated JavaScript source code while maintaining the line and
* column information associated with the original source code.
*
* @param aLine The original line number.
* @param aColumn The original column number.
* @param aSource The original source's filename.
* @param aChunks Optional. An array of strings which are snippets of
* generated JS, or other SourceNodes.
* @param aName The original identifier.
*/
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
this.children = [];
this.sourceContents = {};
this.line = aLine === undefined ? null : aLine;
this.column = aColumn === undefined ? null : aColumn;
this.source = aSource === undefined ? null : aSource;
this.name = aName === undefined ? null : aName;
if (aChunks != null) this.add(aChunks);
}
/**
* Creates a SourceNode from generated code and a SourceMapConsumer.
*
* @param aGeneratedCode The generated code
* @param aSourceMapConsumer The SourceMap for the generated code
*/
SourceNode.fromStringWithSourceMap =
function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
// The SourceNode we want to fill with the generated code
// and the SourceMap
var node = new SourceNode();
// The generated code
// Processed fragments are removed from this array.
var remainingLines = aGeneratedCode.split('\n');
// We need to remember the position of "remainingLines"
var lastGeneratedLine = 1, lastGeneratedColumn = 0;
// The generate SourceNodes we need a code range.
// To extract it current and last mapping is used.
// Here we store the last mapping.
var lastMapping = null;
aSourceMapConsumer.eachMapping(function (mapping) {
if (lastMapping === null) {
// We add the generated code until the first mapping
// to the SourceNode without any mapping.
// Each line is added as separate string.
while (lastGeneratedLine < mapping.generatedLine) {
node.add(remainingLines.shift() + "\n");
lastGeneratedLine++;
}
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
node.add(nextLine.substr(0, mapping.generatedColumn));
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
} else {
// We add the code from "lastMapping" to "mapping":
// First check if there is a new line in between.
if (lastGeneratedLine < mapping.generatedLine) {
var code = "";
// Associate full lines with "lastMapping"
do {
code += remainingLines.shift() + "\n";
lastGeneratedLine++;
lastGeneratedColumn = 0;
} while (lastGeneratedLine < mapping.generatedLine);
// When we reached the correct line, we add code until we
// reach the correct column too.
if (lastGeneratedColumn < mapping.generatedColumn) {
var nextLine = remainingLines[0];
code += nextLine.substr(0, mapping.generatedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn);
lastGeneratedColumn = mapping.generatedColumn;
}
// Create the SourceNode.
addMappingWithCode(lastMapping, code);
} else {
// There is no new line in between.
// Associate the code between "lastGeneratedColumn" and
// "mapping.generatedColumn" with "lastMapping"
var nextLine = remainingLines[0];
var code = nextLine.substr(0, mapping.generatedColumn -
lastGeneratedColumn);
remainingLines[0] = nextLine.substr(mapping.generatedColumn -
lastGeneratedColumn);
lastGeneratedColumn = mapping.generatedColumn;
addMappingWithCode(lastMapping, code);
}
}
lastMapping = mapping;
}, this);
// We have processed all mappings.
// Associate the remaining code in the current line with "lastMapping"
// and add the remaining lines without any mapping
addMappingWithCode(lastMapping, remainingLines.join("\n"));
// Copy sourcesContent into SourceNode
aSourceMapConsumer.sources.forEach(function (sourceFile) {
var content = aSourceMapConsumer.sourceContentFor(sourceFile);
if (content) {
node.setSourceContent(sourceFile, content);
}
});
return node;
function addMappingWithCode(mapping, code) {
if (mapping === null || mapping.source === undefined) {
node.add(code);
} else {
node.add(new SourceNode(mapping.originalLine,
mapping.originalColumn,
mapping.source,
code,
mapping.name));
}
}
};
/**
* Add a chunk of generated JS to this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.add = function SourceNode_add(aChunk) {
if (Array.isArray(aChunk)) {
aChunk.forEach(function (chunk) {
this.add(chunk);
}, this);
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
if (aChunk) {
this.children.push(aChunk);
}
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Add a chunk of generated JS to the beginning of this source node.
*
* @param aChunk A string snippet of generated JS code, another instance of
* SourceNode, or an array where each member is one of those things.
*/
SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
if (Array.isArray(aChunk)) {
for (var i = aChunk.length-1; i >= 0; i--) {
this.prepend(aChunk[i]);
}
}
else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
this.children.unshift(aChunk);
}
else {
throw new TypeError(
"Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
);
}
return this;
};
/**
* Walk over the tree of JS snippets in this node and its children. The
* walking function is called once for each snippet of JS and is passed that
* snippet and the its original associated source's line/column location.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walk = function SourceNode_walk(aFn) {
var chunk;
for (var i = 0, len = this.children.length; i < len; i++) {
chunk = this.children[i];
if (chunk instanceof SourceNode) {
chunk.walk(aFn);
}
else {
if (chunk !== '') {
aFn(chunk, { source: this.source,
line: this.line,
column: this.column,
name: this.name });
}
}
}
};
/**
* Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
* each of `this.children`.
*
* @param aSep The separator.
*/
SourceNode.prototype.join = function SourceNode_join(aSep) {
var newChildren;
var i;
var len = this.children.length;
if (len > 0) {
newChildren = [];
for (i = 0; i < len-1; i++) {
newChildren.push(this.children[i]);
newChildren.push(aSep);
}
newChildren.push(this.children[i]);
this.children = newChildren;
}
return this;
};
/**
* Call String.prototype.replace on the very right-most source snippet. Useful
* for trimming whitespace from the end of a source node, etc.
*
* @param aPattern The pattern to replace.
* @param aReplacement The thing to replace the pattern with.
*/
SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
var lastChild = this.children[this.children.length - 1];
if (lastChild instanceof SourceNode) {
lastChild.replaceRight(aPattern, aReplacement);
}
else if (typeof lastChild === 'string') {
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
}
else {
this.children.push(''.replace(aPattern, aReplacement));
}
return this;
};
/**
* Set the source content for a source file. This will be added to the SourceMapGenerator
* in the sourcesContent field.
*
* @param aSourceFile The filename of the source file
* @param aSourceContent The content of the source file
*/
SourceNode.prototype.setSourceContent =
function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
/**
* Walk over the tree of SourceNodes. The walking function is called for each
* source file content and is passed the filename and source content.
*
* @param aFn The traversal function.
*/
SourceNode.prototype.walkSourceContents =
function SourceNode_walkSourceContents(aFn) {
for (var i = 0, len = this.children.length; i < len; i++) {
if (this.children[i] instanceof SourceNode) {
this.children[i].walkSourceContents(aFn);
}
}
var sources = Object.keys(this.sourceContents);
for (var i = 0, len = sources.length; i < len; i++) {
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
}
};
/**
* Return the string representation of this source node. Walks over the tree
* and concatenates all the various snippets together to one string.
*/
SourceNode.prototype.toString = function SourceNode_toString() {
var str = "";
this.walk(function (chunk) {
str += chunk;
});
return str;
};
/**
* Returns the string representation of this source node along with a source
* map.
*/
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
var generated = {
code: "",
line: 1,
column: 0
};
var map = new SourceMapGenerator(aArgs);
var sourceMappingActive = false;
var lastOriginalSource = null;
var lastOriginalLine = null;
var lastOriginalColumn = null;
var lastOriginalName = null;
this.walk(function (chunk, original) {
generated.code += chunk;
if (original.source !== null
&& original.line !== null
&& original.column !== null) {
if(lastOriginalSource !== original.source
|| lastOriginalLine !== original.line
|| lastOriginalColumn !== original.column
|| lastOriginalName !== original.name) {
map.addMapping({
source: original.source,
original: {
line: original.line,
column: original.column
},
generated: {
line: generated.line,
column: generated.column
},
name: original.name
});
}
lastOriginalSource = original.source;
lastOriginalLine = original.line;
lastOriginalColumn = original.column;
lastOriginalName = original.name;
sourceMappingActive = true;
} else if (sourceMappingActive) {
map.addMapping({
generated: {
line: generated.line,
column: generated.column
}
});
lastOriginalSource = null;
sourceMappingActive = false;
}
chunk.split('').forEach(function (ch) {
if (ch === '\n') {
generated.line++;
generated.column = 0;
} else {
generated.column++;
}
});
});
this.walkSourceContents(function (sourceFile, sourceContent) {
map.setSourceContent(sourceFile, sourceContent);
});
return { code: generated.code, map: map };
};
exports.SourceNode = SourceNode;
});
},{"./source-map-generator":17,"./util":19,"amdefine":20}],19:[function(_dereq_,module,exports){
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = _dereq_('amdefine')(module, _dereq_);
}
define(function (_dereq_, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
},{"amdefine":20}],20:[function(_dereq_,module,exports){
(function (process,__filename){
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = _dereq_('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
}).call(this,_dereq_('_process'),"/node_modules/jstransform/node_modules/source-map/node_modules/amdefine/amdefine.js")
},{"_process":8,"path":7}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var docblockRe = /^\s*(\/\*\*(.|\r?\n)*?\*\/)/;
var ltrimRe = /^\s*/;
/**
* @param {String} contents
* @return {String}
*/
function extract(contents) {
var match = contents.match(docblockRe);
if (match) {
return match[0].replace(ltrimRe, '') || '';
}
return '';
}
var commentStartRe = /^\/\*\*?/;
var commentEndRe = /\*+\/$/;
var wsRe = /[\t ]+/g;
var stringStartRe = /(\r?\n|^) *\*/g;
var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
/**
* @param {String} contents
* @return {Array}
*/
function parse(docblock) {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
.replace(wsRe, ' ')
.replace(stringStartRe, '$1');
// Normalize multi-line directives
var prev = '';
while (prev != docblock) {
prev = docblock;
docblock = docblock.replace(multilineRe, "\n$1 $2\n");
}
docblock = docblock.trim();
var result = [];
var match;
while (match = propertyRe.exec(docblock)) {
result.push([match[1], match[2]]);
}
return result;
}
/**
* Same as parse but returns an object of prop: value instead of array of paris
* If a property appers more than once the last one will be returned
*
* @param {String} contents
* @return {Object}
*/
function parseAsObject(docblock) {
var pairs = parse(docblock);
var result = {};
for (var i = 0; i < pairs.length; i++) {
result[pairs[i][0]] = pairs[i][1];
}
return result;
}
exports.extract = extract;
exports.parse = parse;
exports.parseAsObject = parseAsObject;
},{}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node: true*/
"use strict";
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('./utils');
var getBoundaryNode = utils.getBoundaryNode;
var declareIdentInScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var Syntax = esprima.Syntax;
/**
* @param {object} node
* @param {object} parentNode
* @return {boolean}
*/
function _nodeIsClosureScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return true;
}
var parentIsFunction =
parentNode.type === Syntax.FunctionDeclaration
|| parentNode.type === Syntax.FunctionExpression
|| parentNode.type === Syntax.ArrowFunctionExpression;
var parentIsCurlylessArrowFunc =
parentNode.type === Syntax.ArrowFunctionExpression
&& node === parentNode.body;
return parentIsFunction
&& (node.type === Syntax.BlockStatement || parentIsCurlylessArrowFunc);
}
function _nodeIsBlockScopeBoundary(node, parentNode) {
if (node.type === Syntax.Program) {
return false;
}
return node.type === Syntax.BlockStatement
&& parentNode.type === Syntax.CatchClause;
}
/**
* @param {object} node
* @param {array} path
* @param {object} state
*/
function traverse(node, path, state) {
/*jshint -W004*/
// Create a scope stack entry if this is the first node we've encountered in
// its local scope
var startIndex = null;
var parentNode = path[0];
if (!Array.isArray(node) && state.localScope.parentNode !== parentNode) {
if (_nodeIsClosureScopeBoundary(node, parentNode)) {
var scopeIsStrict = state.scopeIsStrict;
if (!scopeIsStrict
&& (node.type === Syntax.BlockStatement
|| node.type === Syntax.Program)) {
scopeIsStrict =
node.body.length > 0
&& node.body[0].type === Syntax.ExpressionStatement
&& node.body[0].expression.type === Syntax.Literal
&& node.body[0].expression.value === 'use strict';
}
if (node.type === Syntax.Program) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
scopeIsStrict: scopeIsStrict
});
} else {
startIndex = state.g.buffer.length + 1;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
scopeIsStrict: scopeIsStrict
});
// All functions have an implicit 'arguments' object in scope
declareIdentInScope('arguments', initScopeMetadata(node), state);
// Include function arg identifiers in the scope boundaries of the
// function
if (parentNode.params.length > 0) {
var param;
var metadata = initScopeMetadata(parentNode, path.slice(1), path[0]);
for (var i = 0; i < parentNode.params.length; i++) {
param = parentNode.params[i];
if (param.type === Syntax.Identifier) {
declareIdentInScope(param.name, metadata, state);
}
}
}
// Include rest arg identifiers in the scope boundaries of their
// functions
if (parentNode.rest) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
path[0]
);
declareIdentInScope(parentNode.rest.name, metadata, state);
}
// Named FunctionExpressions scope their name within the body block of
// themselves only
if (parentNode.type === Syntax.FunctionExpression && parentNode.id) {
var metaData =
initScopeMetadata(parentNode, path.parentNodeslice, parentNode);
declareIdentInScope(parentNode.id.name, metaData, state);
}
}
// Traverse and find all local identifiers in this closure first to
// account for function/variable declaration hoisting
collectClosureIdentsAndTraverse(node, path, state);
}
if (_nodeIsBlockScopeBoundary(node, parentNode)) {
startIndex = state.g.buffer.length;
state = utils.updateState(state, {
localScope: {
parentNode: parentNode,
parentScope: state.localScope,
identifiers: {},
tempVarIndex: 0,
tempVars: []
}
});
if (parentNode.type === Syntax.CatchClause) {
var metadata = initScopeMetadata(
parentNode,
path.slice(1),
parentNode
);
declareIdentInScope(parentNode.param.name, metadata, state);
}
collectBlockIdentsAndTraverse(node, path, state);
}
}
// Only catchup() before and after traversing a child node
function traverser(node, path, state) {
node.range && utils.catchup(node.range[0], state);
traverse(node, path, state);
node.range && utils.catchup(node.range[1], state);
}
utils.analyzeAndTraverse(walker, traverser, node, path, state);
// Inject temp variables into the scope.
if (startIndex !== null) {
utils.injectTempVarDeclarations(state, startIndex);
}
}
function collectClosureIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalClosureIdentifiers,
collectClosureIdentsAndTraverse,
node,
path,
state
);
}
function collectBlockIdentsAndTraverse(node, path, state) {
utils.analyzeAndTraverse(
visitLocalBlockIdentifiers,
collectBlockIdentsAndTraverse,
node,
path,
state
);
}
function visitLocalClosureIdentifiers(node, path, state) {
var metaData;
switch (node.type) {
case Syntax.ArrowFunctionExpression:
case Syntax.FunctionExpression:
// Function expressions don't get their names (if there is one) added to
// the closure scope they're defined in
return false;
case Syntax.ClassDeclaration:
case Syntax.ClassExpression:
case Syntax.FunctionDeclaration:
if (node.id) {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
return false;
case Syntax.VariableDeclarator:
// Variables have function-local scope
if (path[0].kind === 'var') {
metaData = initScopeMetadata(getBoundaryNode(path), path.slice(), node);
declareIdentInScope(node.id.name, metaData, state);
}
break;
}
}
function visitLocalBlockIdentifiers(node, path, state) {
// TODO: Support 'let' here...maybe...one day...or something...
if (node.type === Syntax.CatchClause) {
return false;
}
}
function walker(node, path, state) {
var visitors = state.g.visitors;
for (var i = 0; i < visitors.length; i++) {
if (visitors[i].test(node, path, state)) {
return visitors[i](traverse, node, path, state);
}
}
}
var _astCache = {};
function getAstForSource(source, options) {
if (_astCache[source] && !options.disableAstCache) {
return _astCache[source];
}
var ast = esprima.parse(source, {
comment: true,
loc: true,
range: true,
sourceType: options.sourceType
});
if (!options.disableAstCache) {
_astCache[source] = ast;
}
return ast;
}
/**
* Applies all available transformations to the source
* @param {array} visitors
* @param {string} source
* @param {?object} options
* @return {object}
*/
function transform(visitors, source, options) {
options = options || {};
var ast;
try {
ast = getAstForSource(source, options);
} catch (e) {
e.message = 'Parse Error: ' + e.message;
throw e;
}
var state = utils.createState(source, ast, options);
state.g.visitors = visitors;
if (options.sourceMap) {
var SourceMapGenerator = _dereq_('source-map').SourceMapGenerator;
state.g.sourceMap = new SourceMapGenerator({file: options.filename || 'transformed.js'});
}
traverse(ast, [], state);
utils.catchup(source.length, state);
var ret = {code: state.g.buffer, extra: state.g.extra};
if (options.sourceMap) {
ret.sourceMap = state.g.sourceMap;
ret.sourceMapFilename = options.filename || 'source.js';
}
return ret;
}
exports.transform = transform;
exports.Syntax = Syntax;
},{"./utils":23,"esprima-fb":9,"source-map":11}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node: true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var leadingIndentRegexp = /(^|\n)( {2}|\t)/g;
var nonWhiteRegexp = /(\S)/g;
/**
* A `state` object represents the state of the parser. It has "local" and
* "global" parts. Global contains parser position, source, etc. Local contains
* scope based properties like current class name. State should contain all the
* info required for transformation. It's the only mandatory object that is
* being passed to every function in transform chain.
*
* @param {string} source
* @param {object} transformOptions
* @return {object}
*/
function createState(source, rootNode, transformOptions) {
return {
/**
* A tree representing the current local scope (and its lexical scope chain)
* Useful for tracking identifiers from parent scopes, etc.
* @type {Object}
*/
localScope: {
parentNode: rootNode,
parentScope: null,
identifiers: {},
tempVarIndex: 0,
tempVars: []
},
/**
* The name (and, if applicable, expression) of the super class
* @type {Object}
*/
superClass: null,
/**
* The namespace to use when munging identifiers
* @type {String}
*/
mungeNamespace: '',
/**
* Ref to the node for the current MethodDefinition
* @type {Object}
*/
methodNode: null,
/**
* Ref to the node for the FunctionExpression of the enclosing
* MethodDefinition
* @type {Object}
*/
methodFuncNode: null,
/**
* Name of the enclosing class
* @type {String}
*/
className: null,
/**
* Whether we're currently within a `strict` scope
* @type {Bool}
*/
scopeIsStrict: null,
/**
* Indentation offset
* @type {Number}
*/
indentBy: 0,
/**
* Global state (not affected by updateState)
* @type {Object}
*/
g: {
/**
* A set of general options that transformations can consider while doing
* a transformation:
*
* - minify
* Specifies that transformation steps should do their best to minify
* the output source when possible. This is useful for places where
* minification optimizations are possible with higher-level context
* info than what jsxmin can provide.
*
* For example, the ES6 class transform will minify munged private
* variables if this flag is set.
*/
opts: transformOptions,
/**
* Current position in the source code
* @type {Number}
*/
position: 0,
/**
* Auxiliary data to be returned by transforms
* @type {Object}
*/
extra: {},
/**
* Buffer containing the result
* @type {String}
*/
buffer: '',
/**
* Source that is being transformed
* @type {String}
*/
source: source,
/**
* Cached parsed docblock (see getDocblock)
* @type {object}
*/
docblock: null,
/**
* Whether the thing was used
* @type {Boolean}
*/
tagNamespaceUsed: false,
/**
* If using bolt xjs transformation
* @type {Boolean}
*/
isBolt: undefined,
/**
* Whether to record source map (expensive) or not
* @type {SourceMapGenerator|null}
*/
sourceMap: null,
/**
* Filename of the file being processed. Will be returned as a source
* attribute in the source map
*/
sourceMapFilename: 'source.js',
/**
* Only when source map is used: last line in the source for which
* source map was generated
* @type {Number}
*/
sourceLine: 1,
/**
* Only when source map is used: last line in the buffer for which
* source map was generated
* @type {Number}
*/
bufferLine: 1,
/**
* The top-level Program AST for the original file.
*/
originalProgramAST: null,
sourceColumn: 0,
bufferColumn: 0
}
};
}
/**
* Updates a copy of a given state with "update" and returns an updated state.
*
* @param {object} state
* @param {object} update
* @return {object}
*/
function updateState(state, update) {
var ret = Object.create(state);
Object.keys(update).forEach(function(updatedKey) {
ret[updatedKey] = update[updatedKey];
});
return ret;
}
/**
* Given a state fill the resulting buffer from the original source up to
* the end
*
* @param {number} end
* @param {object} state
* @param {?function} contentTransformer Optional callback to transform newly
* added content.
*/
function catchup(end, state, contentTransformer) {
if (end < state.g.position) {
// cannot move backwards
return;
}
var source = state.g.source.substring(state.g.position, end);
var transformed = updateIndent(source, state);
if (state.g.sourceMap && transformed) {
// record where we are
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
// record line breaks in transformed source
var sourceLines = source.split('\n');
var transformedLines = transformed.split('\n');
// Add line break mappings between last known mapping and the end of the
// added piece. So for the code piece
// (foo, bar);
// > var x = 2;
// > var b = 3;
// var c =
// only add lines marked with ">": 2, 3.
for (var i = 1; i < sourceLines.length - 1; i++) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: 0 },
original: { line: state.g.sourceLine, column: 0 },
source: state.g.sourceMapFilename
});
state.g.sourceLine++;
state.g.bufferLine++;
}
// offset for the last piece
if (sourceLines.length > 1) {
state.g.sourceLine++;
state.g.bufferLine++;
state.g.sourceColumn = 0;
state.g.bufferColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer +=
contentTransformer ? contentTransformer(transformed) : transformed;
state.g.position = end;
}
/**
* Returns original source for an AST node.
* @param {object} node
* @param {object} state
* @return {string}
*/
function getNodeSourceText(node, state) {
return state.g.source.substring(node.range[0], node.range[1]);
}
function _replaceNonWhite(value) {
return value.replace(nonWhiteRegexp, ' ');
}
/**
* Removes all non-whitespace characters
*/
function _stripNonWhite(value) {
return value.replace(nonWhiteRegexp, '');
}
/**
* Finds the position of the next instance of the specified syntactic char in
* the pending source.
*
* NOTE: This will skip instances of the specified char if they sit inside a
* comment body.
*
* NOTE: This function also assumes that the buffer's current position is not
* already within a comment or a string. This is rarely the case since all
* of the buffer-advancement utility methods tend to be used on syntactic
* nodes' range values -- but it's a small gotcha that's worth mentioning.
*/
function getNextSyntacticCharOffset(char, state) {
var pendingSource = state.g.source.substring(state.g.position);
var pendingSourceLines = pendingSource.split('\n');
var charOffset = 0;
var line;
var withinBlockComment = false;
var withinString = false;
lineLoop: while ((line = pendingSourceLines.shift()) !== undefined) {
var lineEndPos = charOffset + line.length;
charLoop: for (; charOffset < lineEndPos; charOffset++) {
var currChar = pendingSource[charOffset];
if (currChar === '"' || currChar === '\'') {
withinString = !withinString;
continue charLoop;
} else if (withinString) {
continue charLoop;
} else if (charOffset + 1 < lineEndPos) {
var nextTwoChars = currChar + line[charOffset + 1];
if (nextTwoChars === '//') {
charOffset = lineEndPos + 1;
continue lineLoop;
} else if (nextTwoChars === '/*') {
withinBlockComment = true;
charOffset += 1;
continue charLoop;
} else if (nextTwoChars === '*/') {
withinBlockComment = false;
charOffset += 1;
continue charLoop;
}
}
if (!withinBlockComment && currChar === char) {
return charOffset + state.g.position;
}
}
// Account for '\n'
charOffset++;
withinString = false;
}
throw new Error('`' + char + '` not found!');
}
/**
* Catches up as `catchup` but replaces non-whitespace chars with spaces.
*/
function catchupWhiteOut(end, state) {
catchup(end, state, _replaceNonWhite);
}
/**
* Catches up as `catchup` but removes all non-whitespace characters.
*/
function catchupWhiteSpace(end, state) {
catchup(end, state, _stripNonWhite);
}
/**
* Removes all non-newline characters
*/
var reNonNewline = /[^\n]/g;
function stripNonNewline(value) {
return value.replace(reNonNewline, function() {
return '';
});
}
/**
* Catches up as `catchup` but removes all non-newline characters.
*
* Equivalent to appending as many newlines as there are in the original source
* between the current position and `end`.
*/
function catchupNewlines(end, state) {
catchup(end, state, stripNonNewline);
}
/**
* Same as catchup but does not touch the buffer
*
* @param {number} end
* @param {object} state
*/
function move(end, state) {
// move the internal cursors
if (state.g.sourceMap) {
if (end < state.g.position) {
state.g.position = 0;
state.g.sourceLine = 1;
state.g.sourceColumn = 0;
}
var source = state.g.source.substring(state.g.position, end);
var sourceLines = source.split('\n');
if (sourceLines.length > 1) {
state.g.sourceLine += sourceLines.length - 1;
state.g.sourceColumn = 0;
}
state.g.sourceColumn += sourceLines[sourceLines.length - 1].length;
}
state.g.position = end;
}
/**
* Appends a string of text to the buffer
*
* @param {string} str
* @param {object} state
*/
function append(str, state) {
if (state.g.sourceMap && str) {
state.g.sourceMap.addMapping({
generated: { line: state.g.bufferLine, column: state.g.bufferColumn },
original: { line: state.g.sourceLine, column: state.g.sourceColumn },
source: state.g.sourceMapFilename
});
var transformedLines = str.split('\n');
if (transformedLines.length > 1) {
state.g.bufferLine += transformedLines.length - 1;
state.g.bufferColumn = 0;
}
state.g.bufferColumn +=
transformedLines[transformedLines.length - 1].length;
}
state.g.buffer += str;
}
/**
* Update indent using state.indentBy property. Indent is measured in
* double spaces. Updates a single line only.
*
* @param {string} str
* @param {object} state
* @return {string}
*/
function updateIndent(str, state) {
/*jshint -W004*/
var indentBy = state.indentBy;
if (indentBy < 0) {
for (var i = 0; i < -indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1');
}
} else {
for (var i = 0; i < indentBy; i++) {
str = str.replace(leadingIndentRegexp, '$1$2$2');
}
}
return str;
}
/**
* Calculates indent from the beginning of the line until "start" or the first
* character before start.
* @example
* " foo.bar()"
* ^
* start
* indent will be " "
*
* @param {number} start
* @param {object} state
* @return {string}
*/
function indentBefore(start, state) {
var end = start;
start = start - 1;
while (start > 0 && state.g.source[start] != '\n') {
if (!state.g.source[start].match(/[ \t]/)) {
end = start;
}
start--;
}
return state.g.source.substring(start + 1, end);
}
function getDocblock(state) {
if (!state.g.docblock) {
var docblock = _dereq_('./docblock');
state.g.docblock =
docblock.parseAsObject(docblock.extract(state.g.source));
}
return state.g.docblock;
}
function identWithinLexicalScope(identName, state, stopBeforeNode) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return true;
}
if (stopBeforeNode && currScope.parentNode === stopBeforeNode) {
break;
}
currScope = currScope.parentScope;
}
return false;
}
function identInLocalScope(identName, state) {
return state.localScope.identifiers[identName] !== undefined;
}
/**
* @param {object} boundaryNode
* @param {?array} path
* @return {?object} node
*/
function initScopeMetadata(boundaryNode, path, node) {
return {
boundaryNode: boundaryNode,
bindingPath: path,
bindingNode: node
};
}
function declareIdentInLocalScope(identName, metaData, state) {
state.localScope.identifiers[identName] = {
boundaryNode: metaData.boundaryNode,
path: metaData.bindingPath,
node: metaData.bindingNode,
state: Object.create(state)
};
}
function getLexicalBindingMetadata(identName, state) {
var currScope = state.localScope;
while (currScope) {
if (currScope.identifiers[identName] !== undefined) {
return currScope.identifiers[identName];
}
currScope = currScope.parentScope;
}
}
function getLocalBindingMetadata(identName, state) {
return state.localScope.identifiers[identName];
}
/**
* Apply the given analyzer function to the current node. If the analyzer
* doesn't return false, traverse each child of the current node using the given
* traverser function.
*
* @param {function} analyzer
* @param {function} traverser
* @param {object} node
* @param {array} path
* @param {object} state
*/
function analyzeAndTraverse(analyzer, traverser, node, path, state) {
if (node.type) {
if (analyzer(node, path, state) === false) {
return;
}
path.unshift(node);
}
getOrderedChildren(node).forEach(function(child) {
traverser(child, path, state);
});
node.type && path.shift();
}
/**
* It is crucial that we traverse in order, or else catchup() on a later
* node that is processed out of order can move the buffer past a node
* that we haven't handled yet, preventing us from modifying that node.
*
* This can happen when a node has multiple properties containing children.
* For example, XJSElement nodes have `openingElement`, `closingElement` and
* `children`. If we traverse `openingElement`, then `closingElement`, then
* when we get to `children`, the buffer has already caught up to the end of
* the closing element, after the children.
*
* This is basically a Schwartzian transform. Collects an array of children,
* each one represented as [child, startIndex]; sorts the array by start
* index; then traverses the children in that order.
*/
function getOrderedChildren(node) {
var queue = [];
for (var key in node) {
if (node.hasOwnProperty(key)) {
enqueueNodeWithStartIndex(queue, node[key]);
}
}
queue.sort(function(a, b) { return a[1] - b[1]; });
return queue.map(function(pair) { return pair[0]; });
}
/**
* Helper function for analyzeAndTraverse which queues up all of the children
* of the given node.
*
* Children can also be found in arrays, so we basically want to merge all of
* those arrays together so we can sort them and then traverse the children
* in order.
*
* One example is the Program node. It contains `body` and `comments`, both
* arrays. Lexographically, comments are interspersed throughout the body
* nodes, but esprima's AST groups them together.
*/
function enqueueNodeWithStartIndex(queue, node) {
if (typeof node !== 'object' || node === null) {
return;
}
if (node.range) {
queue.push([node, node.range[0]]);
} else if (Array.isArray(node)) {
for (var ii = 0; ii < node.length; ii++) {
enqueueNodeWithStartIndex(queue, node[ii]);
}
}
}
/**
* Checks whether a node or any of its sub-nodes contains
* a syntactic construct of the passed type.
* @param {object} node - AST node to test.
* @param {string} type - node type to lookup.
*/
function containsChildOfType(node, type) {
return containsChildMatching(node, function(node) {
return node.type === type;
});
}
function containsChildMatching(node, matcher) {
var foundMatchingChild = false;
function nodeTypeAnalyzer(node) {
if (matcher(node) === true) {
foundMatchingChild = true;
return false;
}
}
function nodeTypeTraverser(child, path, state) {
if (!foundMatchingChild) {
foundMatchingChild = containsChildMatching(child, matcher);
}
}
analyzeAndTraverse(
nodeTypeAnalyzer,
nodeTypeTraverser,
node,
[]
);
return foundMatchingChild;
}
var scopeTypes = {};
scopeTypes[Syntax.ArrowFunctionExpression] = true;
scopeTypes[Syntax.FunctionExpression] = true;
scopeTypes[Syntax.FunctionDeclaration] = true;
scopeTypes[Syntax.Program] = true;
function getBoundaryNode(path) {
for (var ii = 0; ii < path.length; ++ii) {
if (scopeTypes[path[ii].type]) {
return path[ii];
}
}
throw new Error(
'Expected to find a node with one of the following types in path:\n' +
JSON.stringify(Object.keys(scopeTypes))
);
}
function getTempVar(tempVarIndex) {
return '$__' + tempVarIndex;
}
function injectTempVar(state) {
var tempVar = '$__' + (state.localScope.tempVarIndex++);
state.localScope.tempVars.push(tempVar);
return tempVar;
}
function injectTempVarDeclarations(state, index) {
if (state.localScope.tempVars.length) {
state.g.buffer =
state.g.buffer.slice(0, index) +
'var ' + state.localScope.tempVars.join(', ') + ';' +
state.g.buffer.slice(index);
state.localScope.tempVars = [];
}
}
exports.analyzeAndTraverse = analyzeAndTraverse;
exports.append = append;
exports.catchup = catchup;
exports.catchupNewlines = catchupNewlines;
exports.catchupWhiteOut = catchupWhiteOut;
exports.catchupWhiteSpace = catchupWhiteSpace;
exports.containsChildMatching = containsChildMatching;
exports.containsChildOfType = containsChildOfType;
exports.createState = createState;
exports.declareIdentInLocalScope = declareIdentInLocalScope;
exports.getBoundaryNode = getBoundaryNode;
exports.getDocblock = getDocblock;
exports.getLexicalBindingMetadata = getLexicalBindingMetadata;
exports.getLocalBindingMetadata = getLocalBindingMetadata;
exports.getNextSyntacticCharOffset = getNextSyntacticCharOffset;
exports.getNodeSourceText = getNodeSourceText;
exports.getOrderedChildren = getOrderedChildren;
exports.getTempVar = getTempVar;
exports.identInLocalScope = identInLocalScope;
exports.identWithinLexicalScope = identWithinLexicalScope;
exports.indentBefore = indentBefore;
exports.initScopeMetadata = initScopeMetadata;
exports.injectTempVar = injectTempVar;
exports.injectTempVarDeclarations = injectTempVarDeclarations;
exports.move = move;
exports.scopeTypes = scopeTypes;
exports.updateIndent = updateIndent;
exports.updateState = updateState;
},{"./docblock":21,"esprima-fb":9}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*global exports:true*/
/**
* Desugars ES6 Arrow functions to ES3 function expressions.
* If the function contains `this` expression -- automatically
* binds the function to current value of `this`.
*
* Single parameter, simple expression:
*
* [1, 2, 3].map(x => x * x);
*
* [1, 2, 3].map(function(x) { return x * x; });
*
* Several parameters, complex block:
*
* this.users.forEach((user, idx) => {
* return this.isActive(idx) && this.send(user);
* });
*
* this.users.forEach(function(user, idx) {
* return this.isActive(idx) && this.send(user);
* }.bind(this));
*
*/
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var destructuringVisitors = _dereq_('./es6-destructuring-visitors');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitArrowFunction(traverse, node, path, state) {
var notInExpression = (path[0].type === Syntax.ExpressionStatement);
// Wrap a function into a grouping operator, if it's not
// in the expression position.
if (notInExpression) {
utils.append('(', state);
}
utils.append('function', state);
renderParams(traverse, node, path, state);
// Skip arrow.
utils.catchupWhiteSpace(node.body.range[0], state);
var renderBody = node.body.type == Syntax.BlockStatement
? renderStatementBody
: renderExpressionBody;
path.unshift(node);
renderBody(traverse, node, path, state);
path.shift();
// Bind the function only if `this` value is used
// inside it or inside any sub-expression.
var containsBindingSyntax =
utils.containsChildMatching(node.body, function(node) {
return node.type === Syntax.ThisExpression
|| (node.type === Syntax.Identifier
&& node.name === "super");
});
if (containsBindingSyntax) {
utils.append('.bind(this)', state);
}
utils.catchupWhiteSpace(node.range[1], state);
// Close wrapper if not in the expression.
if (notInExpression) {
utils.append(')', state);
}
return false;
}
function renderParams(traverse, node, path, state) {
// To preserve inline typechecking directives, we
// distinguish between parens-free and paranthesized single param.
if (isParensFreeSingleParam(node, state) || !node.params.length) {
utils.append('(', state);
}
if (node.params.length !== 0) {
path.unshift(node);
traverse(node.params, path, state);
path.unshift();
}
utils.append(')', state);
}
function isParensFreeSingleParam(node, state) {
return node.params.length === 1 &&
state.g.source[state.g.position] !== '(';
}
function renderExpressionBody(traverse, node, path, state) {
// Wrap simple expression bodies into a block
// with explicit return statement.
utils.append('{', state);
// Special handling of rest param.
if (node.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(node, state),
state
);
}
// Special handling of destructured params.
destructuringVisitors.renderDestructuredComponents(
node,
utils.updateState(state, {
localScope: {
parentNode: state.parentNode,
parentScope: state.parentScope,
identifiers: state.identifiers,
tempVarIndex: 0
}
})
);
utils.append('return ', state);
renderStatementBody(traverse, node, path, state);
utils.append(';}', state);
}
function renderStatementBody(traverse, node, path, state) {
traverse(node.body, path, state);
utils.catchup(node.body.range[1], state);
}
visitArrowFunction.test = function(node, path, state) {
return node.type === Syntax.ArrowFunctionExpression;
};
exports.visitorList = [
visitArrowFunction
];
},{"../src/utils":23,"./es6-destructuring-visitors":27,"./es6-rest-param-visitors":30,"esprima-fb":9}],25:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES6 call spread.
*
* instance.method(a, b, c, ...d)
*
* instance.method.apply(instance, [a, b, c].concat(d))
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function process(traverse, node, path, state) {
utils.move(node.range[0], state);
traverse(node, path, state);
utils.catchup(node.range[1], state);
}
function visitCallSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
if (node.type === Syntax.NewExpression) {
// Input = new Set(1, 2, ...list)
// Output = new (Function.prototype.bind.apply(Set, [null, 1, 2].concat(list)))
utils.append('new (Function.prototype.bind.apply(', state);
process(traverse, node.callee, path, state);
} else if (node.callee.type === Syntax.MemberExpression) {
// Input = get().fn(1, 2, ...more)
// Output = (_ = get()).fn.apply(_, [1, 2].apply(more))
var tempVar = utils.injectTempVar(state);
utils.append('(' + tempVar + ' = ', state);
process(traverse, node.callee.object, path, state);
utils.append(')', state);
if (node.callee.property.type === Syntax.Identifier) {
utils.append('.', state);
process(traverse, node.callee.property, path, state);
} else {
utils.append('[', state);
process(traverse, node.callee.property, path, state);
utils.append(']', state);
}
utils.append('.apply(' + tempVar, state);
} else {
// Input = max(1, 2, ...list)
// Output = max.apply(null, [1, 2].concat(list))
var needsToBeWrappedInParenthesis =
node.callee.type === Syntax.FunctionDeclaration ||
node.callee.type === Syntax.FunctionExpression;
if (needsToBeWrappedInParenthesis) {
utils.append('(', state);
}
process(traverse, node.callee, path, state);
if (needsToBeWrappedInParenthesis) {
utils.append(')', state);
}
utils.append('.apply(null', state);
}
utils.append(', ', state);
var args = node.arguments.slice();
var spread = args.pop();
if (args.length || node.type === Syntax.NewExpression) {
utils.append('[', state);
if (node.type === Syntax.NewExpression) {
utils.append('null' + (args.length ? ', ' : ''), state);
}
while (args.length) {
var arg = args.shift();
utils.move(arg.range[0], state);
traverse(arg, path, state);
if (args.length) {
utils.catchup(args[0].range[0], state);
} else {
utils.catchup(arg.range[1], state);
}
}
utils.append('].concat(', state);
process(traverse, spread.argument, path, state);
utils.append(')', state);
} else {
process(traverse, spread.argument, path, state);
}
utils.append(node.type === Syntax.NewExpression ? '))' : ')', state);
utils.move(node.range[1], state);
return false;
}
visitCallSpread.test = function(node, path, state) {
return (
(
node.type === Syntax.CallExpression ||
node.type === Syntax.NewExpression
) &&
node.arguments.length > 0 &&
node.arguments[node.arguments.length - 1].type === Syntax.SpreadElement
);
};
exports.visitorList = [
visitCallSpread
];
},{"../src/utils":23,"esprima-fb":9}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var base62 = _dereq_('base62');
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var declareIdentInLocalScope = utils.declareIdentInLocalScope;
var initScopeMetadata = utils.initScopeMetadata;
var SUPER_PROTO_IDENT_PREFIX = '____SuperProtoOf';
var _anonClassUUIDCounter = 0;
var _mungedSymbolMaps = {};
function resetSymbols() {
_anonClassUUIDCounter = 0;
_mungedSymbolMaps = {};
}
/**
* Used to generate a unique class for use with code-gens for anonymous class
* expressions.
*
* @param {object} state
* @return {string}
*/
function _generateAnonymousClassName(state) {
var mungeNamespace = state.mungeNamespace || '';
return '____Class' + mungeNamespace + base62.encode(_anonClassUUIDCounter++);
}
/**
* Given an identifier name, munge it using the current state's mungeNamespace.
*
* @param {string} identName
* @param {object} state
* @return {string}
*/
function _getMungedName(identName, state) {
var mungeNamespace = state.mungeNamespace;
var shouldMinify = state.g.opts.minify;
if (shouldMinify) {
if (!_mungedSymbolMaps[mungeNamespace]) {
_mungedSymbolMaps[mungeNamespace] = {
symbolMap: {},
identUUIDCounter: 0
};
}
var symbolMap = _mungedSymbolMaps[mungeNamespace].symbolMap;
if (!symbolMap[identName]) {
symbolMap[identName] =
base62.encode(_mungedSymbolMaps[mungeNamespace].identUUIDCounter++);
}
identName = symbolMap[identName];
}
return '$' + mungeNamespace + identName;
}
/**
* Extracts super class information from a class node.
*
* Information includes name of the super class and/or the expression string
* (if extending from an expression)
*
* @param {object} node
* @param {object} state
* @return {object}
*/
function _getSuperClassInfo(node, state) {
var ret = {
name: null,
expression: null
};
if (node.superClass) {
if (node.superClass.type === Syntax.Identifier) {
ret.name = node.superClass.name;
} else {
// Extension from an expression
ret.name = _generateAnonymousClassName(state);
ret.expression = state.g.source.substring(
node.superClass.range[0],
node.superClass.range[1]
);
}
}
return ret;
}
/**
* Used with .filter() to find the constructor method in a list of
* MethodDefinition nodes.
*
* @param {object} classElement
* @return {boolean}
*/
function _isConstructorMethod(classElement) {
return classElement.type === Syntax.MethodDefinition &&
classElement.key.type === Syntax.Identifier &&
classElement.key.name === 'constructor';
}
/**
* @param {object} node
* @param {object} state
* @return {boolean}
*/
function _shouldMungeIdentifier(node, state) {
return (
!!state.methodFuncNode &&
!utils.getDocblock(state).hasOwnProperty('preventMunge') &&
/^_(?!_)/.test(node.name)
);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassMethod(traverse, node, path, state) {
if (!state.g.opts.es5 && (node.kind === 'get' || node.kind === 'set')) {
throw new Error(
'This transform does not support ' + node.kind + 'ter methods for ES6 ' +
'classes. (line: ' + node.loc.start.line + ', col: ' +
node.loc.start.column + ')'
);
}
state = utils.updateState(state, {
methodNode: node
});
utils.catchup(node.range[0], state);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitClassMethod.test = function(node, path, state) {
return node.type === Syntax.MethodDefinition;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassFunctionExpression(traverse, node, path, state) {
var methodNode = path[0];
var isGetter = methodNode.kind === 'get';
var isSetter = methodNode.kind === 'set';
state = utils.updateState(state, {
methodFuncNode: node
});
if (methodNode.key.name === 'constructor') {
utils.append('function ' + state.className, state);
} else {
var methodAccessorComputed = false;
var methodAccessor;
var prototypeOrStatic = methodNode["static"] ? '' : '.prototype';
var objectAccessor = state.className + prototypeOrStatic;
if (methodNode.key.type === Syntax.Identifier) {
// foo() {}
methodAccessor = methodNode.key.name;
if (_shouldMungeIdentifier(methodNode.key, state)) {
methodAccessor = _getMungedName(methodAccessor, state);
}
if (isGetter || isSetter) {
methodAccessor = JSON.stringify(methodAccessor);
} else if (reservedWordsHelper.isReservedWord(methodAccessor)) {
methodAccessorComputed = true;
methodAccessor = JSON.stringify(methodAccessor);
}
} else if (methodNode.key.type === Syntax.Literal) {
// 'foo bar'() {} | get 'foo bar'() {} | set 'foo bar'() {}
methodAccessor = JSON.stringify(methodNode.key.value);
methodAccessorComputed = true;
}
if (isSetter || isGetter) {
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{configurable:true,' +
methodNode.kind + ':function',
state
);
} else {
if (state.g.opts.es3) {
if (methodAccessorComputed) {
methodAccessor = '[' + methodAccessor + ']';
} else {
methodAccessor = '.' + methodAccessor;
}
utils.append(
objectAccessor +
methodAccessor + '=function' + (node.generator ? '*' : ''),
state
);
} else {
if (!methodAccessorComputed) {
methodAccessor = JSON.stringify(methodAccessor);
}
utils.append(
'Object.defineProperty(' +
objectAccessor + ',' +
methodAccessor + ',' +
'{writable:true,configurable:true,' +
'value:function' + (node.generator ? '*' : ''),
state
);
}
}
}
utils.move(methodNode.key.range[1], state);
utils.append('(', state);
var params = node.params;
if (params.length > 0) {
utils.catchupNewlines(params[0].range[0], state);
for (var i = 0; i < params.length; i++) {
utils.catchup(node.params[i].range[0], state);
path.unshift(node);
traverse(params[i], path, state);
path.shift();
}
}
var closingParenPosition = utils.getNextSyntacticCharOffset(')', state);
utils.catchupWhiteSpace(closingParenPosition, state);
var openingBracketPosition = utils.getNextSyntacticCharOffset('{', state);
utils.catchup(openingBracketPosition + 1, state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
state = utils.updateState(state, {
scopeIsStrict: true
});
}
utils.move(node.body.range[0] + '{'.length, state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
utils.catchup(node.body.range[1], state);
if (methodNode.key.name !== 'constructor') {
if (isGetter || isSetter || !state.g.opts.es3) {
utils.append('})', state);
}
utils.append(';', state);
}
return false;
}
visitClassFunctionExpression.test = function(node, path, state) {
return node.type === Syntax.FunctionExpression
&& path[0].type === Syntax.MethodDefinition;
};
function visitClassMethodParam(traverse, node, path, state) {
var paramName = node.name;
if (_shouldMungeIdentifier(node, state)) {
paramName = _getMungedName(node.name, state);
}
utils.append(paramName, state);
utils.move(node.range[1], state);
}
visitClassMethodParam.test = function(node, path, state) {
if (!path[0] || !path[1]) {
return;
}
var parentFuncExpr = path[0];
var parentClassMethod = path[1];
return parentFuncExpr.type === Syntax.FunctionExpression
&& parentClassMethod.type === Syntax.MethodDefinition
&& node.type === Syntax.Identifier;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function _renderClassBody(traverse, node, path, state) {
var className = state.className;
var superClass = state.superClass;
// Set up prototype of constructor on same line as `extends` for line-number
// preservation. This relies on function-hoisting if a constructor function is
// defined in the class body.
if (superClass.name) {
// If the super class is an expression, we need to memoize the output of the
// expression into the generated class name variable and use that to refer
// to the super class going forward. Example:
//
// class Foo extends mixin(Bar, Baz) {}
// --transforms to--
// function Foo() {} var ____Class0Blah = mixin(Bar, Baz);
if (superClass.expression !== null) {
utils.append(
'var ' + superClass.name + '=' + superClass.expression + ';',
state
);
}
var keyName = superClass.name + '____Key';
var keyNameDeclarator = '';
if (!utils.identWithinLexicalScope(keyName, state)) {
keyNameDeclarator = 'var ';
declareIdentInLocalScope(keyName, initScopeMetadata(node), state);
}
utils.append(
'for(' + keyNameDeclarator + keyName + ' in ' + superClass.name + '){' +
'if(' + superClass.name + '.hasOwnProperty(' + keyName + ')){' +
className + '[' + keyName + ']=' +
superClass.name + '[' + keyName + '];' +
'}' +
'}',
state
);
var superProtoIdentStr = SUPER_PROTO_IDENT_PREFIX + superClass.name;
if (!utils.identWithinLexicalScope(superProtoIdentStr, state)) {
utils.append(
'var ' + superProtoIdentStr + '=' + superClass.name + '===null?' +
'null:' + superClass.name + '.prototype;',
state
);
declareIdentInLocalScope(superProtoIdentStr, initScopeMetadata(node), state);
}
utils.append(
className + '.prototype=Object.create(' + superProtoIdentStr + ');',
state
);
utils.append(
className + '.prototype.constructor=' + className + ';',
state
);
utils.append(
className + '.__superConstructor__=' + superClass.name + ';',
state
);
}
// If there's no constructor method specified in the class body, create an
// empty constructor function at the top (same line as the class keyword)
if (!node.body.body.filter(_isConstructorMethod).pop()) {
utils.append('function ' + className + '(){', state);
if (!state.scopeIsStrict) {
utils.append('"use strict";', state);
}
if (superClass.name) {
utils.append(
'if(' + superClass.name + '!==null){' +
superClass.name + '.apply(this,arguments);}',
state
);
}
utils.append('}', state);
}
utils.move(node.body.range[0] + '{'.length, state);
traverse(node.body, path, state);
utils.catchupWhiteSpace(node.range[1], state);
}
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassDeclaration(traverse, node, path, state) {
var className = node.id.name;
var superClass = _getSuperClassInfo(node, state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
return false;
}
visitClassDeclaration.test = function(node, path, state) {
return node.type === Syntax.ClassDeclaration;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitClassExpression(traverse, node, path, state) {
var className = node.id && node.id.name || _generateAnonymousClassName(state);
var superClass = _getSuperClassInfo(node, state);
utils.append('(function(){', state);
state = utils.updateState(state, {
mungeNamespace: className,
className: className,
superClass: superClass
});
_renderClassBody(traverse, node, path, state);
utils.append('return ' + className + ';})()', state);
return false;
}
visitClassExpression.test = function(node, path, state) {
return node.type === Syntax.ClassExpression;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitPrivateIdentifier(traverse, node, path, state) {
utils.append(_getMungedName(node.name, state), state);
utils.move(node.range[1], state);
}
visitPrivateIdentifier.test = function(node, path, state) {
if (node.type === Syntax.Identifier && _shouldMungeIdentifier(node, state)) {
// Always munge non-computed properties of MemberExpressions
// (a la preventing access of properties of unowned objects)
if (path[0].type === Syntax.MemberExpression && path[0].object !== node
&& path[0].computed === false) {
return true;
}
// Always munge identifiers that were declared within the method function
// scope
if (utils.identWithinLexicalScope(node.name, state, state.methodFuncNode)) {
return true;
}
// Always munge private keys on object literals defined within a method's
// scope.
if (path[0].type === Syntax.Property
&& path[1].type === Syntax.ObjectExpression) {
return true;
}
// Always munge function parameters
if (path[0].type === Syntax.FunctionExpression
|| path[0].type === Syntax.FunctionDeclaration
|| path[0].type === Syntax.ArrowFunctionExpression) {
for (var i = 0; i < path[0].params.length; i++) {
if (path[0].params[i] === node) {
return true;
}
}
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperCallExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
if (node.callee.type === Syntax.Identifier) {
if (_isConstructorMethod(state.methodNode)) {
utils.append(superClassName + '.call(', state);
} else {
var protoProp = SUPER_PROTO_IDENT_PREFIX + superClassName;
if (state.methodNode.key.type === Syntax.Identifier) {
protoProp += '.' + state.methodNode.key.name;
} else if (state.methodNode.key.type === Syntax.Literal) {
protoProp += '[' + JSON.stringify(state.methodNode.key.value) + ']';
}
utils.append(protoProp + ".call(", state);
}
utils.move(node.callee.range[1], state);
} else if (node.callee.type === Syntax.MemberExpression) {
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.callee.object.range[1], state);
if (node.callee.computed) {
// ["a" + "b"]
utils.catchup(node.callee.property.range[1] + ']'.length, state);
} else {
// .ab
utils.append('.' + node.callee.property.name, state);
}
utils.append('.call(', state);
utils.move(node.callee.range[1], state);
}
utils.append('this', state);
if (node.arguments.length > 0) {
utils.append(',', state);
utils.catchupWhiteSpace(node.arguments[0].range[0], state);
traverse(node.arguments, path, state);
}
utils.catchupWhiteSpace(node.range[1], state);
utils.append(')', state);
return false;
}
visitSuperCallExpression.test = function(node, path, state) {
if (state.superClass && node.type === Syntax.CallExpression) {
var callee = node.callee;
if (callee.type === Syntax.Identifier && callee.name === 'super'
|| callee.type == Syntax.MemberExpression
&& callee.object.name === 'super') {
return true;
}
}
return false;
};
/**
* @param {function} traverse
* @param {object} node
* @param {array} path
* @param {object} state
*/
function visitSuperMemberExpression(traverse, node, path, state) {
var superClassName = state.superClass.name;
utils.append(SUPER_PROTO_IDENT_PREFIX + superClassName, state);
utils.move(node.object.range[1], state);
}
visitSuperMemberExpression.test = function(node, path, state) {
return state.superClass
&& node.type === Syntax.MemberExpression
&& node.object.type === Syntax.Identifier
&& node.object.name === 'super';
};
exports.resetSymbols = resetSymbols;
exports.visitorList = [
visitClassDeclaration,
visitClassExpression,
visitClassFunctionExpression,
visitClassMethod,
visitClassMethodParam,
visitPrivateIdentifier,
visitSuperCallExpression,
visitSuperMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"base62":10,"esprima-fb":9}],27:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*global exports:true*/
/**
* Implements ES6 destructuring assignment and pattern matchng.
*
* function init({port, ip, coords: [x, y]}) {
* return (x && y) ? {id, port} : {ip};
* };
*
* function init($__0) {
* var
* port = $__0.port,
* ip = $__0.ip,
* $__1 = $__0.coords,
* x = $__1[0],
* y = $__1[1];
* return (x && y) ? {id, port} : {ip};
* }
*
* var x, {ip, port} = init({ip, port});
*
* var x, $__0 = init({ip, port}), ip = $__0.ip, port = $__0.port;
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
var restParamVisitors = _dereq_('./es6-rest-param-visitors');
var restPropertyHelpers = _dereq_('./es7-rest-property-helpers');
// -------------------------------------------------------
// 1. Structured variable declarations.
//
// var [a, b] = [b, a];
// var {x, y} = {y, x};
// -------------------------------------------------------
function visitStructuredVariable(traverse, node, path, state) {
// Allocate new temp for the pattern.
utils.append(utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
// Skip the pattern and assign the init to the temp.
utils.catchupWhiteSpace(node.init.range[0], state);
traverse(node.init, path, state);
utils.catchup(node.init.range[1], state);
// Render the destructured data.
utils.append(',' + getDestructuredComponents(node.id, state), state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredVariable.test = function(node, path, state) {
return node.type === Syntax.VariableDeclarator &&
isStructuredPattern(node.id);
};
function isStructuredPattern(node) {
return node.type === Syntax.ObjectPattern ||
node.type === Syntax.ArrayPattern;
}
// Main function which does actual recursive destructuring
// of nested complex structures.
function getDestructuredComponents(node, state) {
var tmpIndex = state.localScope.tempVarIndex;
var components = [];
var patternItems = getPatternItems(node);
for (var idx = 0; idx < patternItems.length; idx++) {
var item = patternItems[idx];
if (!item) {
continue;
}
if (item.type === Syntax.SpreadElement) {
// Spread/rest of an array.
// TODO(dmitrys): support spread in the middle of a pattern
// and also for function param patterns: [x, ...xs, y]
components.push(item.argument.name +
'=Array.prototype.slice.call(' +
utils.getTempVar(tmpIndex) + ',' + idx + ')'
);
continue;
}
if (item.type === Syntax.SpreadProperty) {
var restExpression = restPropertyHelpers.renderRestExpression(
utils.getTempVar(tmpIndex),
patternItems
);
components.push(item.argument.name + '=' + restExpression);
continue;
}
// Depending on pattern type (Array or Object), we get
// corresponding pattern item parts.
var accessor = getPatternItemAccessor(node, item, tmpIndex, idx);
var value = getPatternItemValue(node, item);
// TODO(dmitrys): implement default values: {x, y=5}
if (value.type === Syntax.Identifier) {
// Simple pattern item.
components.push(value.name + '=' + accessor);
} else {
// Complex sub-structure.
components.push(
utils.getTempVar(++state.localScope.tempVarIndex) + '=' + accessor +
',' + getDestructuredComponents(value, state)
);
}
}
return components.join(',');
}
function getPatternItems(node) {
return node.properties || node.elements;
}
function getPatternItemAccessor(node, patternItem, tmpIndex, idx) {
var tmpName = utils.getTempVar(tmpIndex);
if (node.type === Syntax.ObjectPattern) {
if (reservedWordsHelper.isReservedWord(patternItem.key.name)) {
return tmpName + '["' + patternItem.key.name + '"]';
} else if (patternItem.key.type === Syntax.Literal) {
return tmpName + '[' + JSON.stringify(patternItem.key.value) + ']';
} else if (patternItem.key.type === Syntax.Identifier) {
return tmpName + '.' + patternItem.key.name;
}
} else if (node.type === Syntax.ArrayPattern) {
return tmpName + '[' + idx + ']';
}
}
function getPatternItemValue(node, patternItem) {
return node.type === Syntax.ObjectPattern
? patternItem.value
: patternItem;
}
// -------------------------------------------------------
// 2. Assignment expression.
//
// [a, b] = [b, a];
// ({x, y} = {y, x});
// -------------------------------------------------------
function visitStructuredAssignment(traverse, node, path, state) {
var exprNode = node.expression;
utils.append('var ' + utils.getTempVar(state.localScope.tempVarIndex) + '=', state);
utils.catchupWhiteSpace(exprNode.right.range[0], state);
traverse(exprNode.right, path, state);
utils.catchup(exprNode.right.range[1], state);
utils.append(
';' + getDestructuredComponents(exprNode.left, state) + ';',
state
);
utils.catchupWhiteSpace(node.range[1], state);
state.localScope.tempVarIndex++;
return false;
}
visitStructuredAssignment.test = function(node, path, state) {
// We consider the expression statement rather than just assignment
// expression to cover case with object patters which should be
// wrapped in grouping operator: ({x, y} = {y, x});
return node.type === Syntax.ExpressionStatement &&
node.expression.type === Syntax.AssignmentExpression &&
isStructuredPattern(node.expression.left);
};
// -------------------------------------------------------
// 3. Structured parameter.
//
// function foo({x, y}) { ... }
// -------------------------------------------------------
function visitStructuredParameter(traverse, node, path, state) {
utils.append(utils.getTempVar(getParamIndex(node, path)), state);
utils.catchupWhiteSpace(node.range[1], state);
return true;
}
function getParamIndex(paramNode, path) {
var funcNode = path[0];
var tmpIndex = 0;
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (param === paramNode) {
break;
}
if (isStructuredPattern(param)) {
tmpIndex++;
}
}
return tmpIndex;
}
visitStructuredParameter.test = function(node, path, state) {
return isStructuredPattern(node) && isFunctionNode(path[0]);
};
function isFunctionNode(node) {
return (node.type == Syntax.FunctionDeclaration ||
node.type == Syntax.FunctionExpression ||
node.type == Syntax.MethodDefinition ||
node.type == Syntax.ArrowFunctionExpression);
}
// -------------------------------------------------------
// 4. Function body for structured parameters.
//
// function foo({x, y}) { x; y; }
// -------------------------------------------------------
function visitFunctionBodyForStructuredParameter(traverse, node, path, state) {
var funcNode = path[0];
utils.catchup(funcNode.body.range[0] + 1, state);
renderDestructuredComponents(funcNode, state);
if (funcNode.rest) {
utils.append(
restParamVisitors.renderRestParamSetup(funcNode, state),
state
);
}
return true;
}
function renderDestructuredComponents(funcNode, state) {
var destructuredComponents = [];
for (var k = 0; k < funcNode.params.length; k++) {
var param = funcNode.params[k];
if (isStructuredPattern(param)) {
destructuredComponents.push(
getDestructuredComponents(param, state)
);
state.localScope.tempVarIndex++;
}
}
if (destructuredComponents.length) {
utils.append('var ' + destructuredComponents.join(',') + ';', state);
}
}
visitFunctionBodyForStructuredParameter.test = function(node, path, state) {
return node.type === Syntax.BlockStatement && isFunctionNode(path[0]);
};
exports.visitorList = [
visitStructuredVariable,
visitStructuredAssignment,
visitStructuredParameter,
visitFunctionBodyForStructuredParameter
];
exports.renderDestructuredComponents = renderDestructuredComponents;
},{"../src/utils":23,"./es6-rest-param-visitors":30,"./es7-rest-property-helpers":32,"./reserved-words-helper":34,"esprima-fb":9}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node:true*/
/**
* Desugars concise methods of objects to function expressions.
*
* var foo = {
* method(x, y) { ... }
* };
*
* var foo = {
* method: function(x, y) { ... }
* };
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reservedWordsHelper = _dereq_('./reserved-words-helper');
function visitObjectConciseMethod(traverse, node, path, state) {
var isGenerator = node.value.generator;
if (isGenerator) {
utils.catchupWhiteSpace(node.range[0] + 1, state);
}
if (node.computed) { // [<expr>]() { ...}
utils.catchup(node.key.range[1] + 1, state);
} else if (reservedWordsHelper.isReservedWord(node.key.name)) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
}
utils.catchup(node.key.range[1], state);
utils.append(
':function' + (isGenerator ? '*' : ''),
state
);
path.unshift(node);
traverse(node.value, path, state);
path.shift();
return false;
}
visitObjectConciseMethod.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.value.type === Syntax.FunctionExpression &&
node.method === true;
};
exports.visitorList = [
visitObjectConciseMethod
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node: true*/
/**
* Desugars ES6 Object Literal short notations into ES3 full notation.
*
* // Easier return values.
* function foo(x, y) {
* return {x, y}; // {x: x, y: y}
* };
*
* // Destructuring.
* function init({port, ip, coords: {x, y}}) { ... }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* @public
*/
function visitObjectLiteralShortNotation(traverse, node, path, state) {
utils.catchup(node.key.range[1], state);
utils.append(':' + node.key.name, state);
return false;
}
visitObjectLiteralShortNotation.test = function(node, path, state) {
return node.type === Syntax.Property &&
node.kind === 'init' &&
node.shorthand === true &&
path[0].type !== Syntax.ObjectPattern;
};
exports.visitorList = [
visitObjectLiteralShortNotation
];
},{"../src/utils":23,"esprima-fb":9}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node:true*/
/**
* Desugars ES6 rest parameters into an ES3 arguments array.
*
* function printf(template, ...args) {
* args.forEach(...);
* }
*
* We could use `Array.prototype.slice.call`, but that usage of arguments causes
* functions to be deoptimized in V8, so instead we use a for-loop.
*
* function printf(template) {
* for (var args = [], $__0 = 1, $__1 = arguments.length; $__0 < $__1; $__0++)
* args.push(arguments[$__0]);
* args.forEach(...);
* }
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function _nodeIsFunctionWithRestParam(node) {
return (node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression)
&& node.rest;
}
function visitFunctionParamsWithRestParam(traverse, node, path, state) {
if (node.parametricType) {
utils.catchup(node.parametricType.range[0], state);
path.unshift(node);
traverse(node.parametricType, path, state);
path.shift();
}
// Render params.
if (node.params.length) {
path.unshift(node);
traverse(node.params, path, state);
path.shift();
} else {
// -3 is for ... of the rest.
utils.catchup(node.rest.range[0] - 3, state);
}
utils.catchupWhiteSpace(node.rest.range[1], state);
path.unshift(node);
traverse(node.body, path, state);
path.shift();
return false;
}
visitFunctionParamsWithRestParam.test = function(node, path, state) {
return _nodeIsFunctionWithRestParam(node);
};
function renderRestParamSetup(functionNode, state) {
var idx = state.localScope.tempVarIndex++;
var len = state.localScope.tempVarIndex++;
return 'for (var ' + functionNode.rest.name + '=[],' +
utils.getTempVar(idx) + '=' + functionNode.params.length + ',' +
utils.getTempVar(len) + '=arguments.length;' +
utils.getTempVar(idx) + '<' + utils.getTempVar(len) + ';' +
utils.getTempVar(idx) + '++) ' +
functionNode.rest.name + '.push(arguments[' + utils.getTempVar(idx) + ']);';
}
function visitFunctionBodyWithRestParam(traverse, node, path, state) {
utils.catchup(node.range[0] + 1, state);
var parentNode = path[0];
utils.append(renderRestParamSetup(parentNode, state), state);
return true;
}
visitFunctionBodyWithRestParam.test = function(node, path, state) {
return node.type === Syntax.BlockStatement
&& _nodeIsFunctionWithRestParam(path[0]);
};
exports.renderRestParamSetup = renderRestParamSetup;
exports.visitorList = [
visitFunctionParamsWithRestParam,
visitFunctionBodyWithRestParam
];
},{"../src/utils":23,"esprima-fb":9}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node:true*/
/**
* @typechecks
*/
'use strict';
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.1.9
*/
function visitTemplateLiteral(traverse, node, path, state) {
var templateElements = node.quasis;
utils.append('(', state);
for (var ii = 0; ii < templateElements.length; ii++) {
var templateElement = templateElements[ii];
if (templateElement.value.raw !== '') {
utils.append(getCookedValue(templateElement), state);
if (!templateElement.tail) {
// + between element and substitution
utils.append(' + ', state);
}
// maintain line numbers
utils.move(templateElement.range[0], state);
utils.catchupNewlines(templateElement.range[1], state);
} else { // templateElement.value.raw === ''
// Concatenat adjacent substitutions, e.g. `${x}${y}`. Empty templates
// appear before the first and after the last element - nothing to add in
// those cases.
if (ii > 0 && !templateElement.tail) {
// + between substitution and substitution
utils.append(' + ', state);
}
}
utils.move(templateElement.range[1], state);
if (!templateElement.tail) {
var substitution = node.expressions[ii];
if (substitution.type === Syntax.Identifier ||
substitution.type === Syntax.MemberExpression ||
substitution.type === Syntax.CallExpression) {
utils.catchup(substitution.range[1], state);
} else {
utils.append('(', state);
traverse(substitution, path, state);
utils.catchup(substitution.range[1], state);
utils.append(')', state);
}
// if next templateElement isn't empty...
if (templateElements[ii + 1].value.cooked !== '') {
utils.append(' + ', state);
}
}
}
utils.move(node.range[1], state);
utils.append(')', state);
return false;
}
visitTemplateLiteral.test = function(node, path, state) {
return node.type === Syntax.TemplateLiteral;
};
/**
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-12.2.6
*/
function visitTaggedTemplateExpression(traverse, node, path, state) {
var template = node.quasi;
var numQuasis = template.quasis.length;
// print the tag
utils.move(node.tag.range[0], state);
traverse(node.tag, path, state);
utils.catchup(node.tag.range[1], state);
// print array of template elements
utils.append('(function() { var siteObj = [', state);
for (var ii = 0; ii < numQuasis; ii++) {
utils.append(getCookedValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(']; siteObj.raw = [', state);
for (ii = 0; ii < numQuasis; ii++) {
utils.append(getRawValue(template.quasis[ii]), state);
if (ii !== numQuasis - 1) {
utils.append(', ', state);
}
}
utils.append(
']; Object.freeze(siteObj.raw); Object.freeze(siteObj); return siteObj; }()',
state
);
// print substitutions
if (numQuasis > 1) {
for (ii = 0; ii < template.expressions.length; ii++) {
var expression = template.expressions[ii];
utils.append(', ', state);
// maintain line numbers by calling catchupWhiteSpace over the whole
// previous TemplateElement
utils.move(template.quasis[ii].range[0], state);
utils.catchupNewlines(template.quasis[ii].range[1], state);
utils.move(expression.range[0], state);
traverse(expression, path, state);
utils.catchup(expression.range[1], state);
}
}
// print blank lines to push the closing ) down to account for the final
// TemplateElement.
utils.catchupNewlines(node.range[1], state);
utils.append(')', state);
return false;
}
visitTaggedTemplateExpression.test = function(node, path, state) {
return node.type === Syntax.TaggedTemplateExpression;
};
function getCookedValue(templateElement) {
return JSON.stringify(templateElement.value.cooked);
}
function getRawValue(templateElement) {
return JSON.stringify(templateElement.value.raw);
}
exports.visitorList = [
visitTemplateLiteral,
visitTaggedTemplateExpression
];
},{"../src/utils":23,"esprima-fb":9}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jslint node:true*/
/**
* Desugars ES7 rest properties into ES5 object iteration.
*/
var Syntax = _dereq_('esprima-fb').Syntax;
// TODO: This is a pretty massive helper, it should only be defined once, in the
// transform's runtime environment. We don't currently have a runtime though.
var restFunction =
'(function(source, exclusion) {' +
'var rest = {};' +
'var hasOwn = Object.prototype.hasOwnProperty;' +
'if (source == null) {' +
'throw new TypeError();' +
'}' +
'for (var key in source) {' +
'if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {' +
'rest[key] = source[key];' +
'}' +
'}' +
'return rest;' +
'})';
function getPropertyNames(properties) {
var names = [];
for (var i = 0; i < properties.length; i++) {
var property = properties[i];
if (property.type === Syntax.SpreadProperty) {
continue;
}
if (property.type === Syntax.Identifier) {
names.push(property.name);
} else {
names.push(property.key.name);
}
}
return names;
}
function getRestFunctionCall(source, exclusion) {
return restFunction + '(' + source + ',' + exclusion + ')';
}
function getSimpleShallowCopy(accessorExpression) {
// This could be faster with 'Object.assign({}, ' + accessorExpression + ')'
// but to unify code paths and avoid a ES6 dependency we use the same
// helper as for the exclusion case.
return getRestFunctionCall(accessorExpression, '{}');
}
function renderRestExpression(accessorExpression, excludedProperties) {
var excludedNames = getPropertyNames(excludedProperties);
if (!excludedNames.length) {
return getSimpleShallowCopy(accessorExpression);
}
return getRestFunctionCall(
accessorExpression,
'{' + excludedNames.join(':1,') + ':1}'
);
}
exports.renderRestExpression = renderRestExpression;
},{"esprima-fb":9}],33:[function(_dereq_,module,exports){
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*/
/*global exports:true*/
/**
* Implements ES7 object spread property.
* https://gist.github.com/sebmarkbage/aa849c7973cb4452c547
*
* { ...a, x: 1 }
*
* Object.assign({}, a, {x: 1 })
*
*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
function visitObjectLiteralSpread(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.append('Object.assign({', state);
// Skip the original {
utils.move(node.range[0] + 1, state);
var previousWasSpread = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}', state);
}
if (i === 0) {
// Normally there will be a comma when we catch up, but not before
// the first property.
utils.append(',', state);
}
utils.catchup(property.range[0], state);
// skip ...
utils.move(property.range[0] + 3, state);
traverse(property.argument, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = true;
} else {
utils.catchup(property.range[0], state);
if (previousWasSpread) {
utils.append('{', state);
}
traverse(property, path, state);
utils.catchup(property.range[1], state);
previousWasSpread = false;
}
}
// Strip any non-whitespace between the last item and the end.
// We only catch up on whitespace so that we ignore any trailing commas which
// are stripped out for IE8 support. Unfortunately, this also strips out any
// trailing comments.
utils.catchupWhiteSpace(node.range[1] - 1, state);
// Skip the trailing }
utils.move(node.range[1], state);
if (!previousWasSpread) {
utils.append('}', state);
}
utils.append(')', state);
return false;
}
visitObjectLiteralSpread.test = function(node, path, state) {
if (node.type !== Syntax.ObjectExpression) {
return false;
}
// Tight loop optimization
var hasAtLeastOneSpreadProperty = false;
for (var i = 0; i < node.properties.length; i++) {
var property = node.properties[i];
if (property.type === Syntax.SpreadProperty) {
hasAtLeastOneSpreadProperty = true;
} else if (property.kind !== 'init') {
return false;
}
}
return hasAtLeastOneSpreadProperty;
};
exports.visitorList = [
visitObjectLiteralSpread
];
},{"../src/utils":23,"esprima-fb":9}],34:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var KEYWORDS = [
'break', 'do', 'in', 'typeof', 'case', 'else', 'instanceof', 'var', 'catch',
'export', 'new', 'void', 'class', 'extends', 'return', 'while', 'const',
'finally', 'super', 'with', 'continue', 'for', 'switch', 'yield', 'debugger',
'function', 'this', 'default', 'if', 'throw', 'delete', 'import', 'try'
];
var FUTURE_RESERVED_WORDS = [
'enum', 'await', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var LITERALS = [
'null',
'true',
'false'
];
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words
var RESERVED_WORDS = [].concat(
KEYWORDS,
FUTURE_RESERVED_WORDS,
LITERALS
);
var reservedWordsMap = Object.create(null);
RESERVED_WORDS.forEach(function(k) {
reservedWordsMap[k] = true;
});
/**
* This list should not grow as new reserved words are introdued. This list is
* of words that need to be quoted because ES3-ish browsers do not allow their
* use as identifier names.
*/
var ES3_FUTURE_RESERVED_WORDS = [
'enum', 'implements', 'package', 'protected', 'static', 'interface',
'private', 'public'
];
var ES3_RESERVED_WORDS = [].concat(
KEYWORDS,
ES3_FUTURE_RESERVED_WORDS,
LITERALS
);
var es3ReservedWordsMap = Object.create(null);
ES3_RESERVED_WORDS.forEach(function(k) {
es3ReservedWordsMap[k] = true;
});
exports.isReservedWord = function(word) {
return !!reservedWordsMap[word];
};
exports.isES3ReservedWord = function(word) {
return !!es3ReservedWordsMap[word];
};
},{}],35:[function(_dereq_,module,exports){
/**
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*global exports:true*/
var Syntax = _dereq_('esprima-fb').Syntax;
var utils = _dereq_('../src/utils');
var reserverdWordsHelper = _dereq_('./reserved-words-helper');
/**
* Code adapted from https://github.com/spicyj/es3ify
* The MIT License (MIT)
* Copyright (c) 2014 Ben Alpert
*/
function visitProperty(traverse, node, path, state) {
utils.catchup(node.key.range[0], state);
utils.append('"', state);
utils.catchup(node.key.range[1], state);
utils.append('"', state);
utils.catchup(node.value.range[0], state);
traverse(node.value, path, state);
return false;
}
visitProperty.test = function(node) {
return node.type === Syntax.Property &&
node.key.type === Syntax.Identifier &&
!node.method &&
!node.shorthand &&
!node.computed &&
reserverdWordsHelper.isES3ReservedWord(node.key.name);
};
function visitMemberExpression(traverse, node, path, state) {
traverse(node.object, path, state);
utils.catchup(node.property.range[0] - 1, state);
utils.append('[', state);
utils.catchupWhiteSpace(node.property.range[0], state);
utils.append('"', state);
utils.catchup(node.property.range[1], state);
utils.append('"]', state);
return false;
}
visitMemberExpression.test = function(node) {
return node.type === Syntax.MemberExpression &&
node.property.type === Syntax.Identifier &&
reserverdWordsHelper.isES3ReservedWord(node.property.name);
};
exports.visitorList = [
visitProperty,
visitMemberExpression
];
},{"../src/utils":23,"./reserved-words-helper":34,"esprima-fb":9}],36:[function(_dereq_,module,exports){
var esprima = _dereq_('esprima-fb');
var utils = _dereq_('../src/utils');
var Syntax = esprima.Syntax;
function _isFunctionNode(node) {
return node.type === Syntax.FunctionDeclaration
|| node.type === Syntax.FunctionExpression
|| node.type === Syntax.ArrowFunctionExpression;
}
function visitClassProperty(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitClassProperty.test = function(node, path, state) {
return node.type === Syntax.ClassProperty;
};
function visitTypeAlias(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitTypeAlias.test = function(node, path, state) {
return node.type === Syntax.TypeAlias;
};
function visitTypeCast(traverse, node, path, state) {
path.unshift(node);
traverse(node.expression, path, state);
path.shift();
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeCast.test = function(node, path, state) {
return node.type === Syntax.TypeCastExpression;
};
function visitInterfaceDeclaration(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitInterfaceDeclaration.test = function(node, path, state) {
return node.type === Syntax.InterfaceDeclaration;
};
function visitDeclare(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitDeclare.test = function(node, path, state) {
switch (node.type) {
case Syntax.DeclareVariable:
case Syntax.DeclareFunction:
case Syntax.DeclareClass:
case Syntax.DeclareModule:
return true;
}
return false;
};
function visitFunctionParametricAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionParametricAnnotation.test = function(node, path, state) {
return node.type === Syntax.TypeParameterDeclaration
&& path[0]
&& _isFunctionNode(path[0])
&& node === path[0].typeParameters;
};
function visitFunctionReturnAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0], state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitFunctionReturnAnnotation.test = function(node, path, state) {
return path[0] && _isFunctionNode(path[0]) && node === path[0].returnType;
};
function visitOptionalFunctionParameterAnnotation(traverse, node, path, state) {
utils.catchup(node.range[0] + node.name.length, state);
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitOptionalFunctionParameterAnnotation.test = function(node, path, state) {
return node.type === Syntax.Identifier
&& node.optional
&& path[0]
&& _isFunctionNode(path[0]);
};
function visitTypeAnnotatedIdentifier(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedIdentifier.test = function(node, path, state) {
return node.type === Syntax.Identifier && node.typeAnnotation;
};
function visitTypeAnnotatedObjectOrArrayPattern(traverse, node, path, state) {
utils.catchup(node.typeAnnotation.range[0], state);
utils.catchupWhiteOut(node.typeAnnotation.range[1], state);
return false;
}
visitTypeAnnotatedObjectOrArrayPattern.test = function(node, path, state) {
var rightType = node.type === Syntax.ObjectPattern
|| node.type === Syntax.ArrayPattern;
return rightType && node.typeAnnotation;
};
/**
* Methods cause trouble, since esprima parses them as a key/value pair, where
* the location of the value starts at the method body. For example
* { bar(x:number,...y:Array<number>):number {} }
* is parsed as
* { bar: function(x: number, ...y:Array<number>): number {} }
* except that the location of the FunctionExpression value is 40-something,
* which is the location of the function body. This means that by the time we
* visit the params, rest param, and return type organically, we've already
* catchup()'d passed them.
*/
function visitMethod(traverse, node, path, state) {
path.unshift(node);
traverse(node.key, path, state);
path.unshift(node.value);
traverse(node.value.params, path, state);
node.value.rest && traverse(node.value.rest, path, state);
node.value.returnType && traverse(node.value.returnType, path, state);
traverse(node.value.body, path, state);
path.shift();
path.shift();
return false;
}
visitMethod.test = function(node, path, state) {
return (node.type === "Property" && (node.method || node.kind === "set" || node.kind === "get"))
|| (node.type === "MethodDefinition");
};
function visitImportType(traverse, node, path, state) {
utils.catchupWhiteOut(node.range[1], state);
return false;
}
visitImportType.test = function(node, path, state) {
return node.type === 'ImportDeclaration'
&& node.isType;
};
exports.visitorList = [
visitClassProperty,
visitDeclare,
visitImportType,
visitInterfaceDeclaration,
visitFunctionParametricAnnotation,
visitFunctionReturnAnnotation,
visitMethod,
visitOptionalFunctionParameterAnnotation,
visitTypeAlias,
visitTypeCast,
visitTypeAnnotatedIdentifier,
visitTypeAnnotatedObjectOrArrayPattern
];
},{"../src/utils":23,"esprima-fb":9}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function renderJSXLiteral(object, isLast, state, start, end) {
var lines = object.value.split(/\r\n|\n|\r/);
if (start) {
utils.append(start, state);
}
var lastNonEmptyLine = 0;
lines.forEach(function(line, index) {
if (line.match(/[^ \t]/)) {
lastNonEmptyLine = index;
}
});
lines.forEach(function(line, index) {
var isFirstLine = index === 0;
var isLastLine = index === lines.length - 1;
var isLastNonEmptyLine = index === lastNonEmptyLine;
// replace rendered whitespace tabs with spaces
var trimmedLine = line.replace(/\t/g, ' ');
// trim whitespace touching a newline
if (!isFirstLine) {
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
}
if (!isLastLine) {
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
}
if (!isFirstLine) {
utils.append(line.match(/^[ \t]*/)[0], state);
}
if (trimmedLine || isLastNonEmptyLine) {
utils.append(
JSON.stringify(trimmedLine) +
(!isLastNonEmptyLine ? ' + \' \' +' : ''),
state);
if (isLastNonEmptyLine) {
if (end) {
utils.append(end, state);
}
if (!isLast) {
utils.append(', ', state);
}
}
// only restore tail whitespace if line had literals
if (trimmedLine && !isLastLine) {
utils.append(line.match(/[ \t]*$/)[0], state);
}
}
if (!isLastLine) {
utils.append('\n', state);
}
});
utils.move(object.range[1], state);
}
function renderJSXExpressionContainer(traverse, object, isLast, path, state) {
// Plus 1 to skip `{`.
utils.move(object.range[0] + 1, state);
utils.catchup(object.expression.range[0], state);
traverse(object.expression, path, state);
if (!isLast && object.expression.type !== Syntax.JSXEmptyExpression) {
// If we need to append a comma, make sure to do so after the expression.
utils.catchup(object.expression.range[1], state, trimLeft);
utils.append(', ', state);
}
// Minus 1 to skip `}`.
utils.catchup(object.range[1] - 1, state, trimLeft);
utils.move(object.range[1], state);
return false;
}
function quoteAttrName(attr) {
// Quote invalid JS identifiers.
if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) {
return '"' + attr + '"';
}
return attr;
}
function trimLeft(value) {
return value.replace(/^[ ]+/, '');
}
exports.renderJSXExpressionContainer = renderJSXExpressionContainer;
exports.renderJSXLiteral = renderJSXLiteral;
exports.quoteAttrName = quoteAttrName;
exports.trimLeft = trimLeft;
},{"jstransform":22,"jstransform/src/utils":23}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
var renderJSXExpressionContainer =
_dereq_('./jsx').renderJSXExpressionContainer;
var renderJSXLiteral = _dereq_('./jsx').renderJSXLiteral;
var quoteAttrName = _dereq_('./jsx').quoteAttrName;
var trimLeft = _dereq_('./jsx').trimLeft;
/**
* Customized desugar processor for React JSX. Currently:
*
* <X> </X> => React.createElement(X, null)
* <X prop="1" /> => React.createElement(X, {prop: '1'}, null)
* <X prop="2"><Y /></X> => React.createElement(X, {prop:'2'},
* React.createElement(Y, null)
* )
* <div /> => React.createElement("div", null)
*/
/**
* Removes all non-whitespace/parenthesis characters
*/
var reNonWhiteParen = /([^\s\(\)])/g;
function stripNonWhiteParen(value) {
return value.replace(reNonWhiteParen, '');
}
var tagConvention = /^[a-z]|\-/;
function isTagName(name) {
return tagConvention.test(name);
}
function visitReactTag(traverse, object, path, state) {
var openingElement = object.openingElement;
var nameObject = openingElement.name;
var attributesObject = openingElement.attributes;
utils.catchup(openingElement.range[0], state, trimLeft);
if (nameObject.type === Syntax.JSXNamespacedName && nameObject.namespace) {
throw new Error('Namespace tags are not supported. ReactJSX is not XML.');
}
// We assume that the React runtime is already in scope
utils.append('React.createElement(', state);
if (nameObject.type === Syntax.JSXIdentifier && isTagName(nameObject.name)) {
utils.append('"' + nameObject.name + '"', state);
utils.move(nameObject.range[1], state);
} else {
// Use utils.catchup in this case so we can easily handle
// JSXMemberExpressions which look like Foo.Bar.Baz. This also handles
// JSXIdentifiers that aren't fallback tags.
utils.move(nameObject.range[0], state);
utils.catchup(nameObject.range[1], state);
}
utils.append(', ', state);
var hasAttributes = attributesObject.length;
var hasAtLeastOneSpreadProperty = attributesObject.some(function(attr) {
return attr.type === Syntax.JSXSpreadAttribute;
});
// if we don't have any attributes, pass in null
if (hasAtLeastOneSpreadProperty) {
utils.append('React.__spread({', state);
} else if (hasAttributes) {
utils.append('{', state);
} else {
utils.append('null', state);
}
// keep track of if the previous attribute was a spread attribute
var previousWasSpread = false;
// write attributes
attributesObject.forEach(function(attr, index) {
var isLast = index === attributesObject.length - 1;
if (attr.type === Syntax.JSXSpreadAttribute) {
// Close the previous object or initial object
if (!previousWasSpread) {
utils.append('}, ', state);
}
// Move to the expression start, ignoring everything except parenthesis
// and whitespace.
utils.catchup(attr.range[0], state, stripNonWhiteParen);
// Plus 1 to skip `{`.
utils.move(attr.range[0] + 1, state);
utils.catchup(attr.argument.range[0], state, stripNonWhiteParen);
traverse(attr.argument, path, state);
utils.catchup(attr.argument.range[1], state);
// Move to the end, ignoring parenthesis and the closing `}`
utils.catchup(attr.range[1] - 1, state, stripNonWhiteParen);
if (!isLast) {
utils.append(', ', state);
}
utils.move(attr.range[1], state);
previousWasSpread = true;
return;
}
// If the next attribute is a spread, we're effective last in this object
if (!isLast) {
isLast = attributesObject[index + 1].type === Syntax.JSXSpreadAttribute;
}
if (attr.name.namespace) {
throw new Error(
'Namespace attributes are not supported. ReactJSX is not XML.');
}
var name = attr.name.name;
utils.catchup(attr.range[0], state, trimLeft);
if (previousWasSpread) {
utils.append('{', state);
}
utils.append(quoteAttrName(name), state);
utils.append(': ', state);
if (!attr.value) {
state.g.buffer += 'true';
state.g.position = attr.name.range[1];
if (!isLast) {
utils.append(', ', state);
}
} else {
utils.move(attr.name.range[1], state);
// Use catchupNewlines to skip over the '=' in the attribute
utils.catchupNewlines(attr.value.range[0], state);
if (attr.value.type === Syntax.Literal) {
renderJSXLiteral(attr.value, isLast, state);
} else {
renderJSXExpressionContainer(traverse, attr.value, isLast, path, state);
}
}
utils.catchup(attr.range[1], state, trimLeft);
previousWasSpread = false;
});
if (!openingElement.selfClosing) {
utils.catchup(openingElement.range[1] - 1, state, trimLeft);
utils.move(openingElement.range[1], state);
}
if (hasAttributes && !previousWasSpread) {
utils.append('}', state);
}
if (hasAtLeastOneSpreadProperty) {
utils.append(')', state);
}
// filter out whitespace
var childrenToRender = object.children.filter(function(child) {
return !(child.type === Syntax.Literal
&& typeof child.value === 'string'
&& child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/));
});
if (childrenToRender.length > 0) {
var lastRenderableIndex;
childrenToRender.forEach(function(child, index) {
if (child.type !== Syntax.JSXExpressionContainer ||
child.expression.type !== Syntax.JSXEmptyExpression) {
lastRenderableIndex = index;
}
});
if (lastRenderableIndex !== undefined) {
utils.append(', ', state);
}
childrenToRender.forEach(function(child, index) {
utils.catchup(child.range[0], state, trimLeft);
var isLast = index >= lastRenderableIndex;
if (child.type === Syntax.Literal) {
renderJSXLiteral(child, isLast, state);
} else if (child.type === Syntax.JSXExpressionContainer) {
renderJSXExpressionContainer(traverse, child, isLast, path, state);
} else {
traverse(child, path, state);
if (!isLast) {
utils.append(', ', state);
}
}
utils.catchup(child.range[1], state, trimLeft);
});
}
if (openingElement.selfClosing) {
// everything up to />
utils.catchup(openingElement.range[1] - 2, state, trimLeft);
utils.move(openingElement.range[1], state);
} else {
// everything up to </ sdflksjfd>
utils.catchup(object.closingElement.range[0], state, trimLeft);
utils.move(object.closingElement.range[1], state);
}
utils.append(')', state);
return false;
}
visitReactTag.test = function(object, path, state) {
return object.type === Syntax.JSXElement;
};
exports.visitorList = [
visitReactTag
];
},{"./jsx":37,"jstransform":22,"jstransform/src/utils":23}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/*global exports:true*/
'use strict';
var Syntax = _dereq_('jstransform').Syntax;
var utils = _dereq_('jstransform/src/utils');
function addDisplayName(displayName, object, state) {
if (object &&
object.type === Syntax.CallExpression &&
object.callee.type === Syntax.MemberExpression &&
object.callee.object.type === Syntax.Identifier &&
object.callee.object.name === 'React' &&
object.callee.property.type === Syntax.Identifier &&
object.callee.property.name === 'createClass' &&
object.arguments.length === 1 &&
object.arguments[0].type === Syntax.ObjectExpression) {
// Verify that the displayName property isn't already set
var properties = object.arguments[0].properties;
var safe = properties.every(function(property) {
var value = property.key.type === Syntax.Identifier ?
property.key.name :
property.key.value;
return value !== 'displayName';
});
if (safe) {
utils.catchup(object.arguments[0].range[0] + 1, state);
utils.append('displayName: "' + displayName + '",', state);
}
}
}
/**
* Transforms the following:
*
* var MyComponent = React.createClass({
* render: ...
* });
*
* into:
*
* var MyComponent = React.createClass({
* displayName: 'MyComponent',
* render: ...
* });
*
* Also catches:
*
* MyComponent = React.createClass(...);
* exports.MyComponent = React.createClass(...);
* module.exports = {MyComponent: React.createClass(...)};
*/
function visitReactDisplayName(traverse, object, path, state) {
var left, right;
if (object.type === Syntax.AssignmentExpression) {
left = object.left;
right = object.right;
} else if (object.type === Syntax.Property) {
left = object.key;
right = object.value;
} else if (object.type === Syntax.VariableDeclarator) {
left = object.id;
right = object.init;
}
if (left && left.type === Syntax.MemberExpression) {
left = left.property;
}
if (left && left.type === Syntax.Identifier) {
addDisplayName(left.name, right, state);
}
}
visitReactDisplayName.test = function(object, path, state) {
return (
object.type === Syntax.AssignmentExpression ||
object.type === Syntax.Property ||
object.type === Syntax.VariableDeclarator
);
};
exports.visitorList = [
visitReactDisplayName
];
},{"jstransform":22,"jstransform/src/utils":23}],40:[function(_dereq_,module,exports){
/*global exports:true*/
'use strict';
var es6ArrowFunctions =
_dereq_('jstransform/visitors/es6-arrow-function-visitors');
var es6Classes = _dereq_('jstransform/visitors/es6-class-visitors');
var es6Destructuring =
_dereq_('jstransform/visitors/es6-destructuring-visitors');
var es6ObjectConciseMethod =
_dereq_('jstransform/visitors/es6-object-concise-method-visitors');
var es6ObjectShortNotation =
_dereq_('jstransform/visitors/es6-object-short-notation-visitors');
var es6RestParameters = _dereq_('jstransform/visitors/es6-rest-param-visitors');
var es6Templates = _dereq_('jstransform/visitors/es6-template-visitors');
var es6CallSpread =
_dereq_('jstransform/visitors/es6-call-spread-visitors');
var es7SpreadProperty =
_dereq_('jstransform/visitors/es7-spread-property-visitors');
var react = _dereq_('./transforms/react');
var reactDisplayName = _dereq_('./transforms/reactDisplayName');
var reservedWords = _dereq_('jstransform/visitors/reserved-words-visitors');
/**
* Map from transformName => orderedListOfVisitors.
*/
var transformVisitors = {
'es6-arrow-functions': es6ArrowFunctions.visitorList,
'es6-classes': es6Classes.visitorList,
'es6-destructuring': es6Destructuring.visitorList,
'es6-object-concise-method': es6ObjectConciseMethod.visitorList,
'es6-object-short-notation': es6ObjectShortNotation.visitorList,
'es6-rest-params': es6RestParameters.visitorList,
'es6-templates': es6Templates.visitorList,
'es6-call-spread': es6CallSpread.visitorList,
'es7-spread-property': es7SpreadProperty.visitorList,
'react': react.visitorList.concat(reactDisplayName.visitorList),
'reserved-words': reservedWords.visitorList
};
var transformSets = {
'harmony': [
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property'
],
'es3': [
'reserved-words'
],
'react': [
'react'
]
};
/**
* Specifies the order in which each transform should run.
*/
var transformRunOrder = [
'reserved-words',
'es6-arrow-functions',
'es6-object-concise-method',
'es6-object-short-notation',
'es6-classes',
'es6-rest-params',
'es6-templates',
'es6-destructuring',
'es6-call-spread',
'es7-spread-property',
'react'
];
/**
* Given a list of transform names, return the ordered list of visitors to be
* passed to the transform() function.
*
* @param {array?} excludes
* @return {array}
*/
function getAllVisitors(excludes) {
var ret = [];
for (var i = 0, il = transformRunOrder.length; i < il; i++) {
if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) {
ret = ret.concat(transformVisitors[transformRunOrder[i]]);
}
}
return ret;
}
/**
* Given a list of visitor set names, return the ordered list of visitors to be
* passed to jstransform.
*
* @param {array}
* @return {array}
*/
function getVisitorsBySet(sets) {
var visitorsToInclude = sets.reduce(function(visitors, set) {
if (!transformSets.hasOwnProperty(set)) {
throw new Error('Unknown visitor set: ' + set);
}
transformSets[set].forEach(function(visitor) {
visitors[visitor] = true;
});
return visitors;
}, {});
var visitorList = [];
for (var i = 0; i < transformRunOrder.length; i++) {
if (visitorsToInclude.hasOwnProperty(transformRunOrder[i])) {
visitorList = visitorList.concat(transformVisitors[transformRunOrder[i]]);
}
}
return visitorList;
}
exports.getVisitorsBySet = getVisitorsBySet;
exports.getAllVisitors = getAllVisitors;
exports.transformVisitors = transformVisitors;
},{"./transforms/react":38,"./transforms/reactDisplayName":39,"jstransform/visitors/es6-arrow-function-visitors":24,"jstransform/visitors/es6-call-spread-visitors":25,"jstransform/visitors/es6-class-visitors":26,"jstransform/visitors/es6-destructuring-visitors":27,"jstransform/visitors/es6-object-concise-method-visitors":28,"jstransform/visitors/es6-object-short-notation-visitors":29,"jstransform/visitors/es6-rest-param-visitors":30,"jstransform/visitors/es6-template-visitors":31,"jstransform/visitors/es7-spread-property-visitors":33,"jstransform/visitors/reserved-words-visitors":35}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/*eslint-disable no-undef*/
var Buffer = _dereq_('buffer').Buffer;
function inlineSourceMap(sourceMap, sourceCode, sourceFilename) {
// This can be used with a sourcemap that has already has toJSON called on it.
// Check first.
var json = sourceMap;
if (typeof sourceMap.toJSON === 'function') {
json = sourceMap.toJSON();
}
json.sources = [sourceFilename];
json.sourcesContent = [sourceCode];
var base64 = Buffer(JSON.stringify(json)).toString('base64');
return '//# sourceMappingURL=data:application/json;base64,' + base64;
}
module.exports = inlineSourceMap;
},{"buffer":3}]},{},[1])(1)
}); |
src/svg-icons/action/dashboard.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDashboard = (props) => (
<SvgIcon {...props}>
<path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/>
</SvgIcon>
);
ActionDashboard = pure(ActionDashboard);
ActionDashboard.displayName = 'ActionDashboard';
ActionDashboard.muiName = 'SvgIcon';
export default ActionDashboard;
|
packages/material-ui-icons/src/RoomOutlined.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zM7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9z" /><circle cx="12" cy="9" r="2.5" /></React.Fragment>
, 'RoomOutlined');
|
example/screens/TerribleNameScreen.js | GantMan/useless-things | import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import { TerribleName } from 'useless-things'
export default class App extends React.Component {
render () {
return (
<View style={styles.container}>
<Text style={styles.title}>Examples of Terrible Names</Text>
<Text style={styles.thing}>Terrible Name Generator</Text>
<Text style={styles.text}>
Random 1: {TerribleName() + '\n'}
Random 2: {TerribleName() + '\n'}
With Separator: {TerribleName('-') + '\n'}
</Text>
<Text style={[styles.title, {backgroundColor: 'rgba(0,0,0,0.4)'}]} onPress={() => this.forceUpdate()}>
GIVE ME MOAR!!!!
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#333',
alignItems: 'center',
justifyContent: 'center'
},
title: {
fontSize: 20,
fontWeight: 'bold',
color: 'red',
padding: 10
},
thing: {
fontSize: 18,
color: '#fff',
paddingTop: 40
},
text: {
color: '#ccc'
}
})
|
packages/react/src/components/UIShell/HeaderMenuButton.js | carbon-design-system/carbon-components | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { Close20, Menu20 } from '@carbon/icons-react';
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { AriaLabelPropType } from '../../prop-types/AriaPropTypes';
import { usePrefix } from '../../internal/usePrefix';
const HeaderMenuButton = ({
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
className: customClassName,
renderMenuIcon,
renderCloseIcon,
onClick,
isActive,
isCollapsible,
...rest
}) => {
const prefix = usePrefix();
const className = cx({
[customClassName]: !!customClassName,
[`${prefix}--header__action`]: true,
[`${prefix}--header__menu-trigger`]: true,
[`${prefix}--header__action--active`]: isActive,
[`${prefix}--header__menu-toggle`]: true,
[`${prefix}--header__menu-toggle__hidden`]: !isCollapsible,
});
const accessibilityLabel = {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
};
const menuIcon = renderMenuIcon ? renderMenuIcon : <Menu20 />;
const closeIcon = renderCloseIcon ? renderCloseIcon : <Close20 />;
return (
<button
{...rest}
{...accessibilityLabel}
className={className}
title={ariaLabel}
type="button"
onClick={onClick}>
{isActive ? closeIcon : menuIcon}
</button>
);
};
HeaderMenuButton.propTypes = {
/**
* Required props for accessibility label on the underlying menu button
*/
...AriaLabelPropType,
/**
* Optionally provide a custom class name that is applied to the underlying
* button
*/
className: PropTypes.string,
isActive: PropTypes.bool,
/**
* Optionally provide an onClick handler that is called when the underlying
* button fires it's onclick event
*/
onClick: PropTypes.func,
};
export default HeaderMenuButton;
|
app/components/Balance/__tests__/index-test.js | ModusCreateOrg/budgeting-sample-app-webpack2 | import React from 'react';
import renderer from 'react-test-renderer';
import Balance from '..';
it('renders correctly', () => {
const mockAmount = {
text: 'text',
isNegative: false,
};
const tree = renderer.create(<Balance title="title" amount={mockAmount} />).toJSON();
expect(tree).toMatchSnapshot();
});
it('renders correctly with a prefix', () => {
const mockAmount = {
text: 'text',
isNegative: false,
};
const tree = renderer.create(<Balance title="title" amount={mockAmount} prefix="prefix" />).toJSON();
expect(tree).toMatchSnapshot();
});
|
ajax/libs/react-select/1.0.0/react-select.es.js | wout/cdnjs | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import AutosizeInput from 'react-input-autosize';
import classNames from 'classnames';
function arrowRenderer(_ref) {
var onMouseDown = _ref.onMouseDown;
return React.createElement('span', {
className: 'Select-arrow',
onMouseDown: onMouseDown
});
}
arrowRenderer.propTypes = {
onMouseDown: PropTypes.func
};
var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }];
function stripDiacritics(str) {
for (var i = 0; i < map.length; i++) {
str = str.replace(map[i].letters, map[i].base);
}
return str;
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
function filterOptions(options, filterValue, excludeOptions, props) {
var _this = this;
if (props.ignoreAccents) {
filterValue = stripDiacritics(filterValue);
}
if (props.ignoreCase) {
filterValue = filterValue.toLowerCase();
}
if (props.trimFilter) {
filterValue = trim(filterValue);
}
if (excludeOptions) excludeOptions = excludeOptions.map(function (i) {
return i[props.valueKey];
});
return options.filter(function (option) {
if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false;
if (props.filterOption) return props.filterOption.call(_this, option, filterValue);
if (!filterValue) return true;
var valueTest = String(option[props.valueKey]);
var labelTest = String(option[props.labelKey]);
if (props.ignoreAccents) {
if (props.matchProp !== 'label') valueTest = stripDiacritics(valueTest);
if (props.matchProp !== 'value') labelTest = stripDiacritics(labelTest);
}
if (props.ignoreCase) {
if (props.matchProp !== 'label') valueTest = valueTest.toLowerCase();
if (props.matchProp !== 'value') labelTest = labelTest.toLowerCase();
}
return props.matchPos === 'start' ? props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0;
});
}
function menuRenderer(_ref) {
var focusedOption = _ref.focusedOption,
instancePrefix = _ref.instancePrefix,
labelKey = _ref.labelKey,
onFocus = _ref.onFocus,
onSelect = _ref.onSelect,
optionClassName = _ref.optionClassName,
optionComponent = _ref.optionComponent,
optionRenderer = _ref.optionRenderer,
options = _ref.options,
valueArray = _ref.valueArray,
valueKey = _ref.valueKey,
onOptionRef = _ref.onOptionRef;
var Option = optionComponent;
return options.map(function (option, i) {
var isSelected = valueArray && valueArray.some(function (x) {
return x[valueKey] == option[valueKey];
});
var isFocused = option === focusedOption;
var optionClass = classNames(optionClassName, {
'Select-option': true,
'is-selected': isSelected,
'is-focused': isFocused,
'is-disabled': option.disabled
});
return React.createElement(
Option,
{
className: optionClass,
instancePrefix: instancePrefix,
isDisabled: option.disabled,
isFocused: isFocused,
isSelected: isSelected,
key: 'option-' + i + '-' + option[valueKey],
onFocus: onFocus,
onSelect: onSelect,
option: option,
optionIndex: i,
ref: function ref(_ref2) {
onOptionRef(_ref2, isFocused);
}
},
optionRenderer(option, i)
);
});
}
function clearRenderer() {
return React.createElement('span', {
className: 'Select-clear',
dangerouslySetInnerHTML: { __html: '×' }
});
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var asyncGenerator = function () {
function AwaitValue(value) {
this.value = value;
}
function AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function (resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
if (value instanceof AwaitValue) {
Promise.resolve(value.value).then(function (arg) {
resume("next", arg);
}, function (arg) {
resume("throw", arg);
});
} else {
settle(result.done ? "return" : "normal", result.value);
}
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch (type) {
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== "function") {
this.return = undefined;
}
}
if (typeof Symbol === "function" && Symbol.asyncIterator) {
AsyncGenerator.prototype[Symbol.asyncIterator] = function () {
return this;
};
}
AsyncGenerator.prototype.next = function (arg) {
return this._invoke("next", arg);
};
AsyncGenerator.prototype.throw = function (arg) {
return this._invoke("throw", arg);
};
AsyncGenerator.prototype.return = function (arg) {
return this._invoke("return", arg);
};
return {
wrap: function (fn) {
return function () {
return new AsyncGenerator(fn.apply(this, arguments));
};
},
await: function (value) {
return new AwaitValue(value);
}
};
}();
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (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 _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var Option = function (_React$Component) {
inherits(Option, _React$Component);
function Option(props) {
classCallCheck(this, Option);
var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props));
_this.handleMouseDown = _this.handleMouseDown.bind(_this);
_this.handleMouseEnter = _this.handleMouseEnter.bind(_this);
_this.handleMouseMove = _this.handleMouseMove.bind(_this);
_this.handleTouchStart = _this.handleTouchStart.bind(_this);
_this.handleTouchEnd = _this.handleTouchEnd.bind(_this);
_this.handleTouchMove = _this.handleTouchMove.bind(_this);
_this.onFocus = _this.onFocus.bind(_this);
return _this;
}
createClass(Option, [{
key: 'blockEvent',
value: function blockEvent(event) {
event.preventDefault();
event.stopPropagation();
if (event.target.tagName !== 'A' || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
}
}, {
key: 'handleMouseEnter',
value: function handleMouseEnter(event) {
this.onFocus(event);
}
}, {
key: 'handleMouseMove',
value: function handleMouseMove(event) {
this.onFocus(event);
}
}, {
key: 'handleTouchEnd',
value: function handleTouchEnd(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
this.handleMouseDown(event);
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'onFocus',
value: function onFocus(event) {
if (!this.props.isFocused) {
this.props.onFocus(this.props.option, event);
}
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
option = _props.option,
instancePrefix = _props.instancePrefix,
optionIndex = _props.optionIndex;
var className = classNames(this.props.className, option.className);
return option.disabled ? React.createElement(
'div',
{ className: className,
onMouseDown: this.blockEvent,
onClick: this.blockEvent },
this.props.children
) : React.createElement(
'div',
{ className: className,
style: option.style,
role: 'option',
'aria-label': option.label,
onMouseDown: this.handleMouseDown,
onMouseEnter: this.handleMouseEnter,
onMouseMove: this.handleMouseMove,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove,
onTouchEnd: this.handleTouchEnd,
id: instancePrefix + '-option-' + optionIndex,
title: option.title },
this.props.children
);
}
}]);
return Option;
}(React.Component);
Option.propTypes = {
children: PropTypes.node,
className: PropTypes.string, // className (based on mouse position)
instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria)
isDisabled: PropTypes.bool, // the option is disabled
isFocused: PropTypes.bool, // the option is focused
isSelected: PropTypes.bool, // the option is selected
onFocus: PropTypes.func, // method to handle mouseEnter on option element
onSelect: PropTypes.func, // method to handle click on option element
onUnfocus: PropTypes.func, // method to handle mouseLeave on option element
option: PropTypes.object.isRequired, // object that is base for that option
optionIndex: PropTypes.number // index of the option, used to generate unique ids for aria
};
var Value = function (_React$Component) {
inherits(Value, _React$Component);
function Value(props) {
classCallCheck(this, Value);
var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props));
_this.handleMouseDown = _this.handleMouseDown.bind(_this);
_this.onRemove = _this.onRemove.bind(_this);
_this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this);
_this.handleTouchMove = _this.handleTouchMove.bind(_this);
_this.handleTouchStart = _this.handleTouchStart.bind(_this);
return _this;
}
createClass(Value, [{
key: 'handleMouseDown',
value: function handleMouseDown(event) {
if (event.type === 'mousedown' && event.button !== 0) {
return;
}
if (this.props.onClick) {
event.stopPropagation();
this.props.onClick(this.props.value, event);
return;
}
if (this.props.value.href) {
event.stopPropagation();
}
}
}, {
key: 'onRemove',
value: function onRemove(event) {
event.preventDefault();
event.stopPropagation();
this.props.onRemove(this.props.value);
}
}, {
key: 'handleTouchEndRemove',
value: function handleTouchEndRemove(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Fire the mouse events
this.onRemove(event);
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'renderRemoveIcon',
value: function renderRemoveIcon() {
if (this.props.disabled || !this.props.onRemove) return;
return React.createElement(
'span',
{ className: 'Select-value-icon',
'aria-hidden': 'true',
onMouseDown: this.onRemove,
onTouchEnd: this.handleTouchEndRemove,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove },
'\xD7'
);
}
}, {
key: 'renderLabel',
value: function renderLabel() {
var className = 'Select-value-label';
return this.props.onClick || this.props.value.href ? React.createElement(
'a',
{ className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown },
this.props.children
) : React.createElement(
'span',
{ className: className, role: 'option', 'aria-selected': 'true', id: this.props.id },
this.props.children
);
}
}, {
key: 'render',
value: function render() {
return React.createElement(
'div',
{ className: classNames('Select-value', this.props.value.className),
style: this.props.value.style,
title: this.props.value.title
},
this.renderRemoveIcon(),
this.renderLabel()
);
}
}]);
return Value;
}(React.Component);
Value.propTypes = {
children: PropTypes.node,
disabled: PropTypes.bool, // disabled prop passed to ReactSelect
id: PropTypes.string, // Unique id for the value - used for aria
onClick: PropTypes.func, // method to handle click on value label
onRemove: PropTypes.func, // method to handle removal of the value
value: PropTypes.object.isRequired // the option object for this value
};
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/react-select
*/
var stringifyValue = function stringifyValue(value) {
return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || '';
};
var stringOrNode = PropTypes.oneOfType([PropTypes.string, PropTypes.node]);
var stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
var instanceId = 1;
var Select$1 = function (_React$Component) {
inherits(Select, _React$Component);
function Select(props) {
classCallCheck(this, Select);
var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));
['clearValue', 'focusOption', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleRequired', 'handleTouchOutside', 'handleTouchMove', 'handleTouchStart', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleValueClick', 'getOptionLabel', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) {
return _this[fn] = _this[fn].bind(_this);
});
_this.state = {
inputValue: '',
isFocused: false,
isOpen: false,
isPseudoFocused: false,
required: false
};
return _this;
}
createClass(Select, [{
key: 'componentWillMount',
value: function componentWillMount() {
this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-';
var valueArray = this.getValueArray(this.props.value);
if (this.props.required) {
this.setState({
required: this.handleRequired(valueArray[0], this.props.multi)
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
if (typeof this.props.autofocus !== 'undefined' && typeof console !== 'undefined') {
console.warn('Warning: The autofocus prop has changed to autoFocus, support will be removed after [email protected]');
}
if (this.props.autoFocus || this.props.autofocus) {
this.focus();
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var valueArray = this.getValueArray(nextProps.value, nextProps);
if (nextProps.required) {
this.setState({
required: this.handleRequired(valueArray[0], nextProps.multi)
});
} else if (this.props.required) {
// Used to be required but it's not any more
this.setState({ required: false });
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps, prevState) {
// focus to the selected option
if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) {
var focusedOptionNode = findDOMNode(this.focused);
var menuNode = findDOMNode(this.menu);
menuNode.scrollTop = focusedOptionNode.offsetTop;
this.hasScrolledToOption = true;
} else if (!this.state.isOpen) {
this.hasScrolledToOption = false;
}
if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) {
this._scrollToFocusedOptionOnUpdate = false;
var focusedDOM = findDOMNode(this.focused);
var menuDOM = findDOMNode(this.menu);
var focusedRect = focusedDOM.getBoundingClientRect();
var menuRect = menuDOM.getBoundingClientRect();
if (focusedRect.bottom > menuRect.bottom) {
menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight;
} else if (focusedRect.top < menuRect.top) {
menuDOM.scrollTop = focusedDOM.offsetTop;
}
}
if (this.props.scrollMenuIntoView && this.menuContainer) {
var menuContainerRect = this.menuContainer.getBoundingClientRect();
if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) {
window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight);
}
}
if (prevProps.disabled !== this.props.disabled) {
this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state
this.closeMenu();
}
if (prevState.isOpen !== this.state.isOpen) {
this.toggleTouchOutsideEvent(this.state.isOpen);
var handler = this.state.isOpen ? this.props.onOpen : this.props.onClose;
handler && handler();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.toggleTouchOutsideEvent(false);
}
}, {
key: 'toggleTouchOutsideEvent',
value: function toggleTouchOutsideEvent(enabled) {
if (enabled) {
if (!document.addEventListener && document.attachEvent) {
document.attachEvent('ontouchstart', this.handleTouchOutside);
} else {
document.addEventListener('touchstart', this.handleTouchOutside);
}
} else {
if (!document.removeEventListener && document.detachEvent) {
document.detachEvent('ontouchstart', this.handleTouchOutside);
} else {
document.removeEventListener('touchstart', this.handleTouchOutside);
}
}
}
}, {
key: 'handleTouchOutside',
value: function handleTouchOutside(event) {
// handle touch outside on ios to dismiss menu
if (this.wrapper && !this.wrapper.contains(event.target)) {
this.closeMenu();
}
}
}, {
key: 'focus',
value: function focus() {
if (!this.input) return;
this.input.focus();
}
}, {
key: 'blurInput',
value: function blurInput() {
if (!this.input) return;
this.input.blur();
}
}, {
key: 'handleTouchMove',
value: function handleTouchMove(event) {
// Set a flag that the view is being dragged
this.dragging = true;
}
}, {
key: 'handleTouchStart',
value: function handleTouchStart(event) {
// Set a flag that the view is not being dragged
this.dragging = false;
}
}, {
key: 'handleTouchEnd',
value: function handleTouchEnd(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Fire the mouse events
this.handleMouseDown(event);
}
}, {
key: 'handleTouchEndClearValue',
value: function handleTouchEndClearValue(event) {
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if (this.dragging) return;
// Clear the value
this.clearValue(event);
}
}, {
key: 'handleMouseDown',
value: function handleMouseDown(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
if (event.target.tagName === 'INPUT') {
return;
}
// prevent default event handlers
event.stopPropagation();
event.preventDefault();
// for the non-searchable select, toggle the menu
if (!this.props.searchable) {
// TODO: This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open.
this.focus();
return this.setState({
isOpen: !this.state.isOpen
});
}
if (this.state.isFocused) {
// On iOS, we can get into a state where we think the input is focused but it isn't really,
// since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event.
// Call focus() again here to be safe.
this.focus();
var input = this.input;
if (typeof input.getInput === 'function') {
// Get the actual DOM input if the ref is an <AutosizeInput /> component
input = input.getInput();
}
// clears the value so that the cursor will be at the end of input when the component re-renders
input.value = '';
// if the input is focused, ensure the menu is open
this.setState({
isOpen: true,
isPseudoFocused: false
});
} else {
// otherwise, focus the input and open the menu
this._openAfterFocus = this.props.openOnClick;
this.focus();
}
}
}, {
key: 'handleMouseDownOnArrow',
value: function handleMouseDownOnArrow(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
// If the menu isn't open, let the event bubble to the main handleMouseDown
if (!this.state.isOpen) {
return;
}
// prevent default event handlers
event.stopPropagation();
event.preventDefault();
// close the menu
this.closeMenu();
}
}, {
key: 'handleMouseDownOnMenu',
value: function handleMouseDownOnMenu(event) {
// if the event was triggered by a mousedown and not the primary
// button, or if the component is disabled, ignore it.
if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this._openAfterFocus = true;
this.focus();
}
}, {
key: 'closeMenu',
value: function closeMenu() {
if (this.props.onCloseResetsInput) {
this.setState({
isOpen: false,
isPseudoFocused: this.state.isFocused && !this.props.multi,
inputValue: this.handleInputValueChange('')
});
} else {
this.setState({
isOpen: false,
isPseudoFocused: this.state.isFocused && !this.props.multi
});
}
this.hasScrolledToOption = false;
}
}, {
key: 'handleInputFocus',
value: function handleInputFocus(event) {
if (this.props.disabled) return;
var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus;
if (this.props.onFocus) {
this.props.onFocus(event);
}
this.setState({
isFocused: true,
isOpen: isOpen
});
this._openAfterFocus = false;
}
}, {
key: 'handleInputBlur',
value: function handleInputBlur(event) {
// The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts.
if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) {
this.focus();
return;
}
if (this.props.onBlur) {
this.props.onBlur(event);
}
var onBlurredState = {
isFocused: false,
isOpen: false,
isPseudoFocused: false
};
if (this.props.onBlurResetsInput) {
onBlurredState.inputValue = this.handleInputValueChange('');
}
this.setState(onBlurredState);
}
}, {
key: 'handleInputChange',
value: function handleInputChange(event) {
var newInputValue = event.target.value;
if (this.state.inputValue !== event.target.value) {
newInputValue = this.handleInputValueChange(newInputValue);
}
this.setState({
isOpen: true,
isPseudoFocused: false,
inputValue: newInputValue
});
}
}, {
key: 'handleInputValueChange',
value: function handleInputValueChange(newValue) {
if (this.props.onInputChange) {
var nextState = this.props.onInputChange(newValue);
// Note: != used deliberately here to catch undefined and null
if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') {
newValue = '' + nextState;
}
}
return newValue;
}
}, {
key: 'handleKeyDown',
value: function handleKeyDown(event) {
if (this.props.disabled) return;
if (typeof this.props.onInputKeyDown === 'function') {
this.props.onInputKeyDown(event);
if (event.defaultPrevented) {
return;
}
}
switch (event.keyCode) {
case 8:
// backspace
if (!this.state.inputValue && this.props.backspaceRemoves) {
event.preventDefault();
this.popValue();
}
return;
case 9:
// tab
if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) {
return;
}
event.preventDefault();
this.selectFocusedOption();
return;
case 13:
// enter
event.preventDefault();
event.stopPropagation();
if (this.state.isOpen) {
this.selectFocusedOption();
} else {
this.focusNextOption();
}
return;
break;
case 27:
// escape
if (this.state.isOpen) {
this.closeMenu();
event.stopPropagation();
} else if (this.props.clearable && this.props.escapeClearsValue) {
this.clearValue(event);
event.stopPropagation();
}
break;
case 32:
// space
if (this.props.searchable) {
return;
}
event.preventDefault();
if (!this.state.isOpen) {
this.focusNextOption();
return;
}
event.stopPropagation();
this.selectFocusedOption();
break;
case 38:
// up
this.focusPreviousOption();
break;
case 40:
// down
this.focusNextOption();
break;
case 33:
// page up
this.focusPageUpOption();
break;
case 34:
// page down
this.focusPageDownOption();
break;
case 35:
// end key
if (event.shiftKey) {
return;
}
this.focusEndOption();
break;
case 36:
// home key
if (event.shiftKey) {
return;
}
this.focusStartOption();
break;
case 46:
// delete
if (!this.state.inputValue && this.props.deleteRemoves) {
event.preventDefault();
this.popValue();
}
return;
default:
return;
}
event.preventDefault();
}
}, {
key: 'handleValueClick',
value: function handleValueClick(option, event) {
if (!this.props.onValueClick) return;
this.props.onValueClick(option, event);
}
}, {
key: 'handleMenuScroll',
value: function handleMenuScroll(event) {
if (!this.props.onMenuScrollToBottom) return;
var target = event.target;
if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) {
this.props.onMenuScrollToBottom();
}
}
}, {
key: 'handleRequired',
value: function handleRequired(value, multi) {
if (!value) return true;
return multi ? value.length === 0 : Object.keys(value).length === 0;
}
}, {
key: 'getOptionLabel',
value: function getOptionLabel(op) {
return op[this.props.labelKey];
}
/**
* Turns a value into an array from the given options
* @param {String|Number|Array} value - the value of the select input
* @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration
* @returns {Array} the value of the select represented in an array
*/
}, {
key: 'getValueArray',
value: function getValueArray(value, nextProps) {
var _this2 = this;
/** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */
var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props;
if (props.multi) {
if (typeof value === 'string') {
value = value.split(props.delimiter);
}
if (!Array.isArray(value)) {
if (value === null || value === undefined) return [];
value = [value];
}
return value.map(function (value) {
return _this2.expandValue(value, props);
}).filter(function (i) {
return i;
});
}
var expandedValue = this.expandValue(value, props);
return expandedValue ? [expandedValue] : [];
}
/**
* Retrieve a value from the given options and valueKey
* @param {String|Number|Array} value - the selected value(s)
* @param {Object} props - the Select component's props (or nextProps)
*/
}, {
key: 'expandValue',
value: function expandValue(value, props) {
var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value;
var options = props.options,
valueKey = props.valueKey;
if (!options) return;
for (var i = 0; i < options.length; i++) {
if (String(options[i][valueKey]) === String(value)) return options[i];
}
}
}, {
key: 'setValue',
value: function setValue(value) {
var _this3 = this;
if (this.props.autoBlur) {
this.blurInput();
}
if (this.props.required) {
var required = this.handleRequired(value, this.props.multi);
this.setState({ required: required });
}
if (this.props.onChange) {
if (this.props.simpleValue && value) {
value = this.props.multi ? value.map(function (i) {
return i[_this3.props.valueKey];
}).join(this.props.delimiter) : value[this.props.valueKey];
}
this.props.onChange(value);
}
}
}, {
key: 'selectValue',
value: function selectValue(value) {
var _this4 = this;
// NOTE: we actually add/set the value in a callback to make sure the
// input value is empty to avoid styling issues in Chrome
if (this.props.closeOnSelect) {
this.hasScrolledToOption = false;
}
if (this.props.multi) {
var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue;
this.setState({
focusedIndex: null,
inputValue: this.handleInputValueChange(updatedValue),
isOpen: !this.props.closeOnSelect
}, function () {
var valueArray = _this4.getValueArray(_this4.props.value);
if (valueArray.some(function (i) {
return i[_this4.props.valueKey] === value[_this4.props.valueKey];
})) {
_this4.removeValue(value);
} else {
_this4.addValue(value);
}
});
} else {
this.setState({
inputValue: this.handleInputValueChange(''),
isOpen: !this.props.closeOnSelect,
isPseudoFocused: this.state.isFocused
}, function () {
_this4.setValue(value);
});
}
}
}, {
key: 'addValue',
value: function addValue(value) {
var valueArray = this.getValueArray(this.props.value);
var visibleOptions = this._visibleOptions.filter(function (val) {
return !val.disabled;
});
var lastValueIndex = visibleOptions.indexOf(value);
this.setValue(valueArray.concat(value));
if (visibleOptions.length - 1 === lastValueIndex) {
// the last option was selected; focus the second-last one
this.focusOption(visibleOptions[lastValueIndex - 1]);
} else if (visibleOptions.length > lastValueIndex) {
// focus the option below the selected one
this.focusOption(visibleOptions[lastValueIndex + 1]);
}
}
}, {
key: 'popValue',
value: function popValue() {
var valueArray = this.getValueArray(this.props.value);
if (!valueArray.length) return;
if (valueArray[valueArray.length - 1].clearableValue === false) return;
this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null);
}
}, {
key: 'removeValue',
value: function removeValue(value) {
var _this5 = this;
var valueArray = this.getValueArray(this.props.value);
this.setValue(valueArray.filter(function (i) {
return i[_this5.props.valueKey] !== value[_this5.props.valueKey];
}));
this.focus();
}
}, {
key: 'clearValue',
value: function clearValue(event) {
// if the event was triggered by a mousedown and not the primary
// button, ignore it.
if (event && event.type === 'mousedown' && event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this.setValue(this.getResetValue());
this.setState({
isOpen: false,
inputValue: this.handleInputValueChange('')
}, this.focus);
}
}, {
key: 'getResetValue',
value: function getResetValue() {
if (this.props.resetValue !== undefined) {
return this.props.resetValue;
} else if (this.props.multi) {
return [];
} else {
return null;
}
}
}, {
key: 'focusOption',
value: function focusOption(option) {
this.setState({
focusedOption: option
});
}
}, {
key: 'focusNextOption',
value: function focusNextOption() {
this.focusAdjacentOption('next');
}
}, {
key: 'focusPreviousOption',
value: function focusPreviousOption() {
this.focusAdjacentOption('previous');
}
}, {
key: 'focusPageUpOption',
value: function focusPageUpOption() {
this.focusAdjacentOption('page_up');
}
}, {
key: 'focusPageDownOption',
value: function focusPageDownOption() {
this.focusAdjacentOption('page_down');
}
}, {
key: 'focusStartOption',
value: function focusStartOption() {
this.focusAdjacentOption('start');
}
}, {
key: 'focusEndOption',
value: function focusEndOption() {
this.focusAdjacentOption('end');
}
}, {
key: 'focusAdjacentOption',
value: function focusAdjacentOption(dir) {
var options = this._visibleOptions.map(function (option, index) {
return { option: option, index: index };
}).filter(function (option) {
return !option.option.disabled;
});
this._scrollToFocusedOptionOnUpdate = true;
if (!this.state.isOpen) {
this.setState({
isOpen: true,
inputValue: '',
focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null)
});
return;
}
if (!options.length) return;
var focusedIndex = -1;
for (var i = 0; i < options.length; i++) {
if (this._focusedOption === options[i].option) {
focusedIndex = i;
break;
}
}
if (dir === 'next' && focusedIndex !== -1) {
focusedIndex = (focusedIndex + 1) % options.length;
} else if (dir === 'previous') {
if (focusedIndex > 0) {
focusedIndex = focusedIndex - 1;
} else {
focusedIndex = options.length - 1;
}
} else if (dir === 'start') {
focusedIndex = 0;
} else if (dir === 'end') {
focusedIndex = options.length - 1;
} else if (dir === 'page_up') {
var potentialIndex = focusedIndex - this.props.pageSize;
if (potentialIndex < 0) {
focusedIndex = 0;
} else {
focusedIndex = potentialIndex;
}
} else if (dir === 'page_down') {
var potentialIndex = focusedIndex + this.props.pageSize;
if (potentialIndex > options.length - 1) {
focusedIndex = options.length - 1;
} else {
focusedIndex = potentialIndex;
}
}
if (focusedIndex === -1) {
focusedIndex = 0;
}
this.setState({
focusedIndex: options[focusedIndex].index,
focusedOption: options[focusedIndex].option
});
}
}, {
key: 'getFocusedOption',
value: function getFocusedOption() {
return this._focusedOption;
}
}, {
key: 'selectFocusedOption',
value: function selectFocusedOption() {
if (this._focusedOption) {
return this.selectValue(this._focusedOption);
}
}
}, {
key: 'renderLoading',
value: function renderLoading() {
if (!this.props.isLoading) return;
return React.createElement(
'span',
{ className: 'Select-loading-zone', 'aria-hidden': 'true' },
React.createElement('span', { className: 'Select-loading' })
);
}
}, {
key: 'renderValue',
value: function renderValue(valueArray, isOpen) {
var _this6 = this;
var renderLabel = this.props.valueRenderer || this.getOptionLabel;
var ValueComponent = this.props.valueComponent;
if (!valueArray.length) {
return !this.state.inputValue ? React.createElement(
'div',
{ className: 'Select-placeholder' },
this.props.placeholder
) : null;
}
var onClick = this.props.onValueClick ? this.handleValueClick : null;
if (this.props.multi) {
return valueArray.map(function (value, i) {
return React.createElement(
ValueComponent,
{
id: _this6._instancePrefix + '-value-' + i,
instancePrefix: _this6._instancePrefix,
disabled: _this6.props.disabled || value.clearableValue === false,
key: 'value-' + i + '-' + value[_this6.props.valueKey],
onClick: onClick,
onRemove: _this6.removeValue,
value: value
},
renderLabel(value, i),
React.createElement(
'span',
{ className: 'Select-aria-only' },
'\xA0'
)
);
});
} else if (!this.state.inputValue) {
if (isOpen) onClick = null;
return React.createElement(
ValueComponent,
{
id: this._instancePrefix + '-value-item',
disabled: this.props.disabled,
instancePrefix: this._instancePrefix,
onClick: onClick,
value: valueArray[0]
},
renderLabel(valueArray[0])
);
}
}
}, {
key: 'renderInput',
value: function renderInput(valueArray, focusedOptionIndex) {
var _classNames,
_this7 = this;
var className = classNames('Select-input', this.props.inputProps.className);
var isOpen = !!this.state.isOpen;
var ariaOwns = classNames((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames));
var inputProps = _extends({}, this.props.inputProps, {
role: 'combobox',
'aria-expanded': '' + isOpen,
'aria-owns': ariaOwns,
'aria-haspopup': '' + isOpen,
'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
'aria-describedby': this.props['aria-describedby'],
'aria-labelledby': this.props['aria-labelledby'],
'aria-label': this.props['aria-label'],
className: className,
tabIndex: this.props.tabIndex,
onBlur: this.handleInputBlur,
onChange: this.handleInputChange,
onFocus: this.handleInputFocus,
ref: function ref(_ref) {
return _this7.input = _ref;
},
required: this.state.required,
value: this.state.inputValue
});
if (this.props.inputRenderer) {
return this.props.inputRenderer(inputProps);
}
if (this.props.disabled || !this.props.searchable) {
var _props$inputProps = this.props.inputProps,
inputClassName = _props$inputProps.inputClassName,
divProps = objectWithoutProperties(_props$inputProps, ['inputClassName']);
var _ariaOwns = classNames(defineProperty({}, this._instancePrefix + '-list', isOpen));
return React.createElement('div', _extends({}, divProps, {
role: 'combobox',
'aria-expanded': isOpen,
'aria-owns': _ariaOwns,
'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value',
'aria-labelledby': this.props['aria-labelledby'],
'aria-label': this.props['aria-label'],
className: className,
tabIndex: this.props.tabIndex || 0,
onBlur: this.handleInputBlur,
onFocus: this.handleInputFocus,
ref: function ref(_ref2) {
return _this7.input = _ref2;
},
'aria-disabled': '' + !!this.props.disabled,
style: { border: 0, width: 1, display: 'inline-block' } }));
}
if (this.props.autosize) {
return React.createElement(AutosizeInput, _extends({ id: this.props.id }, inputProps, { minWidth: '5' }));
}
return React.createElement(
'div',
{ className: className, key: 'input-wrap' },
React.createElement('input', _extends({ id: this.props.id }, inputProps))
);
}
}, {
key: 'renderClear',
value: function renderClear() {
var valueArray = this.getValueArray(this.props.value);
if (!this.props.clearable || !valueArray.length || this.props.disabled || this.props.isLoading) return;
var clear = this.props.clearRenderer();
return React.createElement(
'span',
{ className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText,
'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText,
onMouseDown: this.clearValue,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove,
onTouchEnd: this.handleTouchEndClearValue
},
clear
);
}
}, {
key: 'renderArrow',
value: function renderArrow() {
if (!this.props.arrowRenderer) return;
var onMouseDown = this.handleMouseDownOnArrow;
var isOpen = this.state.isOpen;
var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen });
if (!arrow) {
return null;
}
return React.createElement(
'span',
{
className: 'Select-arrow-zone',
onMouseDown: onMouseDown
},
arrow
);
}
}, {
key: 'filterOptions',
value: function filterOptions$$1(excludeOptions) {
var filterValue = this.state.inputValue;
var options = this.props.options || [];
if (this.props.filterOptions) {
// Maintain backwards compatibility with boolean attribute
var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions;
return filterOptions$$1(options, filterValue, excludeOptions, {
filterOption: this.props.filterOption,
ignoreAccents: this.props.ignoreAccents,
ignoreCase: this.props.ignoreCase,
labelKey: this.props.labelKey,
matchPos: this.props.matchPos,
matchProp: this.props.matchProp,
valueKey: this.props.valueKey,
trimFilter: this.props.trimFilter
});
} else {
return options;
}
}
}, {
key: 'onOptionRef',
value: function onOptionRef(ref, isFocused) {
if (isFocused) {
this.focused = ref;
}
}
}, {
key: 'renderMenu',
value: function renderMenu(options, valueArray, focusedOption) {
if (options && options.length) {
return this.props.menuRenderer({
focusedOption: focusedOption,
focusOption: this.focusOption,
inputValue: this.state.inputValue,
instancePrefix: this._instancePrefix,
labelKey: this.props.labelKey,
onFocus: this.focusOption,
onSelect: this.selectValue,
optionClassName: this.props.optionClassName,
optionComponent: this.props.optionComponent,
optionRenderer: this.props.optionRenderer || this.getOptionLabel,
options: options,
selectValue: this.selectValue,
removeValue: this.removeValue,
valueArray: valueArray,
valueKey: this.props.valueKey,
onOptionRef: this.onOptionRef
});
} else if (this.props.noResultsText) {
return React.createElement(
'div',
{ className: 'Select-noresults' },
this.props.noResultsText
);
} else {
return null;
}
}
}, {
key: 'renderHiddenField',
value: function renderHiddenField(valueArray) {
var _this8 = this;
if (!this.props.name) return;
if (this.props.joinValues) {
var value = valueArray.map(function (i) {
return stringifyValue(i[_this8.props.valueKey]);
}).join(this.props.delimiter);
return React.createElement('input', {
type: 'hidden',
ref: function ref(_ref3) {
return _this8.value = _ref3;
},
name: this.props.name,
value: value,
disabled: this.props.disabled });
}
return valueArray.map(function (item, index) {
return React.createElement('input', { key: 'hidden.' + index,
type: 'hidden',
ref: 'value' + index,
name: _this8.props.name,
value: stringifyValue(item[_this8.props.valueKey]),
disabled: _this8.props.disabled });
});
}
}, {
key: 'getFocusableOptionIndex',
value: function getFocusableOptionIndex(selectedOption) {
var options = this._visibleOptions;
if (!options.length) return null;
var valueKey = this.props.valueKey;
var focusedOption = this.state.focusedOption || selectedOption;
if (focusedOption && !focusedOption.disabled) {
var focusedOptionIndex = -1;
options.some(function (option, index) {
var isOptionEqual = option[valueKey] === focusedOption[valueKey];
if (isOptionEqual) {
focusedOptionIndex = index;
}
return isOptionEqual;
});
if (focusedOptionIndex !== -1) {
return focusedOptionIndex;
}
}
for (var i = 0; i < options.length; i++) {
if (!options[i].disabled) return i;
}
return null;
}
}, {
key: 'renderOuter',
value: function renderOuter(options, valueArray, focusedOption) {
var _this9 = this;
var menu = this.renderMenu(options, valueArray, focusedOption);
if (!menu) {
return null;
}
return React.createElement(
'div',
{ ref: function ref(_ref5) {
return _this9.menuContainer = _ref5;
}, className: 'Select-menu-outer', style: this.props.menuContainerStyle },
React.createElement(
'div',
{ ref: function ref(_ref4) {
return _this9.menu = _ref4;
}, role: 'listbox', tabIndex: -1, className: 'Select-menu', id: this._instancePrefix + '-list',
style: this.props.menuStyle,
onScroll: this.handleMenuScroll,
onMouseDown: this.handleMouseDownOnMenu },
menu
)
);
}
}, {
key: 'render',
value: function render() {
var _this10 = this;
var valueArray = this.getValueArray(this.props.value);
var options = this._visibleOptions = this.filterOptions(this.props.multi && this.props.removeSelected ? valueArray : null);
var isOpen = this.state.isOpen;
if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false;
var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]);
var focusedOption = null;
if (focusedOptionIndex !== null) {
focusedOption = this._focusedOption = options[focusedOptionIndex];
} else {
focusedOption = this._focusedOption = null;
}
var className = classNames('Select', this.props.className, {
'Select--multi': this.props.multi,
'Select--single': !this.props.multi,
'is-clearable': this.props.clearable,
'is-disabled': this.props.disabled,
'is-focused': this.state.isFocused,
'is-loading': this.props.isLoading,
'is-open': isOpen,
'is-pseudo-focused': this.state.isPseudoFocused,
'is-searchable': this.props.searchable,
'has-value': valueArray.length,
'Select--rtl': this.props.rtl
});
var removeMessage = null;
if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) {
removeMessage = React.createElement(
'span',
{ id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' },
this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey])
);
}
return React.createElement(
'div',
{ ref: function ref(_ref7) {
return _this10.wrapper = _ref7;
},
className: className,
style: this.props.wrapperStyle },
this.renderHiddenField(valueArray),
React.createElement(
'div',
{ ref: function ref(_ref6) {
return _this10.control = _ref6;
},
className: 'Select-control',
style: this.props.style,
onKeyDown: this.handleKeyDown,
onMouseDown: this.handleMouseDown,
onTouchEnd: this.handleTouchEnd,
onTouchStart: this.handleTouchStart,
onTouchMove: this.handleTouchMove
},
React.createElement(
'span',
{ className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' },
this.renderValue(valueArray, isOpen),
this.renderInput(valueArray, focusedOptionIndex)
),
removeMessage,
this.renderLoading(),
this.renderClear(),
this.renderArrow()
),
isOpen ? this.renderOuter(options, valueArray, focusedOption) : null
);
}
}]);
return Select;
}(React.Component);
Select$1.propTypes = {
'aria-describedby': PropTypes.string, // html id(s) of element(s) that should be used to describe this input (for assistive tech)
'aria-label': PropTypes.string, // aria label (for assistive tech)
'aria-labelledby': PropTypes.string, // html id of an element that should be used as the label (for assistive tech)
arrowRenderer: PropTypes.func, // create the drop-down caret element
autoBlur: PropTypes.bool, // automatically blur the component when an option is selected
autoFocus: PropTypes.bool, // autofocus the component on mount
autofocus: PropTypes.bool, // deprecated; use autoFocus instead
autosize: PropTypes.bool, // whether to enable autosizing or not
backspaceRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input
backspaceToRemoveMessage: PropTypes.string, // message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label
className: PropTypes.string, // className for the outer element
clearAllText: stringOrNode, // title for the "clear" control when multi: true
clearRenderer: PropTypes.func, // create clearable x element
clearValueText: stringOrNode, // title for the "clear" control
clearable: PropTypes.bool, // should it be possible to reset value
closeOnSelect: PropTypes.bool, // whether to close the menu when a value is selected
deleteRemoves: PropTypes.bool, // whether delete removes an item if there is no text input
delimiter: PropTypes.string, // delimiter to use to join multiple values for the hidden field value
disabled: PropTypes.bool, // whether the Select is disabled or not
escapeClearsValue: PropTypes.bool, // whether escape clears the value when the menu is closed
filterOption: PropTypes.func, // method to filter a single option (option, filterString)
filterOptions: PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values])
id: PropTypes.string, // html id to set on the input element for accessibility or tests
ignoreAccents: PropTypes.bool, // whether to strip diacritics when filtering
ignoreCase: PropTypes.bool, // whether to perform case-insensitive filtering
inputProps: PropTypes.object, // custom attributes for the Input
inputRenderer: PropTypes.func, // returns a custom input component
instanceId: PropTypes.string, // set the components instanceId
isLoading: PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded)
joinValues: PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode)
labelKey: PropTypes.string, // path of the label value in option objects
matchPos: PropTypes.string, // (any|start) match the start or entire string when filtering
matchProp: PropTypes.string, // (any|label|value) which option property to filter on
menuBuffer: PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu
menuContainerStyle: PropTypes.object, // optional style to apply to the menu container
menuRenderer: PropTypes.func, // renders a custom menu with options
menuStyle: PropTypes.object, // optional style to apply to the menu
multi: PropTypes.bool, // multi-value input
name: PropTypes.string, // generates a hidden <input /> tag with this field name for html forms
noResultsText: stringOrNode, // placeholder displayed when there are no matching search results
onBlur: PropTypes.func, // onBlur handler: function (event) {}
onBlurResetsInput: PropTypes.bool, // whether input is cleared on blur
onChange: PropTypes.func, // onChange handler: function (newValue) {}
onClose: PropTypes.func, // fires when the menu is closed
onCloseResetsInput: PropTypes.bool, // whether input is cleared when menu is closed through the arrow
onFocus: PropTypes.func, // onFocus handler: function (event) {}
onInputChange: PropTypes.func, // onInputChange handler: function (inputValue) {}
onInputKeyDown: PropTypes.func, // input keyDown handler: function (event) {}
onMenuScrollToBottom: PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options
onOpen: PropTypes.func, // fires when the menu is opened
onSelectResetsInput: PropTypes.bool, // whether input is cleared on select (works only for multiselect)
onValueClick: PropTypes.func, // onClick handler for value labels: function (value, event) {}
openOnClick: PropTypes.bool, // boolean to control opening the menu when the control is clicked
openOnFocus: PropTypes.bool, // always open options menu on focus
optionClassName: PropTypes.string, // additional class(es) to apply to the <Option /> elements
optionComponent: PropTypes.func, // option component to render in dropdown
optionRenderer: PropTypes.func, // optionRenderer: function (option) {}
options: PropTypes.array, // array of options
pageSize: PropTypes.number, // number of entries to page when using page up/down keys
placeholder: stringOrNode, // field placeholder, displayed when there's no value
removeSelected: PropTypes.bool, // whether the selected option is removed from the dropdown on multi selects
required: PropTypes.bool, // applies HTML5 required attribute when needed
resetValue: PropTypes.any, // value to use when you clear the control
rtl: PropTypes.bool, // set to true in order to use react-select in right-to-left direction
scrollMenuIntoView: PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged
searchable: PropTypes.bool, // whether to enable searching feature or not
simpleValue: PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false
style: PropTypes.object, // optional style to apply to the control
tabIndex: stringOrNumber, // optional tab index of the control
tabSelectsValue: PropTypes.bool, // whether to treat tabbing out while focused to be value selection
trimFilter: PropTypes.bool, // whether to trim whitespace around filter value
value: PropTypes.any, // initial field value
valueComponent: PropTypes.func, // value component to render
valueKey: PropTypes.string, // path of the label value in option objects
valueRenderer: PropTypes.func, // valueRenderer: function (option) {}
wrapperStyle: PropTypes.object // optional style to apply to the component wrapper
};
Select$1.defaultProps = {
arrowRenderer: arrowRenderer,
autosize: true,
backspaceRemoves: true,
backspaceToRemoveMessage: 'Press backspace to remove {label}',
clearable: true,
clearAllText: 'Clear all',
clearRenderer: clearRenderer,
clearValueText: 'Clear value',
closeOnSelect: true,
deleteRemoves: true,
delimiter: ',',
disabled: false,
escapeClearsValue: true,
filterOptions: filterOptions,
ignoreAccents: true,
ignoreCase: true,
inputProps: {},
isLoading: false,
joinValues: false,
labelKey: 'label',
matchPos: 'any',
matchProp: 'any',
menuBuffer: 0,
menuRenderer: menuRenderer,
multi: false,
noResultsText: 'No results found',
onBlurResetsInput: true,
onSelectResetsInput: true,
onCloseResetsInput: true,
openOnClick: true,
optionComponent: Option,
pageSize: 5,
placeholder: 'Select...',
removeSelected: true,
required: false,
rtl: false,
scrollMenuIntoView: true,
searchable: true,
simpleValue: false,
tabSelectsValue: true,
trimFilter: true,
valueComponent: Value,
valueKey: 'value'
};
var propTypes = {
autoload: PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true
cache: PropTypes.any, // object to use to cache results; set to null/false to disable caching
children: PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element
ignoreAccents: PropTypes.bool, // strip diacritics when filtering; defaults to true
ignoreCase: PropTypes.bool, // perform case-insensitive filtering; defaults to true
loadOptions: PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise
loadingPlaceholder: PropTypes.oneOfType([// replaces the placeholder while options are loading
PropTypes.string, PropTypes.node]),
multi: PropTypes.bool, // multi-value input
noResultsText: PropTypes.oneOfType([// field noResultsText, displayed when no options come back from the server
PropTypes.string, PropTypes.node]),
onChange: PropTypes.func, // onChange handler: function (newValue) {}
onInputChange: PropTypes.func, // optional for keeping track of what is being typed
options: PropTypes.array.isRequired, // array of options
placeholder: PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select)
PropTypes.string, PropTypes.node]),
searchPromptText: PropTypes.oneOfType([// label to prompt for search input
PropTypes.string, PropTypes.node]),
value: PropTypes.any // initial field value
};
var defaultCache = {};
var defaultProps = {
autoload: true,
cache: defaultCache,
children: defaultChildren,
ignoreAccents: true,
ignoreCase: true,
loadingPlaceholder: 'Loading...',
options: [],
searchPromptText: 'Type to search'
};
var Async = function (_Component) {
inherits(Async, _Component);
function Async(props, context) {
classCallCheck(this, Async);
var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context));
_this._cache = props.cache === defaultCache ? {} : props.cache;
_this.state = {
inputValue: '',
isLoading: false,
options: props.options
};
_this.onInputChange = _this.onInputChange.bind(_this);
return _this;
}
createClass(Async, [{
key: 'componentDidMount',
value: function componentDidMount() {
var autoload = this.props.autoload;
if (autoload) {
this.loadOptions('');
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.options !== this.props.options) {
this.setState({
options: nextProps.options
});
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._callback = null;
}
}, {
key: 'loadOptions',
value: function loadOptions(inputValue) {
var _this2 = this;
var loadOptions = this.props.loadOptions;
var cache = this._cache;
if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) {
this._callback = null;
this.setState({
isLoading: false,
options: cache[inputValue]
});
return;
}
var callback = function callback(error, data) {
var options = data && data.options || [];
if (cache) {
cache[inputValue] = options;
}
if (callback === _this2._callback) {
_this2._callback = null;
_this2.setState({
isLoading: false,
options: options
});
}
};
// Ignore all but the most recent request
this._callback = callback;
var promise = loadOptions(inputValue, callback);
if (promise) {
promise.then(function (data) {
return callback(null, data);
}, function (error) {
return callback(error);
});
}
if (this._callback && !this.state.isLoading) {
this.setState({
isLoading: true
});
}
}
}, {
key: 'onInputChange',
value: function onInputChange(inputValue) {
var _props = this.props,
ignoreAccents = _props.ignoreAccents,
ignoreCase = _props.ignoreCase,
onInputChange = _props.onInputChange;
var newInputValue = inputValue;
if (onInputChange) {
var value = onInputChange(newInputValue);
// Note: != used deliberately here to catch undefined and null
if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') {
newInputValue = '' + value;
}
}
var transformedInputValue = newInputValue;
if (ignoreAccents) {
transformedInputValue = stripDiacritics(transformedInputValue);
}
if (ignoreCase) {
transformedInputValue = transformedInputValue.toLowerCase();
}
this.setState({ inputValue: newInputValue });
this.loadOptions(transformedInputValue);
// Return new input value, but without applying toLowerCase() to avoid modifying the user's view case of the input while typing.
return newInputValue;
}
}, {
key: 'noResultsText',
value: function noResultsText() {
var _props2 = this.props,
loadingPlaceholder = _props2.loadingPlaceholder,
noResultsText = _props2.noResultsText,
searchPromptText = _props2.searchPromptText;
var _state = this.state,
inputValue = _state.inputValue,
isLoading = _state.isLoading;
if (isLoading) {
return loadingPlaceholder;
}
if (inputValue && noResultsText) {
return noResultsText;
}
return searchPromptText;
}
}, {
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props,
children = _props3.children,
loadingPlaceholder = _props3.loadingPlaceholder,
multi = _props3.multi,
onChange = _props3.onChange,
placeholder = _props3.placeholder;
var _state2 = this.state,
isLoading = _state2.isLoading,
options = _state2.options;
var props = {
noResultsText: this.noResultsText(),
placeholder: isLoading ? loadingPlaceholder : placeholder,
options: isLoading && loadingPlaceholder ? [] : options,
ref: function ref(_ref) {
return _this3.select = _ref;
}
};
return children(_extends({}, this.props, props, {
isLoading: isLoading,
onInputChange: this.onInputChange
}));
}
}]);
return Async;
}(Component);
Async.propTypes = propTypes;
Async.defaultProps = defaultProps;
function defaultChildren(props) {
return React.createElement(Select$1, props);
}
var CreatableSelect = function (_React$Component) {
inherits(CreatableSelect, _React$Component);
function CreatableSelect(props, context) {
classCallCheck(this, CreatableSelect);
var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context));
_this.filterOptions = _this.filterOptions.bind(_this);
_this.menuRenderer = _this.menuRenderer.bind(_this);
_this.onInputKeyDown = _this.onInputKeyDown.bind(_this);
_this.onInputChange = _this.onInputChange.bind(_this);
_this.onOptionSelect = _this.onOptionSelect.bind(_this);
return _this;
}
createClass(CreatableSelect, [{
key: 'createNewOption',
value: function createNewOption() {
var _props = this.props,
isValidNewOption = _props.isValidNewOption,
newOptionCreator = _props.newOptionCreator,
onNewOptionClick = _props.onNewOptionClick,
_props$options = _props.options,
options = _props$options === undefined ? [] : _props$options;
if (isValidNewOption({ label: this.inputValue })) {
var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
var _isOptionUnique = this.isOptionUnique({ option: option });
// Don't add the same option twice.
if (_isOptionUnique) {
if (onNewOptionClick) {
onNewOptionClick(option);
} else {
options.unshift(option);
this.select.selectValue(option);
}
}
}
}
}, {
key: 'filterOptions',
value: function filterOptions$$1() {
var _props2 = this.props,
filterOptions$$1 = _props2.filterOptions,
isValidNewOption = _props2.isValidNewOption,
options = _props2.options,
promptTextCreator = _props2.promptTextCreator;
// TRICKY Check currently selected options as well.
// Don't display a create-prompt for a value that's selected.
// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || [];
var filteredOptions = filterOptions$$1.apply(undefined, arguments) || [];
if (isValidNewOption({ label: this.inputValue })) {
var _newOptionCreator = this.props.newOptionCreator;
var option = _newOptionCreator({
label: this.inputValue,
labelKey: this.labelKey,
valueKey: this.valueKey
});
// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
// For multi-selects, this would remove it from the filtered list.
var _isOptionUnique2 = this.isOptionUnique({
option: option,
options: excludeOptions.concat(filteredOptions)
});
if (_isOptionUnique2) {
var prompt = promptTextCreator(this.inputValue);
this._createPlaceholderOption = _newOptionCreator({
label: prompt,
labelKey: this.labelKey,
valueKey: this.valueKey
});
filteredOptions.unshift(this._createPlaceholderOption);
}
}
return filteredOptions;
}
}, {
key: 'isOptionUnique',
value: function isOptionUnique(_ref) {
var option = _ref.option,
options = _ref.options;
var isOptionUnique = this.props.isOptionUnique;
options = options || this.props.options;
return isOptionUnique({
labelKey: this.labelKey,
option: option,
options: options,
valueKey: this.valueKey
});
}
}, {
key: 'menuRenderer',
value: function menuRenderer$$1(params) {
var menuRenderer$$1 = this.props.menuRenderer;
return menuRenderer$$1(_extends({}, params, {
onSelect: this.onOptionSelect,
selectValue: this.onOptionSelect
}));
}
}, {
key: 'onInputChange',
value: function onInputChange(input) {
var onInputChange = this.props.onInputChange;
// This value may be needed in between Select mounts (when this.select is null)
this.inputValue = input;
if (onInputChange) {
this.inputValue = onInputChange(input);
}
return this.inputValue;
}
}, {
key: 'onInputKeyDown',
value: function onInputKeyDown(event) {
var _props3 = this.props,
shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption,
onInputKeyDown = _props3.onInputKeyDown;
var focusedOption = this.select.getFocusedOption();
if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) {
this.createNewOption();
// Prevent decorated Select from doing anything additional with this keyDown event
event.preventDefault();
} else if (onInputKeyDown) {
onInputKeyDown(event);
}
}
}, {
key: 'onOptionSelect',
value: function onOptionSelect(option, event) {
if (option === this._createPlaceholderOption) {
this.createNewOption();
} else {
this.select.selectValue(option);
}
}
}, {
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props4 = this.props,
newOptionCreator = _props4.newOptionCreator,
shouldKeyDownEventCreateNewOption = _props4.shouldKeyDownEventCreateNewOption,
refProp = _props4.ref,
restProps = objectWithoutProperties(_props4, ['newOptionCreator', 'shouldKeyDownEventCreateNewOption', 'ref']);
var children = this.props.children;
// We can't use destructuring default values to set the children,
// because it won't apply work if `children` is null. A falsy check is
// more reliable in real world use-cases.
if (!children) {
children = defaultChildren$2;
}
var props = _extends({}, restProps, {
allowCreate: true,
filterOptions: this.filterOptions,
menuRenderer: this.menuRenderer,
onInputChange: this.onInputChange,
onInputKeyDown: this.onInputKeyDown,
ref: function ref(_ref2) {
_this2.select = _ref2;
// These values may be needed in between Select mounts (when this.select is null)
if (_ref2) {
_this2.labelKey = _ref2.props.labelKey;
_this2.valueKey = _ref2.props.valueKey;
}
if (refProp) {
refProp(_ref2);
}
}
});
return children(props);
}
}]);
return CreatableSelect;
}(React.Component);
function defaultChildren$2(props) {
return React.createElement(Select$1, props);
}
function isOptionUnique(_ref3) {
var option = _ref3.option,
options = _ref3.options,
labelKey = _ref3.labelKey,
valueKey = _ref3.valueKey;
return options.filter(function (existingOption) {
return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey];
}).length === 0;
}
function isValidNewOption(_ref4) {
var label = _ref4.label;
return !!label;
}
function newOptionCreator(_ref5) {
var label = _ref5.label,
labelKey = _ref5.labelKey,
valueKey = _ref5.valueKey;
var option = {};
option[valueKey] = label;
option[labelKey] = label;
option.className = 'Select-create-option-placeholder';
return option;
}
function promptTextCreator(label) {
return 'Create option "' + label + '"';
}
function shouldKeyDownEventCreateNewOption(_ref6) {
var keyCode = _ref6.keyCode;
switch (keyCode) {
case 9: // TAB
case 13: // ENTER
case 188:
// COMMA
return true;
}
return false;
}
// Default prop methods
CreatableSelect.isOptionUnique = isOptionUnique;
CreatableSelect.isValidNewOption = isValidNewOption;
CreatableSelect.newOptionCreator = newOptionCreator;
CreatableSelect.promptTextCreator = promptTextCreator;
CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption;
CreatableSelect.defaultProps = {
filterOptions: filterOptions,
isOptionUnique: isOptionUnique,
isValidNewOption: isValidNewOption,
menuRenderer: menuRenderer,
newOptionCreator: newOptionCreator,
promptTextCreator: promptTextCreator,
shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption
};
CreatableSelect.propTypes = {
// Child function responsible for creating the inner Select component
// This component can be used to compose HOCs (eg Creatable and Async)
// (props: Object): PropTypes.element
children: PropTypes.func,
// See Select.propTypes.filterOptions
filterOptions: PropTypes.any,
// Searches for any matching option within the set of options.
// This function prevents duplicate options from being created.
// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isOptionUnique: PropTypes.func,
// Determines if the current input text represents a valid option.
// ({ label: string }): boolean
isValidNewOption: PropTypes.func,
// See Select.propTypes.menuRenderer
menuRenderer: PropTypes.any,
// Factory to create new option.
// ({ label: string, labelKey: string, valueKey: string }): Object
newOptionCreator: PropTypes.func,
// input change handler: function (inputValue) {}
onInputChange: PropTypes.func,
// input keyDown handler: function (event) {}
onInputKeyDown: PropTypes.func,
// new option click handler: function (option) {}
onNewOptionClick: PropTypes.func,
// See Select.propTypes.options
options: PropTypes.array,
// Creates prompt/placeholder option text.
// (filterText: string): string
promptTextCreator: PropTypes.func,
ref: PropTypes.func,
// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
shouldKeyDownEventCreateNewOption: PropTypes.func
};
var AsyncCreatableSelect = function (_React$Component) {
inherits(AsyncCreatableSelect, _React$Component);
function AsyncCreatableSelect() {
classCallCheck(this, AsyncCreatableSelect);
return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments));
}
createClass(AsyncCreatableSelect, [{
key: 'focus',
value: function focus() {
this.select.focus();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return React.createElement(
Async,
this.props,
function (_ref) {
var ref = _ref.ref,
asyncProps = objectWithoutProperties(_ref, ['ref']);
var asyncRef = ref;
return React.createElement(
CreatableSelect,
asyncProps,
function (_ref2) {
var ref = _ref2.ref,
creatableProps = objectWithoutProperties(_ref2, ['ref']);
var creatableRef = ref;
return _this2.props.children(_extends({}, creatableProps, {
ref: function ref(select) {
creatableRef(select);
asyncRef(select);
_this2.select = select;
}
}));
}
);
}
);
}
}]);
return AsyncCreatableSelect;
}(React.Component);
function defaultChildren$1(props) {
return React.createElement(Select$1, props);
}
AsyncCreatableSelect.propTypes = {
children: PropTypes.func.isRequired // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element
};
AsyncCreatableSelect.defaultProps = {
children: defaultChildren$1
};
Select$1.Async = Async;
Select$1.AsyncCreatable = AsyncCreatableSelect;
Select$1.Creatable = CreatableSelect;
Select$1.Value = Value;
Select$1.Option = Option;
export { Async, AsyncCreatableSelect as AsyncCreatable, CreatableSelect as Creatable, Value, Option, menuRenderer as defaultMenuRenderer, arrowRenderer as defaultArrowRenderer, clearRenderer as defaultClearRenderer, filterOptions as defaultFilterOptions };
export default Select$1;
|
webpack/scenes/AnsibleCollections/AnsibleCollectionsPage.js | snagoor/katello | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import qs from 'query-string';
import { translate as __ } from 'foremanReact/common/I18n';
import { orgId } from '../../services/api';
import TableSchema from './AnsibleCollectionsTableSchema';
import ContentPage from '../../components/Content/ContentPage';
class AnsibleCollectionsPage extends Component {
constructor(props) {
super(props);
const queryParams = qs.parse(this.props.location.search);
this.state = {
searchQuery: queryParams.search || '',
};
}
componentDidMount() {
this.props.getAnsibleCollections({
search: this.state.searchQuery,
});
}
onPaginationChange = (pagination) => {
this.props.getAnsibleCollections({
...pagination,
});
};
onSearch = (search) => {
this.props.getAnsibleCollections({ search });
};
getAutoCompleteParams = search => ({
endpoint: '/ansible_collections/auto_complete_search',
params: {
organization_id: orgId(),
search,
},
});
updateSearchQuery = (searchQuery) => {
this.setState({ searchQuery });
};
render() {
const { ansibleCollections } = this.props;
return (
<ContentPage
header={__('Ansible Collections')}
content={ansibleCollections}
tableSchema={TableSchema}
onSearch={this.onSearch}
getAutoCompleteParams={this.getAutoCompleteParams}
updateSearchQuery={this.updateSearchQuery}
initialInputValue={this.state.searchQuery}
onPaginationChange={this.onPaginationChange}
/>
);
}
}
AnsibleCollectionsPage.propTypes = {
location: PropTypes.shape({
search: PropTypes.oneOfType([
PropTypes.shape({}),
PropTypes.string,
]),
}),
getAnsibleCollections: PropTypes.func.isRequired,
ansibleCollections: PropTypes.shape({}).isRequired,
};
AnsibleCollectionsPage.defaultProps = {
location: { search: '' },
};
export default AnsibleCollectionsPage;
|
static-assets/js/libs/jquery-1.6.2.min.js | vestrada/studio-ui | /*!
* jQuery JavaScript Library v1.6.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: Thu Jun 30 14:16:56 2011 -0400
*/
(function(a,b){function cv(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cs(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 cr(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cq(){cn=b}function cp(){setTimeout(cq,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||bC.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,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===bR,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=bX(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bX(a,c,d,e,"*",g));return l}function bW(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bN),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 bA(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bv:bw;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=bx(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 bm(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(be,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bl(a){f.nodeName(a,"input")?bk(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bk)}function bk(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bj(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bi(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 bh(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 bg(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(a,b){return(a&&a!=="*"?a+".":"")+b.replace(z,"`").replace(A,"&")}function M(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(x,"")===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 K(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 E(){return!0}function D(){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-$2").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 J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\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])/ig,x=function(a,b){return b.toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=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.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.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(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!A){A=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||D.call(a,c)},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(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(H)return H.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=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=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){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g="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](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},m&&f.extend(p,{position:"absolute",left:-1e3,top:-1e3});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])([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=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]||i[c]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[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=/\:|^on/,v,w;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].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=w:v&&c!=="className"&&(f.nodeName(a,"form")||u.test(c))&&(i=v)));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.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(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}}},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}},value:{get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.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))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return f.prop(a,c)?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||(f.attrFix=f.propFix,v=f.attrHooks.name=f.attrHooks.title=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return 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)}})),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 x=/\.(.*)$/,y=/^(?:textarea|input|select)$/i,z=/\./g,A=/ /g,B=/[^\w\s.|`]/g,C=function(a){return a.replace(B,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=D;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=D);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(),C).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,N(a.origType,a.selector),f.extend({},a,{handler:M,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,N(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()?E:D):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=E;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=E;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=E,this.stopPropagation()},isDefaultPrevented:D,isPropagationStopped:D,isImmediatePropagationStopped:D};var F=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))},G=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?G:F,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?G:F)}}}),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=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&K("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&K("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var H,I=function(a){var b=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},J=function(c){var d=c.target,e,g;if(!!y.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=I(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:J,beforedeactivate:J,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&J.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")&&J.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",I(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in H)f.event.add(this,c+".specialChange",H[c]);return y.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return y.test(this.nodeName)}},H=f.event.special.change.filters,H.focus=H.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 L={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||D,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=x.exec(h),k="",j&&(k=j[0],h=h.replace(x,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,L[h]?(a.push(L[h]+k),h=h+k):h=(L[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+N(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+N(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 O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?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]=T.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=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(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||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var X=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,Z=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,$=/<([\w:]+)/,_=/<tbody/i,ba=/<|&#?\w+;/,bb=/<(?:script|object|embed|option|style)/i,bc=/checked\s*(?:[^=]|=\s*.checked.)/i,bd=/\/(java|ecma)script/i,be=/^\s*<!(?:\[CDATA\[|\-\-)/,bf={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,"",""]};bf.optgroup=bf.option,bf.tbody=bf.tfoot=bf.colgroup=bf.caption=bf.thead,bf.th=bf.td,f.support.htmlSerialize||(bf._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(X,""):null;if(typeof a=="string"&&!bb.test(a)&&(f.support.leadingWhitespace||!Y.test(a))&&!bf[($.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Z,"<$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"&&bc.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?bg(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bm)}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)==="<"&&!bb.test(a[0])&&(f.support.checkClone||!bc.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)){bi(a,d),e=bj(a),g=bj(d);for(h=0;e[h];++h)bi(e[h],g[h])}if(b){bh(a,d);if(c){e=bj(a),g=bj(d);for(h=0;e[h];++h)bh(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(!ba.test(k))k=b.createTextNode(k);else{k=k.replace(Z,"<$1></$2>");var l=($.exec(k)||["",""])[1].toLowerCase(),m=bf[l]||bf._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&&Y.test(k)&&o.insertBefore(b.createTextNode(Y.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++)bl(k[i]);else bl(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bd.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 bn=/alpha\([^)]*\)/i,bo=/opacity=([^)]*)/,bp=/([A-Z]|^ms)/g,bq=/^-?\d+(?:px)?$/i,br=/^-?\d/,bs=/^[+\-]=/,bt=/[^+\-\.\de]+/g,bu={position:"absolute",visibility:"hidden",display:"block"},bv=["Left","Right"],bw=["Top","Bottom"],bx,by,bz;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=bx(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;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bs.test(d)&&(d=+d.replace(bt,"")+parseFloat(f.css(a,c)),h="number"),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(bx)return bx(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 bA(a,b,d);f.swap(a,bu,function(){e=bA(a,b,d)});return e}},set:function(a,b){if(!bq.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bo.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;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bn.test(g)?g.replace(bn,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=bx(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(by=function(a,c){var d,e,g;c=c.replace(bp,"-$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&&(bz=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bq.test(d)&&br.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}),bx=by||bz,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 bB=/%20/g,bC=/\[\]$/,bD=/\r?\n/g,bE=/#.*$/,bF=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bG=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bH=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bI=/^(?:GET|HEAD)$/,bJ=/^\/\//,bK=/\?/,bL=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bM=/^(?:select|textarea)/i,bN=/\s+/,bO=/([?&])_=[^&]*/,bP=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bQ=f.fn.load,bR={},bS={},bT,bU;try{bT=e.href}catch(bV){bT=c.createElement("a"),bT.href="",bT=bT.href}bU=bP.exec(bT.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bQ)return bQ.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(bL,"")).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||bM.test(this.nodeName)||bG.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(bD,"\r\n")}}):{name:b.name,value:c.replace(bD,"\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?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bT,isLocal:bH.test(bU[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","*":"*/*"},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}},ajaxPrefilter:bW(bR),ajaxTransport:bW(bS),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?4:0;var o,r,u,w=l?bZ(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=b$(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),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=bF.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(bE,"").replace(bJ,bU[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bN),d.crossDomain==null&&(r=bP.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bU[1]&&r[2]==bU[2]&&(r[3]||(r[1]==="http:"?80:443))==(bU[3]||(bU[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bX(bR,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bI.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bK.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bO,"$1_="+x);d.url=y+(y===d.url?(bK.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]!=="*"?", */*; 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=bX(bS,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){status<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(bB,"+")}}),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,co=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cr("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",cs(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(cr("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(cr("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=cs(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:cr("show",1),slideUp:cr("hide",1),slideToggle:cr("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 h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cn||cp(),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,h.elem=this.elem,h()&&f.timers.push(h)&&!cl&&(co?(cl=!0,g=function(){cl&&(co(g),e.tick())},co(g)):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||cp(),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 ct=/^t(?:able|d|h)$/i,cu=/^(?: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=cv(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||!ct.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=cu.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&&!cu.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=cv(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=cv(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];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["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 h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); |
src/@ui/Header/index.js | NewSpring/Apollos | import React from 'react';
import { View, StatusBar, Platform } from 'react-native';
import SafeAreaView from '@ui/SafeAreaView';
import PropTypes from 'prop-types';
import { compose, setPropTypes, pure, branch, renderNothing, defaultProps } from 'recompose';
import { withTheme, withThemeMixin } from '@ui/theme';
import styled from '@ui/styled';
import { H2, H6 } from '@ui/typography';
import BackButton from './BackButton';
const StyledHeaderBar = styled(
({ theme }) => ({
height: 50,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: theme.sizing.baseUnit / 2,
...Platform.select({
web: {
height: undefined,
paddingHorizontal: theme.sizing.baseUnit,
paddingVertical: theme.sizing.baseUnit,
paddingTop: theme.sizing.baseUnit * 2.5,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
},
}),
}),
'Header.Bar',
)(View);
const HeaderContainer = styled(
({ theme, backgroundColor }) => ({
backgroundColor: backgroundColor || theme.colors.background.primary,
...Platform.select({
android: {
paddingTop: 25, // todo: this is currently required as SafeAreaView isn't
// properly adding padding on android.
},
web: {
backgroundColor: theme.colors.background.paper,
},
}),
}),
'Header.Container',
)(SafeAreaView);
const WebHeaderText = styled(
({ theme }) => ({
color: theme.colors.darkSecondary,
}),
'Header.WebHeaderText',
)(H2);
const StyledHeaderText =
Platform.OS === 'web'
? WebHeaderText
: styled(
({ theme, barStyle }) => ({
color: barStyle === 'dark-content' ? theme.colors.darkPrimary : theme.colors.lightPrimary,
maxWidth: '80%',
}),
'Header.Text',
)(H6);
const RightContainer = styled(
({ theme }) => ({
position: 'absolute',
right: 4,
top: 0,
bottom: 0,
justifyContent: 'center',
...Platform.select({
web: {
right: theme.sizing.baseUnit,
top: theme.sizing.baseUnit,
justifyContent: 'flex-start',
},
}),
}),
'Header.RightContainer',
)(View);
const ColoredBackButton = compose(
pure,
withTheme(({ theme, barstyle }) => ({
color: barstyle === 'dark-content' ? theme.colors.darkPrimary : undefined,
})),
)(BackButton);
const enhance = compose(
defaultProps({
backButton: false,
barStyle: 'light-content',
children: null,
}),
setPropTypes({
webEnabled: PropTypes.bool,
titleText: PropTypes.string,
backButton: PropTypes.bool,
barStyle: PropTypes.oneOf(['light-content', 'dark-content']),
children: PropTypes.node,
}),
branch(({ webEnabled }) => !webEnabled && Platform.OS === 'web', renderNothing),
branch(
() => Platform.OS !== 'web',
withThemeMixin(({ theme, barStyle }) => ({
type: barStyle === 'light-content' ? 'dark' : 'light',
colors: {
background: {
...theme.colors.background,
default: theme.colors.background.primary,
},
},
})),
),
pure,
);
const Header = enhance(
({
titleText,
right,
backButton = false,
barStyle = 'light-content',
style = {},
backgroundColor = null,
children,
}) => (
<HeaderContainer backgroundColor={backgroundColor} style={style}>
<StatusBar barStyle={barStyle} />
<StyledHeaderBar>
{backButton ? <ColoredBackButton barStyle={barStyle} /> : null}
{titleText ? (
<StyledHeaderText barStyle={barStyle} numberOfLines={1}>
{titleText}
</StyledHeaderText>
) : null}
{children}
{right ? <RightContainer>{right}</RightContainer> : null}
</StyledHeaderBar>
</HeaderContainer>
),
);
export default Header;
|
ajax/libs/material-ui/4.9.3/es/SwipeableDrawer/SwipeArea.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import { isHorizontal } from '../Drawer/Drawer';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
zIndex: theme.zIndex.drawer - 1
},
anchorLeft: {
right: 'auto'
},
anchorRight: {
left: 'auto',
right: 0
},
anchorTop: {
bottom: 'auto',
right: 0
},
anchorBottom: {
top: 'auto',
bottom: 0,
right: 0
}
});
/**
* @ignore - internal component.
*/
const SwipeArea = React.forwardRef(function SwipeArea(props, ref) {
const {
anchor,
classes,
className,
width
} = props,
other = _objectWithoutPropertiesLoose(props, ["anchor", "classes", "className", "width"]);
return React.createElement("div", _extends({
className: clsx(classes.root, classes[`anchor${capitalize(anchor)}`], className),
ref: ref,
style: {
[isHorizontal(anchor) ? 'width' : 'height']: width
}
}, other));
});
process.env.NODE_ENV !== "production" ? SwipeArea.propTypes = {
/**
* Side on which to attach the discovery area.
*/
anchor: PropTypes.oneOf(['left', 'top', 'right', 'bottom']).isRequired,
/**
* @ignore
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The width of the left most (or right most) area in pixels where the
* drawer can be swiped open from.
*/
width: PropTypes.number.isRequired
} : void 0;
export default withStyles(styles, {
name: 'PrivateSwipeArea'
})(SwipeArea); |
bin/ISOServer.js | tianyingchun/docs | import path from 'path';
import express from 'express';
import cors from 'cors';
import favicon from 'serve-favicon';
import execTime from 'exec-time';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { Provider } from 'react-redux';
import { RoutingContext, match } from 'react-router';
import createLocation from 'history/lib/createLocation'
import configureStore from '../docs/app/configureStore';
import HtmlHead from '../docs/components/HtmlHead';
import fetchComponentData from '../utils/fetchComponentData';
import getRenderParams from '../utils/getISORenderParams';
import compression from 'compression';
import { minify } from 'html-minifier';
const app = express();
const NODE_ENV = app.get('env') || 'production';
const port = process.env.PORT || 20000;
const profiler = new execTime('[ISO]', NODE_ENV === 'development', 'ms');
// compress all requests
app.use(compression());
app.use(favicon(path.join(__dirname, '../public/favicon.ico')));
// Use this middleware to serve up static files built into the dist directory, milliseconds
app.use("/public", cors(), express.static(path.join(__dirname, '../public'), { maxAge: '30 days'}));
app.use("/shared", cors(), express.static(path.join(__dirname, '../shared'), { maxAge: '30 days'}));
// This is fired every time the server side receives a request
app.use(handleRender);
// We are going to fill these out in the sections to follow
function handleRender(req, res) {
// Resolve current server rendering params.
let { project, routes, jsBundles, cssBundles } = getRenderParams(req, NODE_ENV);
if (!routes || !project) {
console.log('router match failed in build.config.js, 404 not found!');
// should give 404.
res.status(404).send('Not found');
return;
}
// default is web.
let store = configureStore(project.subProjectName);
console.log('projectName %s, sub projectName: %s', project.projectName, project.subProjectName);
let location = createLocation(req.url);
// start profileing.
profiler.beginProfiling();
match({ routes: routes(), location: location }, (error, redirectLocation, renderProps) => {
profiler.step('React-Router');
if (redirectLocation){
res.redirect(301, redirectLocation.pathname + redirectLocation.search);
return;
}
else if (error){
res.status(500).send(error.message);
return;
}
else if (renderProps == null){
console.log('render props is null while through react-router, 404 not found!');
res.status(404).send('Not found');
return;
}
function renderView() {
profiler.step('fetchComponentData');
const InitialView = (
<Provider store={store}>
{ <RoutingContext {...renderProps} /> }
</Provider>
);
const componentHTML = ReactDOMServer.renderToString(InitialView);
const head = ReactDOMServer.renderToString(React.createFactory(HtmlHead)({ links: cssBundles || [] }));
const initialState = store.getState();
let scriptsHtml = jsBundles.map(function (jsLink) {
return ('<script src="' + jsLink + '"></script>');
}).join('');
const HTML = `
<!DOCTYPE html>
<html>
${head}
<body>
<script>window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};</script>
<div id="react-view">${componentHTML}</div>
${scriptsHtml}
</body>
</html>
`;
profiler.step('renderFullPageHtml');
return minify(HTML, {
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
collapseWhitespace: true
});
}
fetchComponentData(store.dispatch, renderProps.components, renderProps.params)
.then(renderView)
.then(html => res.end(html))
.catch(err => res.end(err.message));
});
}
var server = app.listen(port, function () {
console.log('===Express server listening on port %d ===', server.address().port);
});
|
imports/ui/components/PdfContent/PdfContent.js | muhammadsasmito/meteor-solr | import React from 'react'
const PdfContent = React.createClass({
propTypes: {
result : React.PropTypes.string.isRequired,
},
componentDidMount(){
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var currentPage = 1;
var pages = [];
var url = '//10.9.8.104/pdf/' + this.props.result;
// var url = '//cdn.mozilla.net/pdfjs/tracemonkey.pdf';
// The workerSrc property shall be specified.
PDFJS.workerSrc = '/packages/pascoual_pdfjs/build/pdf.worker.js';
// Asynchronous download of PDF
var loadingTask = PDFJS.getDocument(url);
// console.log(url);
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
function renderPage(page) {
console.log('Page loaded');
var scale = 1.15;
var scaledViewport = page.getViewport(scale);
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.height = scaledViewport.height;
canvas.width = scaledViewport.width;
var renderContext = {
canvasContext: context,
viewport: scaledViewport
};
page.render(renderContext).then(function () {
if(currentPage < pdf.numPages) {
pages[currentPage] = canvas;
currentPage++;
pdf.getPage(currentPage).then(renderPage);
} else {
for (var i = 1; i < pages.length; i++) {
document.getElementById('pdfcanvas').appendChild(pages[i]);
}
}
});
}
// Render the fetched first page
pdf.getPage(currentPage).then(renderPage);
}, function (reason) {
// PDF loading error
console.error(reason);
});
},
render(){
return (
<div id="pdfcanvas" className="pdfcanvas"></div>
)
}
});
export default PdfContent; |
client/views/notFound/NotFoundPage.js | Sing-Li/Rocket.Chat | import { Box, Button, ButtonGroup, Flex, Margins } from '@rocket.chat/fuselage';
import React from 'react';
import ConnectionStatusAlert from '../../components/connectionStatus/ConnectionStatusAlert';
import { useRoute } from '../../contexts/RouterContext';
import { useTranslation } from '../../contexts/TranslationContext';
import { useWipeInitialPageLoading } from '../../hooks/useWipeInitialPageLoading';
function NotFoundPage() {
useWipeInitialPageLoading();
const t = useTranslation();
const homeRoute = useRoute('home');
const handleGoToPreviousPageClick = () => {
window.history.back();
};
const handleGoHomeClick = () => {
homeRoute.push();
};
return <>
<ConnectionStatusAlert />
<Flex.Container direction='column' justifyContent='center' alignItems='center'>
<Box is='section' width='full' minHeight='sh' textAlign='center' backgroundColor='neutral-800' style={{
backgroundImage: 'url(\'/images/404.svg\')',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
backgroundSize: 'cover',
}}>
<Flex.Item>
<Box>
<Margins all='x12'>
<Box fontWeight='p2' fontSize='x64' color='alternative'>404</Box>
<Box fontScale='h1' color='alternative'>
{t('Oops_page_not_found')}
</Box>
<Box fontScale='p1' color='alternative'>
{t('Sorry_page_you_requested_does_not_exist_or_was_deleted')}
</Box>
</Margins>
<ButtonGroup align='center' margin='x64'>
<Button type='button' primary onClick={handleGoToPreviousPageClick}>{t('Return_to_previous_page')}</Button>
<Button type='button' primary onClick={handleGoHomeClick}>{t('Return_to_home')}</Button>
</ButtonGroup>
</Box>
</Flex.Item>
</Box>
</Flex.Container>
</>;
}
export default NotFoundPage;
|
src/components/Youtube.js | cape-io/innova | import React, { Component, PropTypes } from 'react'
import Video from './Video'
class Youtube extends Component {
// innova channelId UC1dLyBjCAFz9tNxEr47zIEA
// ACF UUEC1Deur1BSCtznxH3nP2WQ
componentDidMount() {
this.props.fetchItems({
playlistId: 'UU1dLyBjCAFz9tNxEr47zIEA',
key: 'AIzaSyDu7__FOqyJTEPC68dW_Oq-hwRySPZGpDI',
maxResults: '3',
})
}
render() {
const { items, isFetching } = this.props
const headerMsg = 'Loading videos...'
return (
<div>
{ isFetching ? <h3>{headerMsg}</h3> : false }
{ items.map(item => <Video {...item} key={item.videoId} />) }
</div>
)
}
}
Youtube.propTypes = {
items: PropTypes.array.isRequired,
fetchItems: PropTypes.func.isRequired,
isFetching: PropTypes.bool.isRequired,
}
Youtube.defaultProps = {}
export default Youtube
|
ajax/libs/jquery/1.8.3/jquery.js | gokuale/cdnjs | /*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
ajax/libs/rxjs/2.2.27/rx.all.compat.js | wackyapples/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
function isFunction(value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == 'function' && toString.call(value) == funcClass;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Collections
var IndexedItem = function (id, value) {
this.id = id;
this.value = value;
};
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
if (c === 0) {
c = this.id - other.id;
}
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) {
return;
}
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) {
return;
}
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
if (index === undefined) {
index = 0;
}
if (index >= this.length || index < 0) {
return;
}
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable.
*/
CompositeDisposablePrototype.clear = function () {
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
};
/**
* Determines whether the CompositeDisposable contains a specific disposable.
* @param {Mixed} item Disposable to search for.
* @returns {Boolean} true if the disposable was found; otherwise, false.
*/
CompositeDisposablePrototype.contains = function (item) {
return this.disposables.indexOf(item) !== -1;
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var BooleanDisposable = (function () {
function BooleanDisposable (isSingle) {
this.isSingle = isSingle;
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
if (this.current && this.isSingle) {
throw new Error('Disposable has already been assigned');
}
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
if (old) {
old.dispose();
}
if (shouldDispose && value) {
value.dispose();
}
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
if (old) {
old.dispose();
}
};
return BooleanDisposable;
}());
/**
* Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
* If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error.
*/
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) {
inherits(SingleAssignmentDisposable, super_);
function SingleAssignmentDisposable() {
super_.call(this, true);
}
return SingleAssignmentDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
*/
var SerialDisposable = Rx.SerialDisposable = (function (super_) {
inherits(SerialDisposable, super_);
function SerialDisposable() {
super_.call(this, false);
}
return SerialDisposable;
}(BooleanDisposable));
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
/**
* @constructor
* @private
*/
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchException = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, function () {
action();
});
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodicWithState = function (state, period, action) {
var s = state, id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () {
self(_action);
});
});
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, function (s, p) {
return invokeRecImmediate(s, p);
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) {
_action(function (dt) {
self(_action, dt);
});
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
if (timeSpan < 0) {
timeSpan = 0;
}
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt),
t;
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return queue === null; };
currentScheduler.ensureTrampoline = function (action) {
if (queue === null) {
return this.schedule(action);
} else {
return action();
}
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return setTimeout(action, 0); };
clearMethod = clearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = setTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
clearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @private */
var CatchScheduler = (function (_super) {
function localNow() {
return this._scheduler.now();
}
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, _super);
/** @private */
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
/** @private */
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
/** @private */
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
/** @private */
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
/** @private */
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
var NotificationPrototype = Notification.prototype;
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) {
if (arguments.length === 1 && typeof observerOrOnNext === 'object') {
return this._acceptObservable(observerOrOnNext);
}
return this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notification
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
NotificationPrototype.toObservable = function (scheduler) {
var notification = this;
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
if (notification.kind === 'N') {
observer.onCompleted();
}
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) {
return onNext(this.value);
}
function _acceptObservable(observer) {
return observer.onNext(this.value);
}
function toString () {
return 'OnNext(' + this.value + ')';
}
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) {
return onError(this.exception);
}
function _acceptObservable(observer) {
return observer.onError(this.exception);
}
function toString () {
return 'OnError(' + this.exception + ')';
}
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) {
return onCompleted();
}
function _acceptObservable(observer) {
return observer.onCompleted();
}
function toString () {
return 'OnCompleted()';
}
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) {
inherits(ScheduledObserver, _super);
function ScheduledObserver(scheduler, observer) {
_super.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/** @private */
var ObserveOnObserver = (function (_super) {
inherits(ObserveOnObserver, _super);
/** @private */
function ObserveOnObserver() {
_super.apply(this, arguments);
}
/** @private */
ObserveOnObserver.prototype.next = function (value) {
_super.prototype.next.call(this, value);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.error = function (e) {
_super.prototype.error.call(this, e);
this.ensureActive();
};
/** @private */
ObserveOnObserver.prototype.completed = function () {
_super.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0;
return scheduler.scheduleRecursive(function (self) {
if (count < array.length) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an iterable into an Observable sequence
*
* @example
* var res = Rx.Observable.fromIterable(new Map());
* var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence.
*/
Observable.fromIterable = function (iterable, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var iterator;
try {
iterator = iterable[$iterator$]();
} catch (e) {
observer.onError(e);
return;
}
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = iterator.next();
} catch (err) {
observer.onError(err);
return;
}
if (next.done) {
observer.onCompleted();
} else {
observer.onNext(next.value);
self();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
if (repeatCount == null) {
repeatCount = -1;
}
return observableReturn(value, scheduler).repeat(repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwException' for browsers <IE9.
*
* @example
* var res = Rx.Observable.throwException(new Error('Error'));
* var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout);
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) {
scheduler || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
if (resource) {
disposable = resource;
}
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') {
return observableMerge(this, maxConcurrentOrOther);
}
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0,
group = new CompositeDisposable(),
isStopped = false,
q = [],
subscribe = function (xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
var s;
group.remove(subscription);
if (q.length > 0) {
s = q.shift();
subscribe(s);
} else {
activeCount--;
if (isStopped && activeCount === 0) {
observer.onCompleted();
}
}
}));
};
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, observer.onError.bind(observer), function () {
isStopped = true;
if (activeCount === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
innerSubscription.setDisposable(innerSource.subscribe(function (x) {
observer.onNext(x);
}, observer.onError.bind(observer), function () {
group.remove(innerSubscription);
if (isStopped && group.length === 1) { observer.onCompleted(); }
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (group.length === 1) { observer.onCompleted(); }
}));
return group;
});
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) {
throw new Error('Second observable is required');
}
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () {
self();
}, function () {
self();
}));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
d.setDisposable(innerSource.subscribe(function (x) {
if (latest === id) {
observer.onNext(x);
}
}, function (e) {
if (latest === id) {
observer.onError(e);
}
}, function () {
if (latest === id) {
hasLatest = false;
if (isStopped) {
observer.onCompleted();
}
}
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
if (!hasLatest) {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(observer);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.doAction(observer);
* var res = observable.doAction(onNext);
* var res = observable.doAction(onNext, onError);
* var res = observable.doAction(onNext, onError, onCompleted);
* @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (exception) {
if (!onError) {
observer.onError(exception);
} else {
try {
onError(exception);
} catch (e) {
observer.onError(e);
}
observer.onError(exception);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(42);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
try {
if (!hasValue) {
hasValue = true;
}
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
if (!hasValue && hasSeed) {
observer.onNext(seed);
}
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
observer.onNext(q.shift());
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
*
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
*
* @memberOf Observable#
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && 'now' in Object(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue.
*
* @example
* var res = source.takeLast(5);
* var res = source.takeLast(5, Rx.Scheduler.timeout);
*
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count, scheduler) {
return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); });
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
if (q.length > count) {
q.shift();
}
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
if (count <= 0) {
throw new Error(argumentOutOfRange);
}
if (arguments.length === 1) {
skip = count;
}
if (skip <= 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [],
createWindow = function () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
};
createWindow();
m.setDisposable(source.subscribe(function (x) {
var s;
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
var c = n - count + 1;
if (c >= 0 && c % skip === 0) {
s = q.shift();
s.onCompleted();
}
n++;
if (n % skip === 0) {
createWindow();
}
}, function (exception) {
while (q.length > 0) {
q.shift().onError(exception);
}
observer.onError(exception);
}, function () {
while (q.length > 0) {
q.shift().onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
function concatMap(selector) {
return this.map(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
function concatMapObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return concatMap.call(this, selector);
}
return concatMap.call(this, function () {
return selector;
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, keySerializer) {
var source = this;
keySelector || (keySelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var hashSet = {};
return source.subscribe(function (x) {
var key, serializedKey, otherKey, hasMatch = false;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (exception) {
observer.onError(exception);
return;
}
for (otherKey in hashSet) {
if (serializedKey === otherKey) {
hasMatch = true;
break;
}
}
if (!hasMatch) {
hashSet[serializedKey] = null;
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, keySerializer) {
return this.groupByUntil(keySelector, elementSelector, function () {
return observableNever();
}, keySerializer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) {
var source = this;
elementSelector || (elementSelector = identity);
keySerializer || (keySerializer = defaultKeySerializer);
return new AnonymousObservable(function (observer) {
var map = {},
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w;
try {
key = keySelector(x);
serializedKey = keySerializer(key);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
fireNewMapEntry = false;
try {
writer = map[serializedKey];
if (!writer) {
writer = new Subject();
map[serializedKey] = writer;
fireNewMapEntry = true;
}
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
if (fireNewMapEntry) {
group = new GroupedObservable(key, writer, refCountDisposable);
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(group);
md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
if (serializedKey in map) {
delete map[serializedKey];
writer.onCompleted();
}
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(noop, function (exn) {
for (w in map) {
map[w].onError(exn);
}
observer.onError(exn);
}, function () {
expire();
}));
}
try {
element = elementSelector(x);
} catch (e) {
for (w in map) {
map[w].onError(e);
}
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
for (var w in map) {
map[w].onError(ex);
}
observer.onError(ex);
}, function () {
for (var w in map) {
map[w].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var result;
try {
result = selector.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function selectMany(selector) {
return this.select(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
function selectManyObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.selectMany(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.select(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return selectMany.call(this, selector);
}
return selectMany.call(this, function () {
return selector;
});
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
if (running) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) {
throw new Error(argumentOutOfRange);
}
if (count === 0) {
return observableEmpty(scheduler);
}
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining > 0) {
remaining--;
observer.onNext(x);
if (remaining === 0) {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
*
* @example
* var res = source.takeWhile(function (value) { return value < 10; });
* var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
observableProto.finalValue = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var hasValue = false, value;
return source.subscribe(function (x) {
hasValue = true;
value = x;
}, observer.onError.bind(observer), function () {
if (!hasValue) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (observer) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
observer.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
observer.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) {
list.push(x);
}
}, observer.onError.bind(observer), function () {
observer.onNext(list);
observer.onCompleted();
});
});
}
function firstOnly(x) {
if (x.length === 0) {
throw new Error(sequenceContainsNoElements);
}
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.aggregate(function (acc, x) { return acc + x; });
* 2 - res = source.aggregate(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var seed, hasSeed, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
hasSeed = true;
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.reduce(function (acc, x) { return acc + x; });
* 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0);
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var seed, hasSeed;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @example
* var result = source.any();
* var result = source.any(function (x) { return x > 3; });
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = observableProto.any = function (predicate, thisArg) {
var source = this;
return predicate ?
source.where(predicate, thisArg).any() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Determines whether an observable sequence is empty.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().select(function (b) { return !b; });
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
*
* 1 - res = source.all(function (value) { return value.length > 3; });
* @memberOf Observable#
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = observableProto.all = function (predicate, thisArg) {
return this.where(function (v) {
return !predicate(v);
}, thisArg).any().select(function (b) {
return !b;
});
};
/**
* Determines whether an observable sequence contains a specified element with an optional equality comparer.
* @example
* 1 - res = source.contains(42);
* 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; });
* @param value The value to locate in the source sequence.
* @param {Function} [comparer] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value.
*/
observableProto.contains = function (value, comparer) {
comparer || (comparer = defaultComparer);
return this.where(function (v) {
return comparer(v, value);
}).any();
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).count() :
this.aggregate(0, function (count) {
return count + 1;
});
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @example
* var res = source.sum();
* var res = source.sum(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).sum() :
this.aggregate(0, function (prev, curr) {
return prev + curr;
});
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) {
return comparer(x, y) * -1;
});
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @example
* var res = res = source.average();
* var res = res = source.average(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).average() :
this.scan({
sum: 0,
count: 0
}, function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}).finalValue().select(function (s) {
if (s.count === 0) {
throw new Error('The input sequence was empty');
}
return s.sum / s.count;
});
};
function sequenceEqualArray(first, second, comparer) {
return new AnonymousObservable(function (observer) {
var count = 0, len = second.length;
return first.subscribe(function (value) {
var equal = false;
try {
if (count < len) {
equal = comparer(value, second[count++]);
}
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
}, observer.onError.bind(observer), function () {
observer.onNext(count === len);
observer.onCompleted();
});
});
}
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
if (Array.isArray(second)) {
return sequenceEqualArray(first, second, comparer);
}
return new AnonymousObservable(function (observer) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (doner) {
observer.onNext(false);
observer.onCompleted();
} else {
ql.push(x);
}
}, observer.onError.bind(observer), function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (doner) {
observer.onNext(true);
observer.onCompleted();
}
}
});
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal, v;
if (ql.length > 0) {
v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
observer.onError(exception);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (donel) {
observer.onNext(false);
observer.onCompleted();
} else {
qr.push(x);
}
}, observer.onError.bind(observer), function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (donel) {
observer.onNext(true);
observer.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
});
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var i = index;
return source.subscribe(function (x) {
if (i === 0) {
observer.onNext(x);
observer.onCompleted();
}
i--;
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(argumentOutOfRange));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
observer.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @example
* var res = res = source.single();
* var res = res = source.single(function (x) { return x === 42; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate?
this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue)
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
observer.onNext(x);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = res = source.firstOrDefault();
* var res = res = source.firstOrDefault(function (x) { return x > 3; });
* var res = source.firstOrDefault(function (x) { return x > 3; }, 0);
* var res = source.firstOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @example
* var res = source.last();
* var res = source.last(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = source.lastOrDefault();
* var res = source.lastOrDefault(function (x) { return x > 3; });
* var res = source.lastOrDefault(function (x) { return x > 3; }, 0);
* var res = source.lastOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
return new AnonymousObservable(function (observer) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, x, i, source);
} catch(e) {
observer.onError(e);
return;
}
if (shouldRun) {
observer.onNext(yieldIndex ? i : x);
observer.onCompleted();
} else {
i++;
}
}, observer.onError.bind(observer), function () {
observer.onNext(yieldIndex ? -1 : undefined);
observer.onCompleted();
});
});
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, scheduler, context) {
return observableToAsync(func, scheduler, context)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
*
* @example
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, scheduler, context) {
scheduler || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = immediateScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, scheduler, context, selector) {
scheduler || (scheduler = immediateScheduler);
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
} else {
if (results.length === 1) {
results = results[0];
}
}
observer.onNext(results);
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
});
});
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Node.js specific
if (element.addListener) {
element.addListener(name, handler);
return disposableCreate(function () {
element.removeListener(name, handler);
});
}
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (typeof el.item === 'function' && typeof el.length === 'number') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previous = true;
var subscription =
combineLatestSource(
this.source,
this.subject.distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (results.shouldFire && previous) {
observer.onNext(results.data);
}
if (results.shouldFire && !previous) {
while (q.length > 0) {
observer.onNext(q.shift());
}
previous = true;
} else if (!results.shouldFire && !previous) {
q.push(results.data);
} else if (!results.shouldFire && previous) {
previous = false;
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
this.subject.onNext(false);
return subscription;
}
function PausableBufferedObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.share();
*
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish(null).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareValue(42);
*
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).
refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.replayWhileObserved(3);
* var res = source.replayWhileObserved(3, 500);
* var res = source.replayWhileObserved(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.replayWhileObserved = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, _super);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
_super.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (_super) {
function RemovableDisposable (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, _super);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
_super.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/* @private */
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
/** @private */
var ConnectableObservable = Rx.ConnectableObservable = (function (_super) {
inherits(ConnectableObservable, _super);
/**
* @constructor
* @private
*/
function ConnectableObservable(source, subject) {
var state = {
subject: subject,
source: source.asObservable(),
hasSubscription: false,
subscription: null
};
this.connect = function () {
if (!state.hasSubscription) {
state.hasSubscription = true;
state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () {
state.hasSubscription = false;
}));
}
return state.subscription;
};
function subscribe(observer) {
return state.subject.subscribe(observer);
}
_super.call(this, subscribe);
}
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.connect = function () { return this.connect(); };
/**
* @private
* @memberOf ConnectableObservable
*/
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription = null, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect, subscription;
count++;
shouldConnect = count === 1;
subscription = source.subscribe(observer);
if (shouldConnect) {
connectableSubscription = source.connect();
}
return disposableCreate(function () {
subscription.dispose();
count--;
if (count === 0) {
connectableSubscription.dispose();
}
});
});
};
return ConnectableObservable;
}(Observable));
// Real Dictionary
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647];
var noSuchkey = "no such key";
var duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) {
return candidate === 2;
}
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) {
return false;
}
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) {
return num;
}
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) {
return candidate;
}
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) {
return hash;
}
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) {
throw new Error(noSuchkey);
}
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') {
return stringHashFn(obj);
}
if (typeof obj === 'number') {
return numberHashFn(obj);
}
if (typeof obj === 'boolean') {
return obj === true ? 1 : 0;
}
if (obj instanceof Date) {
return obj.getTime();
}
if (obj.getHashCode) {
return obj.getHashCode();
}
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
} ());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
// Dictionary implementation
var Dictionary = function (capacity, comparer) {
if (capacity < 0) {
throw new Error('out of range')
}
if (capacity > 0) {
this._initialize(capacity);
}
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
};
Dictionary.prototype._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
Dictionary.prototype.count = function () {
return this.size;
};
Dictionary.prototype.add = function (key, value) {
return this._insert(key, value, true);
};
Dictionary.prototype._insert = function (key, value, add) {
if (!this.buckets) {
this._initialize(0);
}
var index3;
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) {
throw new Error(duplicatekey);
}
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
Dictionary.prototype._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) {
numArray[index] = -1;
}
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) {
entryArray[index] = this.entries[index];
}
for (var index = this.size; index < prime; ++index) {
entryArray[index] = newEntry();
}
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
Dictionary.prototype.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
var index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
Dictionary.prototype.clear = function () {
var index, len;
if (this.size <= 0) {
return;
}
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
Dictionary.prototype._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
Dictionary.prototype.count = function () {
return this.size - this.freeCount;
};
Dictionary.prototype.tryGetValue = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
return undefined;
};
Dictionary.prototype.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
Dictionary.prototype.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
throw new Error(noSuchkey);
};
Dictionary.prototype.set = function (key, value) {
this._insert(key, value, false);
};
Dictionary.prototype.containskey = function (key) {
return this._findEntry(key) >= 0;
};
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
leftDone = false,
leftId = 0,
leftMap = new Dictionary(),
rightDone = false,
rightId = 0,
rightMap = new Dictionary();
group.add(left.subscribe(function (value) {
var duration,
expire,
id = leftId++,
md = new SingleAssignmentDisposable(),
result,
values;
leftMap.add(id, value);
group.add(md);
expire = function () {
if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) {
observer.onCompleted();
}
return group.remove(md);
};
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); }));
values = rightMap.getValues();
for (var i = 0; i < values.length; i++) {
try {
result = resultSelector(value, values[i]);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}
}, observer.onError.bind(observer), function () {
leftDone = true;
if (rightDone || leftMap.count() === 0) {
observer.onCompleted();
}
}));
group.add(right.subscribe(function (value) {
var duration,
expire,
id = rightId++,
md = new SingleAssignmentDisposable(),
result,
values;
rightMap.add(id, value);
group.add(md);
expire = function () {
if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) {
observer.onCompleted();
}
return group.remove(md);
};
try {
duration = rightDurationSelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); }));
values = leftMap.getValues();
for (var i = 0; i < values.length; i++) {
try {
result = resultSelector(values[i], value);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}
}, observer.onError.bind(observer), function () {
rightDone = true;
if (leftDone || rightMap.count() === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var nothing = function () {};
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary();
var rightMap = new Dictionary();
var leftID = 0;
var rightID = 0;
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftID++;
leftMap.add(id, s);
var i, len, leftValues, rightValues;
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(result);
rightValues = rightMap.getValues();
for (i = 0, len = rightValues.length; i < len; i++) {
s.onNext(rightValues[i]);
}
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
if (leftMap.remove(id)) {
s.onCompleted();
}
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
nothing,
function (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
expire)
);
},
function (e) {
var leftValues = leftMap.getValues();
for (var i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
observer.onCompleted.bind(observer)));
group.add(right.subscribe(
function (value) {
var leftValues, i, len;
var id = rightID++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
nothing,
function (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
expire)
);
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onNext(value);
}
},
function (e) {
var leftValues = leftMap.getValues();
for (var i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
}));
return r;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, function () {
return observableEmpty();
}, function (_, window) {
return window;
});
}
function observableWindowWithBounaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var window = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
d.add(windowBoundaries.subscribe(function (w) {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
return r;
});
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var createWindowClose,
m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
window = new Subject();
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
createWindowClose = function () {
var m1, windowClose;
try {
windowClose = windowClosingSelector();
} catch (exception) {
observer.onError(exception);
return;
}
m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
createWindowClose();
}));
};
createWindowClose();
return r;
});
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector) {
return enumerableFor(sources, resultSelector).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
scheduler || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
});
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
scheduler || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.select(
function (x) {
var curr = new ChainObservable(x);
if (chain) {
chain.onNext(x);
}
chain = curr;
return curr;
})
.doAction(
noop,
function (e) {
if (chain) {
chain.onError(e);
}
},
function () {
if (chain) {
chain.onCompleted();
}
})
.observeOn(scheduler)
.select(function (x, i, o) { return selector(x, i, o); });
});
};
var ChainObservable = (function (_super) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeObservable().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, _super);
function ChainObservable(head) {
_super.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = (function () {
/**
* @constructor
* @private
*/
function Map() {
this.keys = [];
this.values = [];
}
/**
* @private
* @memberOf Map#
*/
Map.prototype['delete'] = function (key) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.keys.splice(i, 1);
this.values.splice(i, 1);
}
return i !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.get = function (key, fallback) {
var i = this.keys.indexOf(key);
return i !== -1 ? this.values[i] : fallback;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.set = function (key, value) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.values[i] = value;
}
this.values[this.keys.push(key) - 1] = value;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.size = function () { return this.keys.length; };
/**
* @private
* @memberOf Map#
*/
Map.prototype.has = function (key) {
return this.keys.indexOf(key) !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.getKeys = function () { return this.keys.slice(0); };
/**
* @private
* @memberOf Map#
*/
Map.prototype.getValues = function () { return this.values.slice(0); };
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
*
* @param other Observable sequence to match in addition to the current pattern.
* @return Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
var patterns = this.patterns.slice(0);
patterns.push(other);
return new Pattern(patterns);
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
*
* @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.then = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
// Active Plan
function ActivePlan(joinObserverArray, onNext, onCompleted) {
var i, joinObserver;
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (i = 0; i < this.joinObserverArray.length; i++) {
joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
var values = this.joinObservers.getValues();
for (var i = 0, len = values.length; i < len; i++) {
values[i].queue.shift();
}
};
ActivePlan.prototype.match = function () {
var firstValues, i, len, isCompleted, values, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
firstValues = [];
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
if (this.joinObserverArray[i].queue[0].kind === 'C') {
isCompleted = true;
}
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
values = [];
for (i = 0; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
/** @private */
var JoinObserver = (function (_super) {
inherits(JoinObserver, _super);
/**
* @constructor
* @private
*/
function JoinObserver(source, onError) {
_super.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
this.onError(notification.exception);
return;
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.error = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.completed = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.removeActivePlan = function (activePlan) {
var idx = this.activePlans.indexOf(activePlan);
this.activePlans.splice(idx, 1);
if (this.activePlans.length === 0) {
this.dispose();
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.then = function (selector) {
return new Pattern([this]).then(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map(),
group,
i, len,
joinObserver,
joinValues,
outObserver;
outObserver = observerCreate(observer.onNext.bind(observer), function (exception) {
var values = externalSubscriptions.getValues();
for (var j = 0, jlen = values.length; j < jlen; j++) {
values[j].onError(exception);
}
observer.onError(exception);
}, observer.onCompleted.bind(observer));
try {
for (i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
if (activePlans.length === 0) {
outObserver.onCompleted();
}
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
group = new CompositeDisposable();
joinValues = externalSubscriptions.getValues();
for (i = 0, len = joinValues.length; i < len; i++) {
joinObserver = joinValues[i];
joinObserver.subscribe();
group.add(joinObserver);
}
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
var p = normalizeTime(period);
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime;
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
var now;
if (p > 0) {
now = scheduler.now();
d = d + p;
if (d <= now) {
d = now + p;
}
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
var d = normalizeTime(dueTime);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(d, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
if (dueTime === period) {
return new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
});
}
return observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return observableTimerTimeSpanAndPeriod(period, period, scheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* 1 - res = Rx.Observable.timer(new Date());
* 2 - res = Rx.Observable.timer(new Date(), 1000);
* 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);
*
* 5 - res = Rx.Observable.timer(5000);
* 6 - res = Rx.Observable.timer(5000, 1000);
* 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
scheduler || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
if (period === undefined) {
return observableTimerTimeSpan(dueTime, scheduler);
}
return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(dueTime, scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
}
function observableDelayDate(dueTime, scheduler) {
var self = this;
return observableDefer(function () {
var timeSpan = dueTime - scheduler.now();
return observableDelayTimeSpan.call(self, timeSpan, scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate.call(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan.call(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
*
* @example
* 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
if (timeShiftOrScheduler === undefined) {
timeShift = timeSpan;
}
if (scheduler === undefined) {
scheduler = timeoutScheduler;
}
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (typeof timeShiftOrScheduler === 'object') {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
var s;
if (isShift) {
s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
if (isSpan) {
s = q.shift();
s.onCompleted();
}
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(function (x) {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onNext(x);
}
}, function (e) {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onError(e);
}
observer.onError(e);
}, function () {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @example
* 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items
* 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items
*
* @memberOf Observable#
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var createTimer,
groupDisposable,
n = 0,
refCountDisposable,
s,
timerD = new SerialDisposable(),
windowId = 0;
groupDisposable = new CompositeDisposable(timerD);
refCountDisposable = new RefCountDisposable(groupDisposable);
createTimer = function (id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
var newId;
if (id !== windowId) {
return;
}
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
};
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
n++;
if (n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
if (newWindow) {
createTimer(newId);
}
}, function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.select(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return {
value: x,
interval: span
};
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.select(function (x) {
return {
value: x,
timestamp: scheduler.now()
};
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
if (atEnd) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
scheduler || (scheduler = timeoutScheduler);
if (typeof intervalOrSampler === 'number') {
return sampleObservable(this, observableinterval(intervalOrSampler, scheduler));
}
return sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
*
* @example
* 1 - res = source.timeout(new Date()); // As a date
* 2 - res = source.timeout(5000); // 5 seconds
* 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable
* 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable
* 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable
* 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
other || (other = observableThrow(new Error('Timeout')));
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
if (hasResult) {
observer.onNext(result);
}
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
if (hasResult) {
observer.onNext(result);
}
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); });
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
*
* @example
* 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500));
* 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); });
* 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42));
*
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
var firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false, setTimer = function (timeout) {
var myId = id, timerWins = function () {
return id === myId;
};
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
d.dispose();
}, function (e) {
if (timerWins()) {
observer.onError(e);
}
}, function () {
if (timerWins()) {
subscription.setDisposable(other.subscribe(observer));
}
}));
};
setTimer(firstTimeout);
var observerWins = function () {
var res = !switched;
if (res) {
id++;
}
return res;
};
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(timeout);
}
}, function (e) {
if (observerWins()) {
observer.onError(e);
}
}, function () {
if (observerWins()) {
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); });
*
* @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttleWithSelector = function (throttleDurationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
if (hasValue && id === currentid) {
observer.onNext(value);
}
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
if (hasValue) {
observer.onNext(value);
}
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
*
* @example
* 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) {
return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); });
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
res.push(next.value);
}
}
observer.onNext(res);
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var t = scheduler.scheduleWithRelative(duration, function () {
observer.onCompleted();
});
return new CompositeDisposable(t, source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false,
t = scheduler.scheduleWithRelative(duration, function () { open = true; }),
d = source.subscribe(function (x) {
if (open) {
observer.onNext(x);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
return new CompositeDisposable(t, d);
});
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [optional scheduler]);
* @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]);
* 2 - res = source.takeUntilWithTime(5000, [optional scheduler]);
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} scheduler Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (_super) {
function notImplemented() {
throw new Error('Not implemented');
}
function localNow() {
return this.toDateTimeOffset(this.clock);
}
function scheduleNow(state, action) {
return this.scheduleAbsoluteWithState(state, this.clock, action);
}
function scheduleRelative(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action);
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
inherits(VirtualTimeScheduler, _super);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
_super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsoluteWithState(state, runAt, action);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) {
return this.scheduleRelativeWithState(action, dueTime, invokeAction);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
var next;
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var next;
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
if (!this.isEnabled) {
this.isEnabled = true;
do {
next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
if (this.comparer(next.dueTime, this.clock) > 0) {
this.clock = next.dueTime;
}
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time);
var dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) {
throw new Error(argumentOutOfRange);
}
if (dueToClock === 0) {
return;
}
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) {
throw new Error(argumentOutOfRange);
}
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
var next;
while (this.queue.length > 0) {
next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Scheduler} scheduler Scheduler to execute the action on.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) {
return this.scheduleAbsoluteWithState(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) {
var self = this,
run = function (scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
},
si = new ScheduledItem(self, state, run, dueTime, self.comparer);
self.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (_super) {
inherits(HistoricalScheduler, _super);
/**
* Creates a new historical scheduler with the specified initial clock value.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
_super.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
/**
* @private
*/
HistoricalSchedulerProto.toDateTimeOffset = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelative = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (typeof subscriber === 'undefined') {
subscriber = disposableEmpty;
} else if (typeof subscriber === 'function') {
subscriber = disposableCreate(subscriber);
}
return subscriber;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
});
} else {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var GroupedObservable = (function (_super) {
inherits(GroupedObservable, _super);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
/**
* @constructor
* @private
*/
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
_super.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, _super);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
_super.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
this.hasValue = true;
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
/** @private */
var AnonymousSubject = (function (_super) {
inherits(AnonymousSubject, _super);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
/**
* @private
* @constructor
*/
function AnonymousSubject(observer, observable) {
_super.call(this, subscribe);
this.observer = observer;
this.observable = observable;
}
addProperties(AnonymousSubject.prototype, Observer, {
/**
* @private
* @memberOf AnonymousSubject#
*/
onCompleted: function () {
this.observer.onCompleted();
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onError: function (exception) {
this.observer.onError(exception);
},
/**
* @private
* @memberOf AnonymousSubject#
*/
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
app/containers/Institute/InstituteListPage.js | kdprojects/nichesportapp | import React from 'react';
import H3 from 'components/H3';
import InstituteForm from './InstituteForm';
import RaisedButton from 'material-ui/RaisedButton';
import CenteredSection from '../../containers/HomePage/CenteredSection';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
import Notifications, {notify} from 'react-notify-toast';
import Loading from 'components/LoadingIndicator';
class InstituteListPage extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor() {
super();
this.state = {
showInstituteForm: false
}
}
toggleInstituteForm(value) {
this.setState({ showInstituteForm: !value })
this.props.data.refetch();
}
shouldComponentUpdate() {
return true;
}
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={()=>this.toggleInstituteForm(this.state.showInstituteForm)}
/>
];
if (this.props.data.loading) {
return (<Loading />)
}
if (this.props.data.error) {
console.log(this.props.data.error)
return (<div>An unexpected error occurred</div>)
}
return (
<div>
<Notifications />
<div>
<RaisedButton style={{"float": "right","marginTop": "10px","marginRight": "10px"}} label="Add Institute" onClick={() => this.toggleInstituteForm(this.state.showInstituteForm)} primary={true} />
<Dialog
title="Add Institute"
autoScrollBodyContent={true}
actions={actions}
modal={false}
titleStyle={{"background":"rgb(0, 188, 212)","color":"white"}}
open={this.state.showInstituteForm}
onRequestClose={()=>this.toggleInstituteForm(this.state.showInstituteForm)}
>
<InstituteForm toggleInstituteForm={(value)=>this.toggleInstituteForm(value)}/>
</Dialog>
</div>
<div style={{"float": "left","marginLeft": "50px","marginRight": "50px","marginBottom": "50px"}}>
<Table
height={"350px"}
fixedHeader={true}
selectable={false}
multiSelectable={false}>
<TableHeader
displaySelectAll={false}
adjustForCheckbox={false}
enableSelectAll={false}
>
<TableRow>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>ID</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Name</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Country</TableHeaderColumn>
<TableHeaderColumn style={{fontSize:"18px",textAlign: 'center'}}>Status</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={false}
deselectOnClickaway={false}
showRowHover={true}
>
{this.props.data.allInstitutes.map(institute=>(
<TableRow key={institute.id}>
<TableRowColumn style={{textAlign: "center"}}>{institute.id}</TableRowColumn>
<TableRowColumn style={{textAlign: "center"}}>{institute.name}</TableRowColumn>
<TableRowColumn style={{textAlign: "center"}}>{institute.country}</TableRowColumn>
<TableRowColumn style={{textAlign: "center"}}>{institute.status}</TableRowColumn>
</TableRow>
))
}
</TableBody>
</Table>
</div>
</div>
);
}
}
const InstituteQuery = gql`query InstituteQuery {
allInstitutes {
id name country status
}
}`
const InstituteData = graphql(InstituteQuery)(InstituteListPage);
export default InstituteData;
|
ajax/libs/react-data-grid/1.0.36/react-data-grid.ui-plugins.min.js | ahocevar/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react"),require("react-dom")):e.ReactDataGrid=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.Filters=t.Draggable=t.ToolsPanel=t.Data=t.Menu=t.Toolbar=t.Formatters=t.Editors=void 0;var o=n(91),i=r(o),u=n(96),s=n(99),a=n(106),l=n(107),c=n(89),p=n(102),f=n(84);window.ReactDataGridPlugins={Editors:u,Formatters:s,Toolbar:a,Menu:p,Data:c,ToolsPanel:l,Draggable:i["default"],Filters:f},t.Editors=u,t.Formatters=s,t.Toolbar=a,t.Menu=p,t.Data=c,t.ToolsPanel=l,t.Draggable=i["default"],t.Filters=f},function(t,n){t.exports=e},function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,u,s){if(!e){var a;if(void 0===t)a=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,u,s],c=0;a=new Error(t.replace(/%s/g,function(){return l[c++]})),a.name="Invariant Violation"}throw a.framesToPop=1,a}};e.exports=r},function(e,t,n){function r(e){if(!u(e)||d.call(e)!=s||i(e))return!1;var t=o(e);if(null===t)return!0;var n=p.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==f}var o=n(167),i=n(52),u=n(57),s="[object Object]",a=Function.prototype,l=Object.prototype,c=a.toString,p=l.hasOwnProperty,f=c.call(Object),d=l.toString;e.exports=r},function(e,n){e.exports=t},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){function r(e,t){return t=i(void 0===t?e.length-1:t,0),function(){for(var n=arguments,r=-1,u=i(n.length-t,0),s=Array(u);++r<u;)s[r]=n[t+r];r=-1;for(var a=Array(t+1);++r<t;)a[r]=n[r];return a[t]=s,o(e,this,a)}}var o=n(47),i=Math.max;e.exports=r},function(e,t,n){"use strict";var r=n(1),o={name:r.PropTypes.node.isRequired,key:r.PropTypes.string.isRequired,width:r.PropTypes.number.isRequired,filterable:r.PropTypes.bool};e.exports=o},function(e,t){"use strict";e.exports=!("undefined"==typeof window||!window.document||!window.document.createElement)},function(e,t,n){function r(e){return i(e)&&o(e)}var o=n(28),i=n(57);e.exports=r},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.publishSource,r=void 0===n||n,o=t.clientOffset,i=void 0===o?null:o,u=t.getSourceClientOffset;f["default"](h["default"](e),"Expected sourceIds to be an array.");var s=this.getMonitor(),a=this.getRegistry();f["default"](!s.isDragging(),"Cannot call beginDrag while dragging.");for(var l=0;l<e.length;l++)f["default"](a.getSource(e[l]),"Expected sourceIds to be registered.");for(var c=null,l=e.length-1;l>=0;l--)if(s.canDragSource(e[l])){c=e[l];break}if(null!==c){var p=null;i&&(f["default"]("function"==typeof u,"When clientOffset is provided, getSourceClientOffset must be a function."),p=u(c));var d=a.getSource(c),g=d.beginDrag(s,c);f["default"](v["default"](g),"Item must be an object."),a.pinSource(c);var m=a.getSourceType(c);return{type:y,itemType:m,item:g,sourceId:c,clientOffset:i,sourceClientOffset:p,isSourcePublic:r}}}function i(e){var t=this.getMonitor();if(t.isDragging())return{type:m}}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.clientOffset,r=void 0===n?null:n;f["default"](h["default"](e),"Expected targetIds to be an array."),e=e.slice(0);var o=this.getMonitor(),i=this.getRegistry();f["default"](o.isDragging(),"Cannot call hover while not dragging."),f["default"](!o.didDrop(),"Cannot call hover after drop.");for(var u=0;u<e.length;u++){var s=e[u];f["default"](e.lastIndexOf(s)===u,"Expected targetIds to be unique in the passed array.");var a=i.getTarget(s);f["default"](a,"Expected targetIds to be registered.")}for(var l=o.getItemType(),u=e.length-1;u>=0;u--){var s=e[u],p=i.getTargetType(s);c["default"](p,l)||e.splice(u,1)}for(var u=0;u<e.length;u++){var s=e[u],a=i.getTarget(s);a.hover(o,s)}return{type:b,targetIds:e,clientOffset:r}}function s(){var e=this,t=this.getMonitor(),n=this.getRegistry();f["default"](t.isDragging(),"Cannot call drop while not dragging."),f["default"](!t.didDrop(),"Cannot call drop twice during one drag operation.");var r=t.getTargetIds().filter(t.canDropOnTarget,t);r.reverse(),r.forEach(function(r,o){var i=n.getTarget(r),u=i.drop(t,r);f["default"]("undefined"==typeof u||v["default"](u),"Drop result must either be an object or undefined."),"undefined"==typeof u&&(u=0===o?{}:t.getDropResult()),e.store.dispatch({type:E,dropResult:u})})}function a(){var e=this.getMonitor(),t=this.getRegistry();f["default"](e.isDragging(),"Cannot call endDrag while not dragging.");var n=e.getSourceId(),r=t.getSource(n,!0);return r.endDrag(e,n),t.unpinSource(),{type:T}}t.__esModule=!0,t.beginDrag=o,t.publishDragSource=i,t.hover=u,t.drop=s,t.endDrag=a;var l=n(42),c=r(l),p=n(2),f=r(p),d=n(5),h=r(d),g=n(10),v=r(g),y="dnd-core/BEGIN_DRAG";t.BEGIN_DRAG=y;var m="dnd-core/PUBLISH_DRAG_SOURCE";t.PUBLISH_DRAG_SOURCE=m;var b="dnd-core/HOVER";t.HOVER=b;var E="dnd-core/DROP";t.DROP=E;var T="dnd-core/END_DRAG";t.END_DRAG=T},function(e,t){"use strict";function n(e){return{type:u,sourceId:e}}function r(e){return{type:s,targetId:e}}function o(e){return{type:a,sourceId:e}}function i(e){return{type:l,targetId:e}}t.__esModule=!0,t.addSource=n,t.addTarget=r,t.removeSource=o,t.removeTarget=i;var u="dnd-core/ADD_SOURCE";t.ADD_SOURCE=u;var s="dnd-core/ADD_TARGET";t.ADD_TARGET=s;var a="dnd-core/REMOVE_SOURCE";t.REMOVE_SOURCE=a;var l="dnd-core/REMOVE_TARGET";t.REMOVE_TARGET=l},function(e,t,n){function r(e,t){for(var n=e.length;n--;)if(o(e[n][0],t))return n;return-1}var o=n(17);e.exports=r},function(e,t,n){function r(e,t){var n=e.__data__;return o(t)?n["string"==typeof t?"string":"hash"]:n.map}var o=n(176);e.exports=r},function(e,t,n){var r=n(27),o=r(Object,"create");e.exports=o},function(e,t,n){var r=n(166),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();e.exports=i},function(e,t){function n(e,t){return e===t||e!==e&&t!==t}e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(246),i=n(207),u=r(i);t["default"]=(0,o.createStore)(u["default"])},function(e,t,n){"use strict";function r(e,t){}t.__esModule=!0,t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";function n(e){return Boolean(e&&"function"==typeof e.dispose)}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(e){return e&&e.ownerDocument||document}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.__data__=new o;++t<n;)this.add(e[t])}var o=n(46),i=n(191),u=n(192);r.prototype.add=r.prototype.push=i,r.prototype.has=u,e.exports=r},function(e,t,n){function r(e,t){var n=e?e.length:0;return!!n&&o(e,t,0)>-1}var o=n(154);e.exports=r},function(e,t){function n(e,t,n){for(var r=-1,o=e?e.length:0;++r<o;)if(n(t,e[r]))return!0;return!1}e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=n},function(e,t){function n(e,t){return e.has(t)}e.exports=n},function(e,t,n){function r(e,t){var n=i(e,t);return o(n)?n:void 0}var o=n(157),i=n(168);e.exports=r},function(e,t,n){function r(e){return null!=e&&i(e.length)&&!o(e)}var o=n(56),i=n(197);e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(18),i=r(o);t["default"]={getItem:function(){return i["default"].getState().currentItem},getPosition:function(){var e=i["default"].getState(),t=e.x,n=e.y;return{x:t,y:n}},hideMenu:function(){i["default"].dispatch({type:"SET_PARAMS",data:{isVisible:!1,currentItem:{}}})}}},function(e,t){"use strict";t.__esModule=!0;var n="__NATIVE_FILE__";t.FILE=n;var r="__NATIVE_URL__";t.URL=r;var o="__NATIVE_TEXT__";t.TEXT=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e["default"]:e}t.__esModule=!0;var o=n(218);t.DragDropContext=r(o);var i=n(219);t.DragLayer=r(i);var u=n(220);t.DragSource=r(u);var s=n(221);t.DropTarget=r(s)},function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,i=0;i<n.length;i++){if(!o.call(t,n[i])||e[n[i]]!==t[n[i]])return!1;var u=e[n[i]],s=t[n[i]];if(u!==s)return!1}return!0}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){var r,o;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var u in r)i.call(r,u)&&r[u]&&e.push(u)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(){y===v&&(y=v.slice())}function i(){return g}function s(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return r(),y.push(e),function(){if(t){t=!1,r();var n=y.indexOf(e);y.splice(n,1)}}}function c(e){if(!(0,u["default"])(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(m)throw new Error("Reducers may not dispatch actions.");try{m=!0,g=h(g,e)}finally{m=!1}for(var t=v=y,n=0;n<t.length;n++)t[n]();return e}function p(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");h=e,c({type:l.INIT})}function f(){var e,t=s;return e={subscribe:function(e){function n(){e.next&&e.next(i())}if("object"!=typeof e)throw new TypeError("Expected the observer to be an object.");n();var r=t(n);return{unsubscribe:r}}},e[a["default"]]=function(){return this},e}var d;if("function"==typeof t&&"undefined"==typeof n&&(n=t,t=void 0),"undefined"!=typeof n){if("function"!=typeof n)throw new Error("Expected the enhancer to be a function.");return n(o)(e,t)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");var h=e,g=t,v=[],y=v,m=!1;return c({type:l.INIT}),d={dispatch:c,subscribe:s,getState:i,replaceReducer:p},d[a["default"]]=f,d}t.__esModule=!0,t.ActionTypes=void 0,t["default"]=o;var i=n(3),u=r(i),s=n(249),a=r(s),l=t.ActionTypes={INIT:"@@redux/INIT"}},function(e,t){"use strict";t.__esModule=!0;t.DragItemTypes={Column:"column"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDragSource:e.dragSource(),isDragging:t.isDragging(),connectDragPreview:e.dragPreview()}}t.__esModule=!0;var a=n(35),l=n(31),c=n(80),p=r(c),f=n(1),d=r(f),h=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.componentDidMount=function(){var e=this.props.connectDragPreview,t=new Image;t.src="./assets/images/drag_column_full.png",t.onload=function(){e(t)}},t.prototype.setScrollLeft=function(e){var t=ReactDOM.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},t.prototype.render=function(){var e=this.props,t=e.connectDragSource,n=e.isDragging;return n?null:t(d["default"].createElement("div",{style:{cursor:"move"}},d["default"].createElement(p["default"],this.props)))},t}(f.Component);h.propTypes={connectDragSource:f.PropTypes.func.isRequired,connectDragPreview:f.PropTypes.func.isRequired,isDragging:f.PropTypes.bool.isRequired};var g={beginDrag:function(e){return e.column},endDrag:function(e){return e.column}};t["default"]=(0,l.DragSource)(a.DragItemTypes.Column,g,s)(h)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(1),s=n(4),a=n(7),l=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.getStyle=function(){return{width:"100%"}},t.prototype.getValue=function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e},t.prototype.getInputNode=function(){var e=s.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")},t.prototype.inheritContainerStyles=function(){return!0},t}(u.Component);l.propTypes={onKeyDown:u.PropTypes.func.isRequired,value:u.PropTypes.any.isRequired,onBlur:u.PropTypes.func.isRequired,column:u.PropTypes.shape(a).isRequired,commit:u.PropTypes.func.isRequired},e.exports=l},function(e,t){"use strict";t.__esModule=!0;var n=function(e){return Array.isArray(e)&&0===e.length};t["default"]=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return e&&e.constructor===Symbol?"symbol":typeof e}function u(e){f["default"]("function"==typeof e.canDrag,"Expected canDrag to be a function."),f["default"]("function"==typeof e.beginDrag,"Expected beginDrag to be a function."),f["default"]("function"==typeof e.endDrag,"Expected endDrag to be a function.")}function s(e){f["default"]("function"==typeof e.canDrop,"Expected canDrop to be a function."),f["default"]("function"==typeof e.hover,"Expected hover to be a function."),f["default"]("function"==typeof e.drop,"Expected beginDrag to be a function.")}function a(e,t){return t&&h["default"](e)?void e.forEach(function(e){return a(e,!1)}):void f["default"]("string"==typeof e||"symbol"===("undefined"==typeof e?"undefined":i(e)),t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}function l(e){var t=v["default"]().toString();switch(e){case E.SOURCE:return"S"+t;case E.TARGET:return"T"+t;default:f["default"](!1,"Unknown role: "+e)}}function c(e){switch(e[0]){case"S":return E.SOURCE;case"T":return E.TARGET;default:f["default"](!1,"Cannot parse handler ID: "+e)}}t.__esModule=!0;var p=n(2),f=r(p),d=n(5),h=r(d),g=n(125),v=r(g),y=n(12),m=n(77),b=r(m),E={SOURCE:"SOURCE",TARGET:"TARGET"},T=function(){function e(t){o(this,e),this.store=t,this.types={},this.handlers={},this.pinnedSourceId=null,this.pinnedSource=null}return e.prototype.addSource=function(e,t){a(e),u(t);var n=this.addHandler(E.SOURCE,e,t);return this.store.dispatch(y.addSource(n)),n},e.prototype.addTarget=function(e,t){a(e,!0),s(t);var n=this.addHandler(E.TARGET,e,t);return this.store.dispatch(y.addTarget(n)),n},e.prototype.addHandler=function(e,t,n){var r=l(e);return this.types[r]=t,this.handlers[r]=n,r},e.prototype.containsHandler=function(e){var t=this;return Object.keys(this.handlers).some(function(n){return t.handlers[n]===e})},e.prototype.getSource=function(e,t){f["default"](this.isSourceId(e),"Expected a valid source ID.");var n=t&&e===this.pinnedSourceId,r=n?this.pinnedSource:this.handlers[e];return r},e.prototype.getTarget=function(e){return f["default"](this.isTargetId(e),"Expected a valid target ID."),this.handlers[e]},e.prototype.getSourceType=function(e){return f["default"](this.isSourceId(e),"Expected a valid source ID."),this.types[e]},e.prototype.getTargetType=function(e){return f["default"](this.isTargetId(e),"Expected a valid target ID."),this.types[e]},e.prototype.isSourceId=function(e){var t=c(e);return t===E.SOURCE},e.prototype.isTargetId=function(e){var t=c(e);return t===E.TARGET},e.prototype.removeSource=function(e){var t=this;f["default"](this.getSource(e),"Expected an existing source."),this.store.dispatch(y.removeSource(e)),b["default"](function(){delete t.handlers[e],delete t.types[e]})},e.prototype.removeTarget=function(e){var t=this;f["default"](this.getTarget(e),"Expected an existing target."),this.store.dispatch(y.removeTarget(e)),b["default"](function(){delete t.handlers[e],delete t.types[e]})},e.prototype.pinSource=function(e){var t=this.getSource(e);f["default"](t,"Expected an existing source."),this.pinnedSourceId=e,this.pinnedSource=t},e.prototype.unpinSource=function(){f["default"](this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null},e}();t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){switch(void 0===e&&(e=f),t.type){case c.HOVER:break;case p.ADD_SOURCE:case p.ADD_TARGET:case p.REMOVE_TARGET:case p.REMOVE_SOURCE:return f;case c.BEGIN_DRAG:case c.PUBLISH_DRAG_SOURCE:case c.END_DRAG:case c.DROP:default:return d}var r=t.targetIds,o=n.targetIds,i=s["default"](r,o),u=!1;if(0===i.length){for(var a=0;a<r.length;a++)if(r[a]!==o[a]){u=!0;break}}else u=!0;if(!u)return f;var l=o[o.length-1],h=r[r.length-1];return l!==h&&(l&&i.push(l),h&&i.push(h)),i}function i(e,t){return e!==f&&(e===d||"undefined"==typeof t||l["default"](t,e).length>0)}t.__esModule=!0,t["default"]=o,t.areDirty=i;var u=n(201),s=r(u),a=n(196),l=r(a),c=n(11),p=n(12),f=[],d=[]},function(e,t,n){"use strict";function r(e,t){return e===t||e&&t&&e.x===t.x&&e.y===t.y}function o(e,t){switch(void 0===e&&(e=l),t.type){case a.BEGIN_DRAG:return{initialSourceClientOffset:t.sourceClientOffset,initialClientOffset:t.clientOffset,clientOffset:t.clientOffset};case a.HOVER:return r(e.clientOffset,t.clientOffset)?e:s({},e,{clientOffset:t.clientOffset});case a.END_DRAG:case a.DROP:return l;default:return e}}function i(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return t&&n&&r?{x:t.x+r.x-n.x,y:t.y+r.y-n.y}:null}function u(e){var t=e.clientOffset,n=e.initialClientOffset;return t&&n?{x:t.x-n.x,y:t.y-n.y}:null}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o,t.getSourceClientOffset=i,t.getDifferenceFromInitialOffset=u;var a=n(11),l={initialSourceClientOffset:null,initialClientOffset:null,clientOffset:null}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return u["default"](e)?e.some(function(e){return e===t}):e===t}t.__esModule=!0,t["default"]=o;var i=n(5),u=r(i);e.exports=t["default"]},function(e,t){"use strict";e.exports=function(e,t){return e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")!==-1}},function(e,t,n){var r,o,i;!function(n,u){o=[t],r=u,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i))}(this,function(e){var t=e;t.interopRequireDefault=function(e){return e&&e.__esModule?e:{"default":e}},t._extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}})},function(e,t,n){"use strict";var r=n(137),o=/^-ms-/;e.exports=function(e){return r(e.replace(o,"ms-"))}},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(184),i=n(185),u=n(186),s=n(187),a=n(188);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t){function n(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=n},function(e,t,n){function r(e,t,n,r){var p=-1,f=i,d=!0,h=e.length,g=[],v=t.length;if(!h)return g;n&&(t=s(t,a(n))),r?(f=u,d=!1):t.length>=c&&(f=l,d=!1,t=new o(t));e:for(;++p<h;){var y=e[p],m=n?n(y):y;if(y=r||0!==y?y:0,d&&m===m){for(var b=v;b--;)if(t[b]===m)continue e;g.push(y)}else f(t,m,r)||g.push(y)}return g}var o=n(22),i=n(23),u=n(24),s=n(25),a=n(50),l=n(26),c=200;e.exports=r},function(e,t){function n(e){return function(t){return e(t)}}e.exports=n},function(e,t,n){function r(e,t,n){var r=-1,p=i,f=e.length,d=!0,h=[],g=h;if(n)d=!1,p=u;else if(f>=c){var v=t?null:a(e);if(v)return l(v);d=!1,p=s,g=new o}else g=t?[]:h;e:for(;++r<f;){var y=e[r],m=t?t(y):y;if(y=n||0!==y?y:0,d&&m===m){for(var b=g.length;b--;)if(g[b]===m)continue e;t&&g.push(m),h.push(y)}else p(g,m,n)||(g!==h&&g.push(m),h.push(y))}return h}var o=n(22),i=n(23),u=n(24),s=n(26),a=n(165),l=n(54),c=200;e.exports=r},function(e,t){function n(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}e.exports=n},function(e,t){function n(e,t){return t=null==t?r:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var r=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=n},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}e.exports=n},function(e,t,n){function r(e){return o(e)&&s.call(e,"callee")&&(!l.call(e,"callee")||a.call(e)==i)}var o=n(9),i="[object Arguments]",u=Object.prototype,s=u.hasOwnProperty,a=u.toString,l=u.propertyIsEnumerable;e.exports=r},function(e,t,n){function r(e){var t=o(e)?a.call(e):"";return t==i||t==u}var o=n(10),i="[object Function]",u="[object GeneratorFunction]",s=Object.prototype,a=s.toString;e.exports=r},function(e,t){function n(e){return!!e&&"object"==typeof e}e.exports=n},function(e,t){function n(){}e.exports=n},function(e,t,n){var r=n(49),o=n(6),i=n(9),u=o(function(e,t){return i(e)?r(e,t):[]});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(203);Object.defineProperty(t,"ContextMenu",{enumerable:!0,get:function(){return r(o)["default"]}});var i=n(205);Object.defineProperty(t,"ContextMenuLayer",{enumerable:!0,get:function(){return r(i)["default"]}});var u=n(206);Object.defineProperty(t,"MenuItem",{enumerable:!0,get:function(){return r(u)["default"]}});var s=n(29);Object.defineProperty(t,"monitor",{enumerable:!0,get:function(){return r(s)["default"]}});var a=n(208);Object.defineProperty(t,"SubMenu",{enumerable:!0,get:function(){return r(a)["default"]}});var l=n(202);Object.defineProperty(t,"connect",{enumerable:!0,get:function(){return r(l)["default"]}})},33,function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,u,s=n(e),a=1;a<arguments.length;a++){r=Object(arguments[a]);for(var l in r)o.call(r,l)&&(s[l]=r[l]);if(Object.getOwnPropertySymbols){u=Object.getOwnPropertySymbols(r);for(var c=0;c<u.length;c++)i.call(r,u[c])&&(s[u[c]]=r[u[c]])}}return s}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(199),i=r(o),u=i["default"](function(){return/firefox/i.test(navigator.userAgent)});t.isFirefox=u;var s=i["default"](function(){return Boolean(window.safari)});t.isSafari=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return t===e||null!==t&&null!==e&&u["default"](t,e)}t.__esModule=!0,t["default"]=o;var i=n(32),u=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t=e.DecoratedComponent,n=e.createHandler,r=e.createMonitor,u=e.createConnector,f=e.registerHandler,h=e.containerDisplayName,v=e.getType,y=e.collect,b=e.options,E=b.arePropsEqual,T=void 0===E?g["default"]:E,_=t.displayName||t.name||"Component";return function(e){function g(t,i){o(this,g),e.call(this,t,i),this.handleChange=this.handleChange.bind(this),this.handleChildRef=this.handleChildRef.bind(this),m["default"]("object"==typeof this.context.dragDropManager,"Could not find the drag and drop manager in the context of %s. Make sure to wrap the top-level component of your app with DragDropContext. Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context",_,_),this.manager=this.context.dragDropManager,this.handlerMonitor=r(this.manager),this.handlerConnector=u(this.manager.getBackend()),this.handler=n(this.handlerMonitor),this.disposable=new p.SerialDisposable,this.receiveProps(t),this.state=this.getCurrentState(),this.dispose()}return i(g,e),g.prototype.getHandlerId=function(){return this.handlerId},g.prototype.getDecoratedComponentInstance=function(){return this.decoratedComponentInstance},g.prototype.shouldComponentUpdate=function(e,t){return!T(e,this.props)||!d["default"](t,this.state)},a(g,null,[{key:"DecoratedComponent",value:t,enumerable:!0},{key:"displayName",value:h+"("+_+")",enumerable:!0},{key:"contextTypes",value:{dragDropManager:l.PropTypes.object.isRequired},enumerable:!0}]),g.prototype.componentDidMount=function(){this.isCurrentlyMounted=!0,this.disposable=new p.SerialDisposable,this.currentType=null,this.receiveProps(this.props),this.handleChange()},g.prototype.componentWillReceiveProps=function(e){T(e,this.props)||(this.receiveProps(e),this.handleChange())},g.prototype.componentWillUnmount=function(){this.dispose(),this.isCurrentlyMounted=!1},g.prototype.receiveProps=function(e){this.handler.receiveProps(e),this.receiveType(v(e))},g.prototype.receiveType=function(e){if(e!==this.currentType){this.currentType=e;var t=f(e,this.handler,this.manager),n=t.handlerId,r=t.unregister;this.handlerId=n,this.handlerMonitor.receiveHandlerId(n),this.handlerConnector.receiveHandlerId(n);var o=this.manager.getMonitor(),i=o.subscribeToStateChange(this.handleChange,{handlerIds:[n]});this.disposable.setDisposable(new p.CompositeDisposable(new p.Disposable(i),new p.Disposable(r)))}},g.prototype.handleChange=function(){if(this.isCurrentlyMounted){var e=this.getCurrentState();d["default"](e,this.state)||this.setState(e)}},g.prototype.dispose=function(){this.disposable.dispose(),this.handlerConnector.receiveHandlerId(null)},g.prototype.handleChildRef=function(e){this.decoratedComponentInstance=e,this.handler.receiveComponent(e)},g.prototype.getCurrentState=function(){var e=y(this.handlerConnector.hooks,this.handlerMonitor);return e},g.prototype.render=function(){return c["default"].createElement(t,s({},this.props,this.state,{ref:this.handleChildRef}))},g}(l.Component)}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var l=n(1),c=r(l),p=n(114),f=n(32),d=r(f),h=n(67),g=r(h),v=n(3),y=(r(v),n(2)),m=r(y);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return"string"==typeof e||"symbol"==typeof e||t&&u["default"](e)&&e.every(function(e){return o(e,!1)})}t.__esModule=!0,t["default"]=o;var i=n(5),u=r(i);e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,i=0;i<n.length;i++){if(!o.call(t,n[i]))return!1;var u=e[n[i]],s=t[n[i]];if(u!==s||"object"==typeof u||"object"==typeof s)return!1}return!0}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if("string"!=typeof e.type){var t=e.type.displayName||e.type.name||"the component";throw new Error("Only native element nodes can now be passed to React DnD connectors. "+("You can either wrap "+t+" into a <div>, or turn it into a ")+"drag source or a drop target itself.")}}function i(e){return function(){var t=arguments.length<=0||void 0===arguments[0]?null:arguments[0],n=arguments.length<=1||void 0===arguments[1]?null:arguments[1];if(!l.isValidElement(t)){var r=t;return void e(r,n)}var i=t;o(i);var u=n?function(t){return e(t,n)}:e;return a["default"](i,u)}}function u(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n],o=i(r);t[n]=function(){return o}}),t}t.__esModule=!0,t["default"]=u;var s=n(230),a=r(s),l=n(1);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return e="function"==typeof e?e():e,u["default"].findDOMNode(e)||t}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(4),u=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(e){return(0,s["default"])(i["default"].findDOMNode(e))};var o=n(4),i=r(o),u=n(21),s=r(u);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var u=e[t],a="undefined"==typeof u?"undefined":i(u);return s["default"].isValidElement(u)?new Error("Invalid "+r+" `"+o+"` of type ReactElement "+("supplied to `"+n+"`, expected a ReactComponent or a ")+"DOMElement. You can usually obtain a ReactComponent or DOMElement from a ReactElement by attaching a ref to it."):"object"===a&&"function"==typeof u.render||1===u.nodeType?null:new Error("Invalid "+r+" `"+o+"` of value `"+u+"` "+("supplied to `"+n+"`, expected a ReactComponent or a ")+"DOMElement.");
}t.__esModule=!0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},u=n(1),s=r(u),a=n(72),l=r(a);t["default"]=(0,l["default"])(o)},function(e,t){"use strict";function n(e){function t(t,n,r,o,i,u){var s=o||"<<anonymous>>",a=u||r;if(null==n[r])return t?new Error("Required "+i+" `"+a+"` was not specified "+("in `"+s+"`.")):null;for(var l=arguments.length,c=Array(l>6?l-6:0),p=6;p<l;p++)c[p-6]=arguments[p];return e.apply(void 0,[n,r,s,i,a].concat(c))}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}t.__esModule=!0,t["default"]=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){return"object"==typeof e?JSON.stringify(e):e}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),a=r(s),l=n(4),c=r(l),p=n(231),f=r(p),d=n(33),h=r(d),g=n(109),v=r(g),y=n(74),m=r(y),b=n(240),E=r(b),T=n(241),_=r(T),D=n(242),w=r(D),C=a["default"].PropTypes.oneOfType([a["default"].PropTypes.string,a["default"].PropTypes.node]),O=1,x=a["default"].createClass({displayName:"Select",propTypes:{addLabelText:a["default"].PropTypes.string,allowCreate:a["default"].PropTypes.bool,"aria-label":a["default"].PropTypes.string,"aria-labelledby":a["default"].PropTypes.string,autoBlur:a["default"].PropTypes.bool,autofocus:a["default"].PropTypes.bool,autosize:a["default"].PropTypes.bool,backspaceRemoves:a["default"].PropTypes.bool,backspaceToRemoveMessage:a["default"].PropTypes.string,className:a["default"].PropTypes.string,clearAllText:C,clearValueText:C,clearable:a["default"].PropTypes.bool,delimiter:a["default"].PropTypes.string,disabled:a["default"].PropTypes.bool,escapeClearsValue:a["default"].PropTypes.bool,filterOption:a["default"].PropTypes.func,filterOptions:a["default"].PropTypes.any,ignoreAccents:a["default"].PropTypes.bool,ignoreCase:a["default"].PropTypes.bool,inputProps:a["default"].PropTypes.object,inputRenderer:a["default"].PropTypes.func,isLoading:a["default"].PropTypes.bool,joinValues:a["default"].PropTypes.bool,labelKey:a["default"].PropTypes.string,matchPos:a["default"].PropTypes.string,matchProp:a["default"].PropTypes.string,menuBuffer:a["default"].PropTypes.number,menuContainerStyle:a["default"].PropTypes.object,menuRenderer:a["default"].PropTypes.func,menuStyle:a["default"].PropTypes.object,multi:a["default"].PropTypes.bool,name:a["default"].PropTypes.string,newOptionCreator:a["default"].PropTypes.func,noResultsText:C,onBlur:a["default"].PropTypes.func,onBlurResetsInput:a["default"].PropTypes.bool,onChange:a["default"].PropTypes.func,onClose:a["default"].PropTypes.func,onFocus:a["default"].PropTypes.func,onInputChange:a["default"].PropTypes.func,onMenuScrollToBottom:a["default"].PropTypes.func,onOpen:a["default"].PropTypes.func,onValueClick:a["default"].PropTypes.func,openAfterFocus:a["default"].PropTypes.bool,openOnFocus:a["default"].PropTypes.bool,optionClassName:a["default"].PropTypes.string,optionComponent:a["default"].PropTypes.func,optionRenderer:a["default"].PropTypes.func,options:a["default"].PropTypes.array,pageSize:a["default"].PropTypes.number,placeholder:C,required:a["default"].PropTypes.bool,resetValue:a["default"].PropTypes.any,scrollMenuIntoView:a["default"].PropTypes.bool,searchable:a["default"].PropTypes.bool,simpleValue:a["default"].PropTypes.bool,style:a["default"].PropTypes.object,tabIndex:a["default"].PropTypes.string,tabSelectsValue:a["default"].PropTypes.bool,value:a["default"].PropTypes.any,valueComponent:a["default"].PropTypes.func,valueKey:a["default"].PropTypes.string,valueRenderer:a["default"].PropTypes.func,wrapperStyle:a["default"].PropTypes.object},statics:{Async:E["default"]},getDefaultProps:function(){return{addLabelText:'Add "{label}"?',autosize:!0,allowCreate:!1,backspaceRemoves:!0,backspaceToRemoveMessage:"Press backspace to remove {label}",clearable:!0,clearAllText:"Clear all",clearValueText:"Clear value",delimiter:",",disabled:!1,escapeClearsValue:!0,filterOptions:!0,ignoreAccents:!0,ignoreCase:!0,inputProps:{},isLoading:!1,joinValues:!1,labelKey:"label",matchPos:"any",matchProp:"any",menuBuffer:0,multi:!1,noResultsText:"No results found",onBlurResetsInput:!0,openAfterFocus:!1,optionComponent:_["default"],pageSize:5,placeholder:"Select...",required:!1,resetValue:null,scrollMenuIntoView:!0,searchable:!0,simpleValue:!1,tabSelectsValue:!0,valueComponent:w["default"],valueKey:"value"}},getInitialState:function(){return{inputValue:"",isFocused:!1,isLoading:!1,isOpen:!1,isPseudoFocused:!1,required:!1}},componentWillMount:function(){this._instancePrefix="react-select-"+ ++O+"-";var e=this.getValueArray(this.props.value);this.props.required&&this.setState({required:this.handleRequired(e[0],this.props.multi)})},componentDidMount:function(){this.props.autofocus&&this.focus()},componentWillReceiveProps:function(e){var t=this.getValueArray(e.value,e);e.required&&this.setState({required:this.handleRequired(t[0],e.multi)})},componentWillUpdate:function(e,t){if(t.isOpen!==this.state.isOpen){var n=t.isOpen?e.onOpen:e.onClose;n&&n()}},componentDidUpdate:function(e,t){if(this.refs.menu&&this.refs.focused&&this.state.isOpen&&!this.hasScrolledToOption){var n=c["default"].findDOMNode(this.refs.focused),r=c["default"].findDOMNode(this.refs.menu);r.scrollTop=n.offsetTop,this.hasScrolledToOption=!0}else this.state.isOpen||(this.hasScrolledToOption=!1);if(this._scrollToFocusedOptionOnUpdate&&this.refs.focused&&this.refs.menu){this._scrollToFocusedOptionOnUpdate=!1;var o=c["default"].findDOMNode(this.refs.focused),i=c["default"].findDOMNode(this.refs.menu),u=o.getBoundingClientRect(),s=i.getBoundingClientRect();(u.bottom>s.bottom||u.top<s.top)&&(i.scrollTop=o.offsetTop+o.clientHeight-i.offsetHeight)}if(this.props.scrollMenuIntoView&&this.refs.menuContainer){var a=this.refs.menuContainer.getBoundingClientRect();window.innerHeight<a.bottom+this.props.menuBuffer&&window.scrollBy(0,a.bottom+this.props.menuBuffer-window.innerHeight)}e.disabled!==this.props.disabled&&(this.setState({isFocused:!1}),this.closeMenu())},focus:function(){this.refs.input&&(this.refs.input.focus(),this.props.openAfterFocus&&this.setState({isOpen:!0}))},blurInput:function(){this.refs.input&&this.refs.input.blur()},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchEndClearValue:function(e){this.dragging||this.clearValue(e)},handleMouseDown:function(e){if(!(this.props.disabled||"mousedown"===e.type&&0!==e.button)&&"INPUT"!==e.target.tagName){if(e.stopPropagation(),e.preventDefault(),!this.props.searchable)return this.focus(),this.setState({isOpen:!this.state.isOpen});if(this.state.isFocused){this.focus();var t=this.refs.input;"function"==typeof t.getInput&&(t=t.getInput()),t.value="",this.setState({isOpen:!0,isPseudoFocused:!1})}else this._openAfterFocus=!0,this.focus()}},handleMouseDownOnArrow:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||this.state.isOpen&&(e.stopPropagation(),e.preventDefault(),this.closeMenu())},handleMouseDownOnMenu:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this._openAfterFocus=!0,this.focus())},closeMenu:function(){this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi,inputValue:""}),this.hasScrolledToOption=!1},handleInputFocus:function(e){var t=this.state.isOpen||this._openAfterFocus||this.props.openOnFocus;this.props.onFocus&&this.props.onFocus(e),this.setState({isFocused:!0,isOpen:t}),this._openAfterFocus=!1},handleInputBlur:function(e){if(this.refs.menu&&(this.refs.menu===document.activeElement||this.refs.menu.contains(document.activeElement)))return void this.focus();this.props.onBlur&&this.props.onBlur(e);var t={isFocused:!1,isOpen:!1,isPseudoFocused:!1};this.props.onBlurResetsInput&&(t.inputValue=""),this.setState(t)},handleInputChange:function(e){var t=e.target.value;if(this.state.inputValue!==e.target.value&&this.props.onInputChange){var n=this.props.onInputChange(t);null!=n&&"object"!=typeof n&&(t=""+n)}this.setState({isOpen:!0,isPseudoFocused:!1,inputValue:t})},handleKeyDown:function(e){if(!this.props.disabled){switch(e.keyCode){case 8:return void(!this.state.inputValue&&this.props.backspaceRemoves&&(e.preventDefault(),this.popValue()));case 9:if(e.shiftKey||!this.state.isOpen||!this.props.tabSelectsValue)return;return void this.selectFocusedOption();case 13:if(!this.state.isOpen)return;e.stopPropagation(),this.selectFocusedOption();break;case 27:this.state.isOpen?(this.closeMenu(),e.stopPropagation()):this.props.clearable&&this.props.escapeClearsValue&&(this.clearValue(e),e.stopPropagation());break;case 38:this.focusPreviousOption();break;case 40:this.focusNextOption();break;case 33:this.focusPageUpOption();break;case 34:this.focusPageDownOption();break;case 35:this.focusEndOption();break;case 36:this.focusStartOption();break;default:return}e.preventDefault()}},handleValueClick:function(e,t){this.props.onValueClick&&this.props.onValueClick(e,t)},handleMenuScroll:function(e){if(this.props.onMenuScrollToBottom){var t=e.target;t.scrollHeight>t.offsetHeight&&!(t.scrollHeight-t.offsetHeight-t.scrollTop)&&this.props.onMenuScrollToBottom()}},handleRequired:function(e,t){return!e||(t?0===e.length:0===Object.keys(e).length)},getOptionLabel:function(e){return e[this.props.labelKey]},getValueArray:function(e,t){var n=this,r="object"==typeof t?t:this.props;if(r.multi){if("string"==typeof e&&(e=e.split(r.delimiter)),!Array.isArray(e)){if(null===e||void 0===e)return[];e=[e]}return e.map(function(e){return n.expandValue(e,r)}).filter(function(e){return e})}var o=this.expandValue(e,r);return o?[o]:[]},expandValue:function(e,t){if("string"!=typeof e&&"number"!=typeof e)return e;var n=t.options,r=t.valueKey;if(n)for(var o=0;o<n.length;o++)if(n[o][r]===e)return n[o]},setValue:function(e){var t=this;if(this.props.autoBlur&&this.blurInput(),this.props.onChange){if(this.props.required){var n=this.handleRequired(e,this.props.multi);this.setState({required:n})}this.props.simpleValue&&e&&(e=this.props.multi?e.map(function(e){return e[t.props.valueKey]}).join(this.props.delimiter):e[this.props.valueKey]),this.props.onChange(e)}},selectValue:function(e){var t=this;this.hasScrolledToOption=!1,this.props.multi?this.setState({inputValue:"",focusedIndex:null},function(){t.addValue(e)}):this.setState({isOpen:!1,inputValue:"",isPseudoFocused:this.state.isFocused},function(){t.setValue(e)})},addValue:function(e){var t=this.getValueArray(this.props.value);this.setValue(t.concat(e))},popValue:function(){var e=this.getValueArray(this.props.value);e.length&&e[e.length-1].clearableValue!==!1&&this.setValue(e.slice(0,e.length-1))},removeValue:function(e){var t=this.getValueArray(this.props.value);this.setValue(t.filter(function(t){return t!==e})),this.focus()},clearValue:function(e){e&&"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this.setValue(this.props.resetValue),this.setState({isOpen:!1,inputValue:""},this.focus))},focusOption:function(e){this.setState({focusedOption:e})},focusNextOption:function(){this.focusAdjacentOption("next")},focusPreviousOption:function(){this.focusAdjacentOption("previous")},focusPageUpOption:function(){this.focusAdjacentOption("page_up")},focusPageDownOption:function(){this.focusAdjacentOption("page_down")},focusStartOption:function(){this.focusAdjacentOption("start")},focusEndOption:function(){this.focusAdjacentOption("end")},focusAdjacentOption:function(e){var t=this._visibleOptions.map(function(e,t){return{option:e,index:t}}).filter(function(e){return!e.option.disabled});if(this._scrollToFocusedOptionOnUpdate=!0,!this.state.isOpen)return void this.setState({isOpen:!0,inputValue:"",focusedOption:this._focusedOption||t["next"===e?0:t.length-1].option});if(t.length){for(var n=-1,r=0;r<t.length;r++)if(this._focusedOption===t[r].option){n=r;break}if("next"===e&&n!==-1)n=(n+1)%t.length;else if("previous"===e)n>0?n-=1:n=t.length-1;else if("start"===e)n=0;else if("end"===e)n=t.length-1;else if("page_up"===e){var o=n-this.props.pageSize;n=o<0?0:o}else if("page_down"===e){var o=n+this.props.pageSize;n=o>t.length-1?t.length-1:o}n===-1&&(n=0),this.setState({focusedIndex:t[n].index,focusedOption:t[n].option})}},selectFocusedOption:function(){if(this._focusedOption)return this.selectValue(this._focusedOption)},renderLoading:function(){if(this.props.isLoading)return a["default"].createElement("span",{className:"Select-loading-zone","aria-hidden":"true"},a["default"].createElement("span",{className:"Select-loading"}))},renderValue:function(e,t){var n=this,r=this.props.valueRenderer||this.getOptionLabel,o=this.props.valueComponent;if(!e.length)return this.state.inputValue?null:a["default"].createElement("div",{className:"Select-placeholder"},this.props.placeholder);var i=this.props.onValueClick?this.handleValueClick:null;return this.props.multi?e.map(function(e,t){return a["default"].createElement(o,{id:n._instancePrefix+"-value-"+t,instancePrefix:n._instancePrefix,disabled:n.props.disabled||e.clearableValue===!1,key:"value-"+t+"-"+e[n.props.valueKey],onClick:i,onRemove:n.removeValue,value:e},r(e),a["default"].createElement("span",{className:"Select-aria-only"}," "))}):this.state.inputValue?void 0:(t&&(i=null),a["default"].createElement(o,{id:this._instancePrefix+"-value-item",disabled:this.props.disabled,instancePrefix:this._instancePrefix,onClick:i,value:e[0]},r(e[0])))},renderInput:function(e,t){if(this.props.inputRenderer)return this.props.inputRenderer();var n,r=(0,h["default"])("Select-input",this.props.inputProps.className),i=!!this.state.isOpen,s=(0,h["default"])((n={},o(n,this._instancePrefix+"-list",i),o(n,this._instancePrefix+"-backspace-remove-message",this.props.multi&&!this.props.disabled&&this.state.isFocused&&!this.state.inputValue),n)),l=u({},this.props.inputProps,{role:"combobox","aria-expanded":""+i,"aria-owns":s,"aria-haspopup":""+i,"aria-activedescendant":i?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value","aria-labelledby":this.props["aria-labelledby"],"aria-label":this.props["aria-label"],className:r,tabIndex:this.props.tabIndex,onBlur:this.handleInputBlur,onChange:this.handleInputChange,onFocus:this.handleInputFocus,ref:"input",required:this.state.required,value:this.state.inputValue});if(this.props.disabled||!this.props.searchable){var c=(0,v["default"])(this.props.inputProps,"inputClassName");return a["default"].createElement("div",u({},c,{role:"combobox","aria-expanded":i,"aria-owns":i?this._instancePrefix+"-list":this._instancePrefix+"-value","aria-activedescendant":i?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value",className:r,tabIndex:this.props.tabIndex||0,onBlur:this.handleInputBlur,onFocus:this.handleInputFocus,ref:"input","aria-readonly":""+!!this.props.disabled,style:{border:0,width:1,display:"inline-block"}}))}return this.props.autosize?a["default"].createElement(f["default"],u({},l,{minWidth:"5px"})):a["default"].createElement("div",{className:r},a["default"].createElement("input",l))},renderClear:function(){if(this.props.clearable&&this.props.value&&(!this.props.multi||this.props.value.length)&&!this.props.disabled&&!this.props.isLoading)return a["default"].createElement("span",{className:"Select-clear-zone",title:this.props.multi?this.props.clearAllText:this.props.clearValueText,"aria-label":this.props.multi?this.props.clearAllText:this.props.clearValueText,onMouseDown:this.clearValue,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEndClearValue},a["default"].createElement("span",{className:"Select-clear",dangerouslySetInnerHTML:{__html:"×"}}))},renderArrow:function(){return a["default"].createElement("span",{className:"Select-arrow-zone",onMouseDown:this.handleMouseDownOnArrow},a["default"].createElement("span",{className:"Select-arrow",onMouseDown:this.handleMouseDownOnArrow}))},filterOptions:function(e){var t=this,n=this.state.inputValue,r=this.props.options||[];return"function"==typeof this.props.filterOptions?this.props.filterOptions.call(this,r,n,e):this.props.filterOptions?(this.props.ignoreAccents&&(n=(0,m["default"])(n)),this.props.ignoreCase&&(n=n.toLowerCase()),e&&(e=e.map(function(e){return e[t.props.valueKey]})),r.filter(function(r){if(e&&e.indexOf(r[t.props.valueKey])>-1)return!1;if(t.props.filterOption)return t.props.filterOption.call(t,r,n);if(!n)return!0;var o=String(r[t.props.valueKey]),i=String(r[t.props.labelKey]);return t.props.ignoreAccents&&("label"!==t.props.matchProp&&(o=(0,m["default"])(o)),"value"!==t.props.matchProp&&(i=(0,m["default"])(i))),t.props.ignoreCase&&("label"!==t.props.matchProp&&(o=o.toLowerCase()),"value"!==t.props.matchProp&&(i=i.toLowerCase())),"start"===t.props.matchPos?"label"!==t.props.matchProp&&o.substr(0,n.length)===n||"value"!==t.props.matchProp&&i.substr(0,n.length)===n:"label"!==t.props.matchProp&&o.indexOf(n)>=0||"value"!==t.props.matchProp&&i.indexOf(n)>=0})):r},renderMenu:function(e,t,n){var r=this;if(!e||!e.length)return this.props.noResultsText?a["default"].createElement("div",{className:"Select-noresults"},this.props.noResultsText):null;if(this.props.menuRenderer)return this.props.menuRenderer({focusedOption:n,focusOption:this.focusOption,labelKey:this.props.labelKey,options:e,selectValue:this.selectValue,valueArray:t});var o=function(){var o=r.props.optionComponent,i=r.props.optionRenderer||r.getOptionLabel;return{v:e.map(function(e,u){var s=t&&t.indexOf(e)>-1,l=e===n,c=l?"focused":null,p=(0,h["default"])(r.props.optionClassName,{"Select-option":!0,"is-selected":s,"is-focused":l,"is-disabled":e.disabled});return a["default"].createElement(o,{instancePrefix:r._instancePrefix,optionIndex:u,className:p,isDisabled:e.disabled,isFocused:l,key:"option-"+u+"-"+e[r.props.valueKey],onSelect:r.selectValue,onFocus:r.focusOption,option:e,isSelected:s,ref:c},i(e))})}}();return"object"==typeof o?o.v:void 0},renderHiddenField:function(e){var t=this;if(this.props.name){if(this.props.joinValues){var n=e.map(function(e){return i(e[t.props.valueKey])}).join(this.props.delimiter);return a["default"].createElement("input",{type:"hidden",ref:"value",name:this.props.name,value:n,disabled:this.props.disabled})}return e.map(function(e,n){return a["default"].createElement("input",{key:"hidden."+n,type:"hidden",ref:"value"+n,name:t.props.name,value:i(e[t.props.valueKey]),disabled:t.props.disabled})})}},getFocusableOptionIndex:function(e){var t=this._visibleOptions;if(!t.length)return null;var n=this.state.focusedOption||e;if(n&&!n.disabled){var r=t.indexOf(n);if(r!==-1)return r}for(var o=0;o<t.length;o++)if(!t[o].disabled)return o;return null},renderOuter:function(e,t,n){var r=this.renderMenu(e,t,n);return r?a["default"].createElement("div",{ref:"menuContainer",className:"Select-menu-outer",style:this.props.menuContainerStyle},a["default"].createElement("div",{ref:"menu",role:"listbox",className:"Select-menu",id:this._instancePrefix+"-list",style:this.props.menuStyle,onScroll:this.handleMenuScroll,onMouseDown:this.handleMouseDownOnMenu},r)):null},render:function(){var e=this.getValueArray(this.props.value),t=this._visibleOptions=this.filterOptions(this.props.multi?e:null),n=this.state.isOpen;this.props.multi&&!t.length&&e.length&&!this.state.inputValue&&(n=!1);var r=this.getFocusableOptionIndex(e[0]),o=null;o=null!==r?this._focusedOption=this._visibleOptions[r]:this._focusedOption=null;var i=(0,h["default"])("Select",this.props.className,{"Select--multi":this.props.multi,"Select--single":!this.props.multi,"is-disabled":this.props.disabled,"is-focused":this.state.isFocused,"is-loading":this.props.isLoading,"is-open":n,"is-pseudo-focused":this.state.isPseudoFocused,"is-searchable":this.props.searchable,"has-value":e.length}),u=null;return this.props.multi&&!this.props.disabled&&e.length&&!this.state.inputValue&&this.state.isFocused&&this.props.backspaceRemoves&&(u=a["default"].createElement("span",{id:this._instancePrefix+"-backspace-remove-message",className:"Select-aria-only","aria-live":"assertive"},this.props.backspaceToRemoveMessage.replace("{label}",e[e.length-1][this.props.labelKey]))),a["default"].createElement("div",{ref:"wrapper",className:i,style:this.props.wrapperStyle},this.renderHiddenField(e),a["default"].createElement("div",{ref:"control",className:"Select-control",style:this.props.style,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleTouchEnd,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},a["default"].createElement("span",{className:"Select-multi-value-wrapper",id:this._instancePrefix+"-value"},this.renderValue(e,n),this.renderInput(e,r)),u,this.renderLoading(),this.renderClear(),this.renderArrow()),n?this.renderOuter(t,this.props.multi?null:e,o):null)}});t["default"]=x,e.exports=t["default"]},function(e,t){"use strict";var n=[{base:"A",letters:/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},{base:"AA",letters:/[\uA732]/g},{base:"AE",letters:/[\u00C6\u01FC\u01E2]/g},{base:"AO",letters:/[\uA734]/g},{base:"AU",letters:/[\uA736]/g},{base:"AV",letters:/[\uA738\uA73A]/g},{base:"AY",letters:/[\uA73C]/g},{base:"B",letters:/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},{base:"C",letters:/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},{base:"D",letters:/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},{base:"DZ",letters:/[\u01F1\u01C4]/g},{base:"Dz",letters:/[\u01F2\u01C5]/g},{base:"E",letters:/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},{base:"F",letters:/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},{base:"G",letters:/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},{base:"H",letters:/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},{base:"I",letters:/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},{base:"J",letters:/[\u004A\u24BF\uFF2A\u0134\u0248]/g},{base:"K",letters:/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},{base:"L",letters:/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},{base:"LJ",letters:/[\u01C7]/g},{base:"Lj",letters:/[\u01C8]/g},{base:"M",letters:/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},{base:"N",letters:/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},{base:"NJ",letters:/[\u01CA]/g},{base:"Nj",letters:/[\u01CB]/g},{base:"O",letters:/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},{base:"OI",letters:/[\u01A2]/g},{base:"OO",letters:/[\uA74E]/g},{base:"OU",letters:/[\u0222]/g},{base:"P",letters:/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},{base:"Q",letters:/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},{base:"R",letters:/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},{base:"S",letters:/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},{base:"T",letters:/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},{base:"TZ",letters:/[\uA728]/g},{base:"U",letters:/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},{base:"V",letters:/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},{base:"VY",letters:/[\uA760]/g},{base:"W",letters:/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},{base:"X",letters:/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},{base:"Y",letters:/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},{base:"Z",letters:/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},{base:"a",letters:/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},{base:"aa",letters:/[\uA733]/g},{base:"ae",letters:/[\u00E6\u01FD\u01E3]/g},{base:"ao",letters:/[\uA735]/g},{base:"au",letters:/[\uA737]/g},{base:"av",letters:/[\uA739\uA73B]/g},{base:"ay",letters:/[\uA73D]/g},{base:"b",letters:/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},{base:"c",letters:/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},{base:"d",letters:/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},{base:"dz",letters:/[\u01F3\u01C6]/g},{base:"e",letters:/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},{base:"f",letters:/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},{base:"g",letters:/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},{base:"h",letters:/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},{base:"hv",letters:/[\u0195]/g},{base:"i",letters:/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},{base:"j",letters:/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},{base:"k",letters:/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},{base:"l",letters:/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},{base:"lj",letters:/[\u01C9]/g},{base:"m",letters:/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},{base:"n",letters:/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},{base:"nj",letters:/[\u01CC]/g},{base:"o",letters:/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},{base:"oi",letters:/[\u01A3]/g},{base:"ou",letters:/[\u0223]/g},{base:"oo",letters:/[\uA74F]/g},{base:"p",letters:/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},{base:"q",letters:/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},{base:"r",letters:/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},{base:"s",letters:/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},{base:"t",letters:/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},{base:"tz",letters:/[\uA729]/g},{base:"u",letters:/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},{base:"v",letters:/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},{base:"vy",letters:/[\uA761]/g},{base:"w",letters:/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},{base:"x",letters:/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},{base:"y",letters:/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},{base:"z",letters:/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}];e.exports=function(e){for(var t=0;t<n.length;t++)e=e.replace(n[t].letters,n[t].base);return e}},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0===t.length)return function(e){return e};var r=function(){var e=t[t.length-1],n=t.slice(0,-1);return{v:function(){return n.reduceRight(function(e,t){return t(e)},e.apply(void 0,arguments))}}}();return"object"==typeof r?r.v:void 0}t.__esModule=!0,t["default"]=n},function(e,t){"use strict";function n(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(t){}}t.__esModule=!0,t["default"]=n},function(e,t,n){"use strict";function r(){if(a.length)throw a.shift()}function o(e){var t;t=s.length?s.pop():new i,t.task=e,u(t)}function i(){this.task=null}var u=n(78),s=[],a=[],l=u.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(e){o.onerror?o.onerror(e):(a.push(e),l())}finally{this.task=null,s[s.length]=this}}},function(e,t,n){"use strict";function r(e){a.length||(s(),l=!0),a[a.length]=e}function o(){for(;c<a.length;){var e=c;if(c+=1,a[e].call(),c>p){for(var t=0,n=a.length-c;t<n;t++)a[t]=a[t+c];a.length-=c,c=0}}a.length=0,c=0,l=!1}function i(e){var t=1,n=new f(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function u(e){return function(){function t(){clearTimeout(n),clearInterval(r),e()}var n=setTimeout(t,0),r=setInterval(t,50)}}e.exports=r;var s,a=[],l=!1,c=0,p=1024,f=window.MutationObserver||window.WebKitMutationObserver;s="function"==typeof f?i(o):u(o),r.requestFlush=s,r.makeRequestCallFromTimer=u},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i=o.PropTypes,u=o.createClass({displayName:"Draggable",propTypes:{onDragStart:i.func,onDragEnd:i.func,onDrag:i.func,component:i.oneOfType([i.func,i.constructor])},getDefaultProps:function(){return{onDragStart:function(){return!0},onDragEnd:function(){},onDrag:function(){}}},getInitialState:function(){return{drag:null}},componentWillUnmount:function(){this.cleanUp()},onMouseDown:function(e){var t=this.props.onDragStart(e);null===t&&0!==e.button||(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("touchend",this.onMouseUp),window.addEventListener("touchmove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("touchend",this.onMouseUp),window.removeEventListener("touchmove",this.onMouseMove)},render:function(){return o.createElement("div",r({},this.props,{onMouseDown:this.onMouseDown,onTouchStart:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))}});e.exports=u},function(e,t,n){"use strict";function r(e){return o.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var o=n(1),i=n(4),u=n(110),s=n(7),a=n(81),l=o.PropTypes,c=o.createClass({
displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(s).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired,className:l.string},getDefaultProps:function(){return{renderer:r}},getInitialState:function(){return{resizing:!1}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var n=this.getWidthFromMouseEvent(e);n>0&&t(this.props.column,n)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX||e.touches&&e.touches[0]&&e.touches[0].pageX||e.changedTouches&&e.changedTouches[e.changedTouches.length-1].pageX,n=i.findDOMNode(this).getBoundingClientRect().left;return t-n},getCell:function(){return o.isValidElement(this.props.renderer)?o.cloneElement(this.props.renderer,{column:this.props.column,height:this.props.height}):this.props.renderer({column:this.props.column})},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},setScrollLeft:function(e){var t=i.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},render:function(){var e=void 0;this.props.column.resizable&&(e=o.createElement(a,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=u({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=u(t,this.props.className,this.props.column.cellClass);var n=this.getCell();return o.createElement("div",{className:t,style:this.getStyle()},n,e)}});e.exports=c},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i=n(79),u=o.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return o.createElement(i,r({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=n(7),c=r(l),p=n(73),f=r(p),d=n(38),h=r(d),g=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return r.getOptions=r.getOptions.bind(r),r.handleChange=r.handleChange.bind(r),r.filterValues=r.filterValues.bind(r),r.state={options:r.getOptions(),rawValue:"",placeholder:"Search..."},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({options:this.getOptions(e)})},t.prototype.getOptions=function(e){var t=e||this.props,n=t.getValidFilterValues(t.column.key);return n=n.map(function(e){return"string"==typeof e?{value:e,label:e}:e})},t.prototype.columnValueContainsSearchTerms=function n(e,t){var n=!1;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r].value,i=e.trim().toLowerCase().indexOf(o.trim().toLowerCase()),u=i!==-1&&(0!==i||e===o);if(u){n=!0;break}}return n},t.prototype.filterValues=function(e,t,n){var r=!0;return null===t?r=!1:(0,h["default"])(t.filterTerm)||(r=this.columnValueContainsSearchTerms(e[n],t.filterTerm)),r},t.prototype.handleChange=function(e){var t=e;this.setState({filters:t}),this.props.onChange({filterTerm:t,column:this.props.column,rawValue:e,filterValues:this.filterValues})},t.prototype.render=function(){var e="filter-"+this.props.column.key;return a["default"].createElement("div",{style:{width:.9*this.props.column.width}},a["default"].createElement(f["default"],{name:e,options:this.state.options,placeholder:this.state.placeholder,onChange:this.handleChange,escapeClearsValue:!0,multi:!0,value:this.state.filters}))},t}(a["default"].Component);g.propTypes={onChange:s.PropTypes.func.isRequired,column:a["default"].PropTypes.shape(c["default"]),getValidFilterValues:s.PropTypes.func},t["default"]=g},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=n(1),a=r(s),l=n(7),c=r(l),p={Number:1,Range:2,GreaterThen:3,LessThen:4},f=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return r.handleChange=r.handleChange.bind(r),r.handleKeyPress=r.handleKeyPress.bind(r),r.getRules=r.getRules.bind(r),r}return u(t,e),t.prototype.componentDidMount=function(){this.attachTooltip()},t.prototype.componentDidUpdate=function(){this.attachTooltip()},t.prototype.attachTooltip=function(){$?$('[data-toggle="tooltip"]').tooltip():jQuery&&jQuery('[data-toggle="tooltip"]').tooltip()},t.prototype.filterValues=function(e,t,n){if(null==t.filterTerm)return!0;var r=!1,o=parseInt(e[n],10);for(var i in t.filterTerm)if(t.filterTerm.hasOwnProperty(i)){var u=t.filterTerm[i];switch(u.type){case p.Number:u.value===o&&(r=!0);break;case p.GreaterThen:u.value<=o&&(r=!0);break;case p.LessThen:u.value>=o&&(r=!0);break;case p.Range:u.begin<=o&&u.end>=o&&(r=!0)}}return r},t.prototype.getRules=function(e){var t=[];if(""===e)return t;var n=e.split(",");if(n.length>0)for(var r in n)if(n.hasOwnProperty(r)){var o=n[r];if(o.indexOf("-")>0){var i=parseInt(o.split("-")[0],10),u=parseInt(o.split("-")[1],10);t.push({type:p.Range,begin:i,end:u})}else if(o.indexOf(">")>-1){var s=parseInt(o.split(">")[1],10);t.push({type:p.GreaterThen,value:s})}else if(o.indexOf("<")>-1){var a=parseInt(o.split("<")[1],10);t.push({type:p.LessThen,value:a})}else{var l=parseInt(o,10);t.push({type:p.Number,value:l})}}return t},t.prototype.handleKeyPress=function(e){var t=">|<|-|,|([0-9])",n=RegExp(t).test(e.key);n===!1&&e.preventDefault()},t.prototype.handleChange=function(e){var t=e.target.value,n=this.getRules(t);this.props.onChange({filterTerm:n.length>0?n:null,column:this.props.column,rawValue:t,filterValues:this.filterValues})},t.prototype.render=function(){var e="header-filter-"+this.props.column.key,t={"float":"left",marginRight:5,maxWidth:"80%"},n={cursor:"help"},r='<table><tbody><tr><td colspan="2"><strong>Input Methods:</strong></td></tr><tr><td><strong>- </strong></td><td style="text-align:left">Range</td></tr><tr><td><strong>> </strong></td><td style="text-align:left"> Greater Then</td></tr><tr><td><strong>< </strong></td><td style="text-align:left"> Less Then</td></tr></tbody>';return a["default"].createElement("div",null,a["default"].createElement("div",{style:t},a["default"].createElement("input",{key:e,type:"text",placeholder:"e.g. 3,10-15,>20",className:"form-control input-sm",onChange:this.handleChange,onKeyPress:this.handleKeyPress})),a["default"].createElement("div",{className:"input-sm"},a["default"].createElement("span",{className:"badge",style:n,"data-toggle":"tooltip","data-container":"body","data-html":"true",title:r},"?")))},t}(a["default"].Component);f.propTypes={onChange:a["default"].PropTypes.func.isRequired,column:a["default"].PropTypes.shape(c["default"])},e.exports=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(83),i=r(o),u=n(82),s=r(u),a={NumericFilter:i["default"],AutoCompleteFilter:s["default"]};e.exports=a},function(e,t){"use strict";var n=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return t.filter(function(t){var n=!0;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];if(o.filterValues&&"function"==typeof o.filterValues&&!o.filterValues(t,o,r))n=!1;else if("string"==typeof o.filterTerm){var i=t[r].toString().toLowerCase();i.indexOf(o.filterTerm.toLowerCase())===-1&&(n=!1)}}return n})};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=n(141),u=r(i),s=function(){function e(t,n){o(this,e),this.columns=t.slice(0),this.expandedRows=n}return e.prototype.isRowExpanded=function(e,t){var n=!0,r=this.expandedRows[e];return r&&r[t]&&(n=r[t].isExpanded),n},e.prototype.groupRowsByColumn=function(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?0:arguments[1],r=n,o=[],i=this.columns[n],s=(0,u["default"])(e,i);return Object.keys(s).forEach(function(e){var u=t.isRowExpanded(i,e),a={name:e,__metaData:{isGroup:!0,treeDepth:n,isExpanded:u,columnGroupName:i}};o.push(a),u&&(r=n+1,t.columns.length>r?(o=o.concat(t.groupRowsByColumn(s[e],r)),r=n-1):o=o.concat(s[e]))}),o},e}(),a=function(e,t,n){var r=new s(t,n);return r.groupRowsByColumn(e,0)};e.exports=a},function(e,t){"use strict";var n=function(e,t,n){var r=function(e,r){return"ASC"===n?e[t]>r[t]?1:-1:"DESC"===n?e[t]<r[t]?1:-1:void 0};return"NONE"===n?e:e.sort(r)};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(247),i=n(108),u=r(i),s=n(38),a=r(s),l=n(86),c=n(85),p=n(87),f=function(e){return e.rows},d=function(e){return e.filters},h=(0,o.createSelector)([d,f],function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return!e||(0,u["default"])(e)?t:c(e,t)}),g=function(e){return e.sortColumn},v=function(e){return e.sortDirection},y=(0,o.createSelector)([h,g,v],function(e,t,n){return n||t?p(e,t,n):e}),m=function(e){return e.groupBy},b=function(e){return e.expandedRows},E=(0,o.createSelector)([y,m,b],function(e,t){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return!t||(0,u["default"])(t)||(0,a["default"])(t)?e:l(e,t,n)}),T={getRows:E};e.exports=T},function(e,t,n){"use strict";e.exports={Selectors:n(88)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(1),i=r(o),u=n(216),s=r(u),a=n(31),l=n(36),c=r(l),p=function(e){var t=e.children,n=i["default"].Children.map(t,function(e){return i["default"].cloneElement(e,{draggableHeaderCell:c["default"]})});return i["default"].createElement("div",null,n)};t["default"]=(0,a.DragDropContext)(s["default"])(p)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(90),i=r(o),u=n(36),s=r(u);t["default"]={Container:i["default"],DraggableHeaderCell:s["default"]}},function(e,t,n){"use strict";var r=n(1),o=n(4),i=n(248),u=n(7),s=r.PropTypes.shape({id:r.PropTypes.required,title:r.PropTypes.string}),a=r.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:r.PropTypes.func,options:r.PropTypes.arrayOf(s),label:r.PropTypes.any,value:r.PropTypes.any,height:r.PropTypes.number,valueParams:r.PropTypes.arrayOf(r.PropTypes.string),column:r.PropTypes.shape(u),resultIdentifier:r.PropTypes.string,search:r.PropTypes.string,onKeyDown:r.PropTypes.func,onFocus:r.PropTypes.func,editorDisplayValue:r.PropTypes.func},getDefaultProps:function(){return{resultIdentifier:"id"}},handleChange:function(){this.props.onCommit()},getValue:function(){var e=void 0,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,t},getEditorDisplayValue:function(){var e={title:""},t=this.props,n=t.column,r=t.value,o=t.editorDisplayValue;return o&&"function"==typeof o?e.title=o(n,r):e.title=r,e},getInputNode:function(){return o.findDOMNode(this).getElementsByTagName("input")[0]},getLabel:function(e){var t=null!=this.props.label?this.props.label:"title";return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},constuctValueFromParams:function(e,t){if(!t)return"";for(var n=[],r=0,o=t.length;r<o;r++)n.push(e[t[r]]);return n.join("|")},render:function(){var e=null!=this.props.label?this.props.label:"title";return r.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},r.createElement(i,{search:this.props.search,ref:"autoComplete",label:e,onChange:this.handleChange,onFocus:this.props.onFocus,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:this.getEditorDisplayValue()}))}});e.exports=a},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"CheckboxEditor",propTypes:{value:r.PropTypes.bool,rowIdx:r.PropTypes.number,column:r.PropTypes.shape({key:r.PropTypes.string,onCellChange:r.PropTypes.func}),dependentValues:r.PropTypes.object},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,this.props.dependentValues,e)},render:function(){var e=null!=this.props.value&&this.props.value,t="checkbox"+this.props.rowIdx;return r.createElement("div",{className:"react-grid-checkbox-container",onClick:this.handleChange},r.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:t,checked:e}),r.createElement("label",{htmlFor:t,className:"react-grid-checkbox-label"}))}});e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=n(4),a=r(s),l=n(1),c=n(37),p=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.getInputNode=function(){return a["default"].findDOMNode(this)},t.prototype.onClick=function(){this.getInputNode().focus()},t.prototype.onDoubleClick=function(){this.getInputNode().focus()},t.prototype.render=function(){return l.createElement("select",{style:this.getStyle(),defaultValue:this.props.value,onBlur:this.props.onBlur,onChange:this.onChange},this.renderOptions())},t.prototype.renderOptions=function(){var e=[];return this.props.options.forEach(function(t){"string"==typeof t?e.push(l.createElement("option",{key:t,value:t},t)):e.push(l.createElement("option",{key:t.id,value:t.value,title:t.title},t.text||t.value))},this),e},t}(c);p.propTypes={options:l.PropTypes.arrayOf(l.PropTypes.oneOfType([l.PropTypes.string,l.PropTypes.objectOf({id:l.PropTypes.string,title:l.PropTypes.string,value:l.PropTypes.string,text:l.PropTypes.string})])).isRequired},e.exports=p},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(1),s=n(37),a=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.render=function(){return u.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})},t}(s);e.exports=a},function(e,t,n){"use strict";var r={AutoComplete:n(92),DropDownEditor:n(94),SimpleTextEditor:n(95),CheckboxEditor:n(93)};e.exports=r},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"DropDownFormatter",propTypes:{options:r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.objectOf({id:r.PropTypes.string,title:r.PropTypes.string,value:r.PropTypes.string,text:r.PropTypes.string})])).isRequired,value:r.PropTypes.string.isRequired},shouldComponentUpdate:function(e){return e.value!==this.props.value},render:function(){var e=this.props.value,t=this.props.options.filter(function(t){return t===e||t.value===e})[0];t||(t=e);var n=t.title||t.value||t,o=t.text||t.value||t;return r.createElement("div",{title:n},o)}});e.exports=o},function(e,t,n){"use strict";var r=n(1),o={},i={},u=r.createClass({displayName:"ImageFormatter",propTypes:{value:r.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.value)},componentWillReceiveProps:function(e){e.value!==this.props.value&&(this.setState({value:null}),this._load(e.value))},_load:function(e){var t=e;if(i[t])return void this.setState({value:t});if(o[t])return void o[t].push(this._onLoad);o[t]=[this._onLoad];var n=new Image;n.onload=function(){o[t].forEach(function(e){e(t)}),delete o[t],n.onload=null,t=void 0},n.src=t},_onLoad:function(e){this.isMounted()&&e===this.props.value&&this.setState({value:e})},render:function(){var e=this.state.value?{backgroundImage:"url("+this.state.value+")"}:void 0;return r.createElement("div",{className:"react-grid-image",style:e})}});e.exports=u},function(e,t,n){"use strict";var r=n(98),o=n(97),i={ImageFormatter:r,DropDownFormatter:o};e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=n(60),c=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement(l.ContextMenu,{identifier:"reactDataGridContextMenu"},this.props.children)},t}(a["default"].Component);c.propTypes={children:s.PropTypes.node},t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement("div",{className:"react-context-menu-header"},this.props.children)},t}(a["default"].Component);l.propTypes={children:s.PropTypes.any},t["default"]=l},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.ContextMenuLayer=t.connect=t.SubMenu=t.monitor=t.MenuItem=t.MenuHeader=t.ContextMenu=void 0;var o=n(60),i=n(100),u=r(i),s=n(101),a=r(s);t.ContextMenu=u["default"],t.MenuHeader=a["default"],t.MenuItem=o.MenuItem,t.monitor=o.monitor,t.SubMenu=o.SubMenu,t.connect=o.connect,t.ContextMenuLayer=o.ContextMenuLayer},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l={children:s.PropTypes.array},c={enableAddRow:!0},p=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement("div",{className:"react-grid-Toolbar"},this.props.children,a["default"].createElement("div",{className:"tools"}))},t}(s.Component);p.defaultProps=c,p.propTypes=l,t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e={width:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};return a["default"].createElement("button",{className:"btn grouped-col-btn btn-sm"},a["default"].createElement("span",{style:e},this.props.name),a["default"].createElement("span",{className:"glyphicon glyphicon-trash",style:{"float":"right",paddingLeft:"5px"},onClick:this.props.onColumnGroupDeleted.bind(this,this.props.name)}))},t}(s.Component);t["default"]=l,l.propTypes={name:s.PropTypes.object.isRequired,onColumnGroupDeleted:s.PropTypes.func}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDropTarget:e.dropTarget(),isOver:t.isOver(),canDrop:t.canDrop(),draggedolumn:t.getItem()}}t.__esModule=!0;var a=n(1),l=r(a),c=n(31),p=n(35),f=n(104),d=r(f),h={isOver:a.PropTypes.bool.isRequired,connectDropTarget:a.PropTypes.func,canDrop:a.PropTypes.bool.isRequired,groupBy:a.PropTypes.array,noColumnsSelectedMessage:a.PropTypes.string,panelDescription:a.PropTypes.string,onColumnGroupDeleted:a.PropTypes.func},g={noColumnsSelectedMessage:"Drag a column header here to group by that column",panelDescription:"Drag a column header here to group by that column"},v=function(e){function t(){return o(this,t),i(this,e.call(this))}return u(t,e),t.prototype.getPanelInstructionMessage=function(){var e=this.props.groupBy;return e&&e.length>0?this.props.panelDescription:this.props.noColumnsSelectedMessage},t.prototype.renderGroupedColumns=function(){var e=this;return this.props.groupBy.map(function(t){return l["default"].createElement(d["default"],{name:t,onColumnGroupDeleted:e.props.onColumnGroupDeleted})})},t.prototype.renderOverlay=function(e){return l["default"].createElement("div",{style:{position:"absolute",top:0,left:0,height:"100%",width:"100%",zIndex:1,opacity:.5,backgroundColor:e}})},t.prototype.render=function(){var e=this.props,t=e.connectDropTarget,n=e.isOver,r=e.canDrop;return t(l["default"].createElement("div",{style:{padding:"2px",position:"relative",margin:"-10px",display:"inline-block",border:"1px solid #eee"}},this.renderGroupedColumns()," ",l["default"].createElement("span",null,this.getPanelInstructionMessage()),n&&r&&this.renderOverlay("yellow"),!n&&r&&this.renderOverlay("#DBECFA")))},t}(a.Component);v.defaultProps=g,v.propTypes=h;var y={drop:function(e,t){var n=t.getItem();"function"==typeof e.onColumnGroupAdded&&e.onColumnGroupAdded(n.key)}};t["default"]=(0,c.DropTarget)(p.DragItemTypes.Column,y,s)(v)},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"Toolbar",propTypes:{onAddRow:r.PropTypes.func,onToggleFilter:r.PropTypes.func,enableFilter:r.PropTypes.bool,numberOfRows:r.PropTypes.number,addRowButtonText:r.PropTypes.string,filterRowsButtonText:r.PropTypes.string},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0,addRowButtonText:"Add Row",filterRowsButtonText:"Filter Rows"}},renderAddRowButton:function(){if(this.props.onAddRow)return r.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},this.props.addRowButtonText)},renderToggleFilterButton:function(){if(this.props.enableFilter)return r.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},this.props.filterRowsButtonText)},render:function(){return r.createElement("div",{className:"react-grid-Toolbar"},r.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}});e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.GroupedColumnsPanel=t.AdvancedToolbar=void 0;var o=n(103),i=r(o),u=n(105),s=r(u);t.AdvancedToolbar=i["default"],t.GroupedColumnsPanel=s["default"]},function(e,t){"use strict";function n(e){return 0===Object.keys(e).length&&e.constructor===Object}t.__esModule=!0,t["default"]=n},function(e,t){e.exports=function(e){var t={},n=arguments[1];if("string"==typeof n){n={};for(var r=1;r<arguments.length;r++)n[arguments[r]]=!0}for(var o in e)n[o]||(t[o]=e[o]);return t}},function(e,t,n){function r(){for(var e,t="",n=0;n<arguments.length;n++)if(e=arguments[n])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+r.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,i;"undefined"!=typeof e&&e.exports&&(e.exports=r),o=[],i=function(){return r}.apply(t,o),!(void 0!==i&&(e.exports=i))},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};t.__esModule=!0;var i=n(20),u=r(i),s=function(){function e(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];o(this,e),Array.isArray(n[0])&&1===n.length&&(n=n[0]);for(var i=0;i<n.length;i++)if(!u["default"](n[i]))throw new Error("Expected a disposable");this.disposables=n,this.isDisposed=!1}return e.prototype.add=function(e){this.isDisposed?e.dispose():this.disposables.push(e)},e.prototype.remove=function(e){if(this.isDisposed)return!1;var t=this.disposables.indexOf(e);return t!==-1&&(this.disposables.splice(t,1),e.dispose(),!0)},e.prototype.dispose=function(){if(!this.isDisposed){for(var e=this.disposables.length,t=new Array(e),n=0;n<e;n++)t[n]=this.disposables[n];this.isDisposed=!0,this.disposables=[],this.length=0;for(var n=0;n<e;n++)t[n].dispose()}},e}();t["default"]=s,e.exports=t["default"]},function(e,t){"use strict";var n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t.__esModule=!0;var o=function(){},i=function(){function e(t){n(this,e),this.isDisposed=!1,this.action=t||o}return e.prototype.dispose=function(){this.isDisposed||(this.action.call(null),this.isDisposed=!0)},r(e,null,[{key:"empty",enumerable:!0,value:{dispose:o}}]),e}();t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};t.__esModule=!0;var i=n(20),u=r(i),s=function(){function e(){o(this,e),this.isDisposed=!1,this.current=null}return e.prototype.getDisposable=function(){return this.current},e.prototype.setDisposable=function(){var e=void 0===arguments[0]?null:arguments[0];if(null!=e&&!u["default"](e))throw new Error("Expected either an empty value or a valid disposable");var t=this.isDisposed,n=void 0;t||(n=this.current,this.current=e),n&&n.dispose(),t&&e&&e.dispose()},e.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var e=this.current;this.current=null,e&&e.dispose()}},e}();t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}};t.__esModule=!0;var o=n(20),i=r(o);t.isDisposable=i["default"];var u=n(112),s=r(u);t.Disposable=s["default"];var a=n(111),l=r(a);t.CompositeDisposable=l["default"];var c=n(113),p=r(c);t.SerialDisposable=p["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var u=n(34),s=o(u),a=n(122),l=o(a),c=n(11),p=r(c),f=n(116),d=o(f),h=n(39),g=(o(h),function(){function e(t){i(this,e);var n=s["default"](l["default"]);this.store=n,this.monitor=new d["default"](n),this.registry=this.monitor.registry,this.backend=t(this),n.subscribe(this.handleRefCountChange.bind(this))}return e.prototype.handleRefCountChange=function(){var e=this.store.getState().refCount>0;e&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!e&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1)},e.prototype.getMonitor=function(){return this.monitor},e.prototype.getBackend=function(){return this.backend},e.prototype.getRegistry=function(){return this.registry},e.prototype.getActions=function(){function e(e){
return function(){var r=e.apply(t,arguments);"undefined"!=typeof r&&n(r)}}var t=this,n=this.store.dispatch;return Object.keys(p).filter(function(e){return"function"==typeof p[e]}).reduce(function(t,n){return t[n]=e(p[n]),t},{})},e}());t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var i=n(2),u=r(i),s=n(42),a=r(s),l=n(5),c=r(l),p=n(39),f=r(p),d=n(41),h=n(40),g=function(){function e(t){o(this,e),this.store=t,this.registry=new f["default"](t)}return e.prototype.subscribeToStateChange=function(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=n.handlerIds;u["default"]("function"==typeof e,"listener must be a function."),u["default"]("undefined"==typeof r||c["default"](r),"handlerIds, when specified, must be an array of strings.");var o=this.store.getState().stateId,i=function(){var n=t.store.getState(),i=n.stateId;try{var u=i===o||i===o+1&&!h.areDirty(n.dirtyHandlerIds,r);u||e()}finally{o=i}};return this.store.subscribe(i)},e.prototype.subscribeToOffsetChange=function(e){var t=this;u["default"]("function"==typeof e,"listener must be a function.");var n=this.store.getState().dragOffset,r=function(){var r=t.store.getState().dragOffset;r!==n&&(n=r,e())};return this.store.subscribe(r)},e.prototype.canDragSource=function(e){var t=this.registry.getSource(e);return u["default"](t,"Expected to find a valid source."),!this.isDragging()&&t.canDrag(this,e)},e.prototype.canDropOnTarget=function(e){var t=this.registry.getTarget(e);if(u["default"](t,"Expected to find a valid target."),!this.isDragging()||this.didDrop())return!1;var n=this.registry.getTargetType(e),r=this.getItemType();return a["default"](n,r)&&t.canDrop(this,e)},e.prototype.isDragging=function(){return Boolean(this.getItemType())},e.prototype.isDraggingSource=function(e){var t=this.registry.getSource(e,!0);if(u["default"](t,"Expected to find a valid source."),!this.isDragging()||!this.isSourcePublic())return!1;var n=this.registry.getSourceType(e),r=this.getItemType();return n===r&&t.isDragging(this,e)},e.prototype.isOverTarget=function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.shallow,r=void 0!==n&&n;if(!this.isDragging())return!1;var o=this.registry.getTargetType(e),i=this.getItemType();if(!a["default"](o,i))return!1;var u=this.getTargetIds();if(!u.length)return!1;var s=u.indexOf(e);return r?s===u.length-1:s>-1},e.prototype.getItemType=function(){return this.store.getState().dragOperation.itemType},e.prototype.getItem=function(){return this.store.getState().dragOperation.item},e.prototype.getSourceId=function(){return this.store.getState().dragOperation.sourceId},e.prototype.getTargetIds=function(){return this.store.getState().dragOperation.targetIds},e.prototype.getDropResult=function(){return this.store.getState().dragOperation.dropResult},e.prototype.didDrop=function(){return this.store.getState().dragOperation.didDrop},e.prototype.isSourcePublic=function(){return this.store.getState().dragOperation.isSourcePublic},e.prototype.getInitialClientOffset=function(){return this.store.getState().dragOffset.initialClientOffset},e.prototype.getInitialSourceClientOffset=function(){return this.store.getState().dragOffset.initialSourceClientOffset},e.prototype.getClientOffset=function(){return this.store.getState().dragOffset.clientOffset},e.prototype.getSourceClientOffset=function(){return d.getSourceClientOffset(this.store.getState().dragOffset)},e.prototype.getDifferenceFromInitialOffset=function(){return d.getDifferenceFromInitialOffset(this.store.getState().dragOffset)},e}();t["default"]=g,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(){n(this,e)}return e.prototype.canDrag=function(){return!0},e.prototype.isDragging=function(e,t){return t===e.getSourceId()},e.prototype.endDrag=function(){},e}();t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(){n(this,e)}return e.prototype.canDrop=function(){return!0},e.prototype.hover=function(){},e.prototype.drop=function(){},e}();t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new a(e)}t.__esModule=!0,t["default"]=i;var u=n(58),s=r(u),a=function(){function e(t){o(this,e),this.actions=t.getActions()}return e.prototype.setup=function(){this.didCallSetup=!0},e.prototype.teardown=function(){this.didCallTeardown=!0},e.prototype.connectDragSource=function(){return s["default"]},e.prototype.connectDragPreview=function(){return s["default"]},e.prototype.connectDropTarget=function(){return s["default"]},e.prototype.simulateBeginDrag=function(e,t){this.actions.beginDrag(e,t)},e.prototype.simulatePublishDragSource=function(){this.actions.publishDragSource()},e.prototype.simulateHover=function(e,t){this.actions.hover(e,t)},e.prototype.simulateDrop=function(){this.actions.drop()},e.prototype.simulateEndDrag=function(){this.actions.endDrag()},e}();e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e["default"]:e}t.__esModule=!0;var o=n(115);t.DragDropManager=r(o);var i=n(117);t.DragSource=r(i);var u=n(118);t.DropTarget=r(u);var s=n(119);t.createTestBackend=r(s)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){switch(void 0===e&&(e=c),t.type){case u.BEGIN_DRAG:return i({},e,{itemType:t.itemType,item:t.item,sourceId:t.sourceId,isSourcePublic:t.isSourcePublic,dropResult:null,didDrop:!1});case u.PUBLISH_DRAG_SOURCE:return i({},e,{isSourcePublic:!0});case u.HOVER:return i({},e,{targetIds:t.targetIds});case s.REMOVE_TARGET:return e.targetIds.indexOf(t.targetId)===-1?e:i({},e,{targetIds:l["default"](e.targetIds,t.targetId)});case u.DROP:return i({},e,{dropResult:t.dropResult,didDrop:!0,targetIds:[]});case u.END_DRAG:return i({},e,{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o;var u=n(11),s=n(12),a=n(59),l=r(a),c={itemType:null,item:null,sourceId:null,targetIds:[],dropResult:null,didDrop:!1,isSourcePublic:null};e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(41),i=r(o),u=n(121),s=r(u),a=n(123),l=r(a),c=n(40),p=r(c),f=n(124),d=r(f);t["default"]=function(e,t){return void 0===e&&(e={}),{dirtyHandlerIds:p["default"](e.dirtyHandlerIds,t,e.dragOperation),dragOffset:i["default"](e.dragOffset,t),refCount:l["default"](e.refCount,t),dragOperation:s["default"](e.dragOperation,t),stateId:d["default"](e.stateId)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t){switch(void 0===e&&(e=0),t.type){case o.ADD_SOURCE:case o.ADD_TARGET:return e+1;case o.REMOVE_SOURCE:case o.REMOVE_TARGET:return e-1;default:return e}}t.__esModule=!0,t["default"]=r;var o=n(12);e.exports=t["default"]},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?0:arguments[0];return e+1}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(){return r++}t.__esModule=!0,t["default"]=n;var r=0;e.exports=t["default"]},function(e,t,n){"use strict";function r(){var e=void 0===arguments[0]?document:arguments[0];try{return e.activeElement}catch(t){}}var o=n(44);t.__esModule=!0,t["default"]=r;var i=n(21);o.interopRequireDefault(i);e.exports=t["default"]},function(e,t,n){"use strict";var r=n(43);e.exports=function(e,t){e.classList?e.classList.add(t):r(e)||(e.className=e.className+" "+t)}},function(e,t,n){"use strict";e.exports={addClass:n(127),removeClass:n(129),hasClass:n(43)}},function(e,t){"use strict";e.exports=function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}},function(e,t,n){"use strict";var r=n(8),o=function(){};r&&(o=function(){return document.addEventListener?function(e,t,n,r){return e.removeEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.detachEvent("on"+t,n)}:void 0}()),e.exports=o},function(e,t,n){"use strict";var r=n(8),o=function(){};r&&(o=function(){return document.addEventListener?function(e,t,n,r){return e.addEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.attachEvent("on"+t,n)}:void 0}()),e.exports=o},function(e,t,n){"use strict";var r=n(8),o=function(){var e=r&&document.documentElement;return e&&e.contains?function(e,t){return e.contains(t)}:e&&e.compareDocumentPosition?function(e,t){return e===t||!!(16&e.compareDocumentPosition(t))}:function(e,t){if(t)do if(t===e)return!0;while(t=t.parentNode);return!1}}();e.exports=o},function(e,t){"use strict";e.exports=function(e){return e===e.window?e:9===e.nodeType&&(e.defaultView||e.parentWindow)}},function(e,t,n){"use strict";var r=n(44),o=n(45),i=r.interopRequireDefault(o),u=/^(top|right|bottom|left)$/,s=/^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;e.exports=function(e){if(!e)throw new TypeError("No Element passed to `getComputedStyle()`");var t=e.ownerDocument;return"defaultView"in t?t.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):window.getComputedStyle(e,null):{getPropertyValue:function(t){var n=e.style;t=(0,i["default"])(t),"float"==t&&(t="styleFloat");var r=e.currentStyle[t]||null;if(null==r&&n&&n[t]&&(r=n[t]),s.test(r)&&!u.test(t)){var o=n.left,a=e.runtimeStyle,l=a&&a.left;l&&(a.left=e.currentStyle.left),n.left="fontSize"===t?"1em":r,r=n.pixelLeft+"px",n.left=o,l&&(a.left=l)}return r}}}},function(e,t,n){"use strict";var r=n(45),o=n(139),i=n(134),u=n(136),s=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var a="",l=t;if("string"==typeof t){if(void 0===n)return e.style[r(t)]||i(e).getPropertyValue(o(t));(l={})[t]=n}for(var c in l)s.call(l,c)&&(l[c]||0===l[c]?a+=o(c)+":"+l[c]+";":u(e,o(c)));e.style.cssText+=";"+a}},function(e,t){"use strict";e.exports=function(e,t){return"removeProperty"in e.style?e.style.removeProperty(t):e.style.removeAttribute(t)}},function(e,t){"use strict";var n=/-(.)/g;e.exports=function(e){return e.replace(n,function(e,t){return t.toUpperCase()})}},function(e,t){"use strict";var n=/([A-Z])/g;e.exports=function(e){return e.replace(n,"-$1").toLowerCase()}},function(e,t,n){"use strict";var r=n(138),o=/^ms-/;e.exports=function(e){return r(e).replace(o,"-ms-")}},function(e,t,n){"use strict";var r,o=n(8);e.exports=function(e){if((!r||e)&&o){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),r=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return r}},function(e,t,n){(function(e){function n(e,t,n,r){for(var o=-1,i=e?e.length:0;++o<i;){var u=e[o];t(r,u,n(u),e)}return r}function r(e,t){for(var n=-1,r=e?e.length:0;++n<r;)if(t(e[n],n,e))return!0;return!1}function o(e){return function(t){return null==t?void 0:t[e]}}function i(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function u(e){return function(t){return e(t)}}function s(e,t){return null==e?void 0:e[t]}function a(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function l(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function c(e,t){return function(n){return e(t(n))}}function p(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}function f(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function d(){this.__data__=rn?rn(null):{}}function h(e){return this.has(e)&&delete this.__data__[e]}function g(e){var t=this.__data__;if(rn){var n=t[e];return n===He?void 0:n}return Wt.call(t,e)?t[e]:void 0}function v(e){var t=this.__data__;return rn?void 0!==t[e]:Wt.call(t,e)}function y(e,t){var n=this.__data__;return n[e]=rn&&void 0===t?He:t,this}function m(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function b(){this.__data__=[]}function E(e){var t=this.__data__,n=B(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Yt.call(t,n,1),!0}function T(e){var t=this.__data__,n=B(t,e);return n<0?void 0:t[n][1]}function _(e){return B(this.__data__,e)>-1}function D(e,t){var n=this.__data__,r=B(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}function w(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function C(){this.__data__={hash:new f,map:new(Zt||m),string:new f}}function O(e){return le(this,e)["delete"](e)}function x(e){return le(this,e).get(e)}function S(e){return le(this,e).has(e)}function P(e,t){return le(this,e).set(e,t),this}function M(e){var t=-1,n=e?e.length:0;for(this.__data__=new w;++t<n;)this.add(e[t])}function A(e){return this.__data__.set(e,He),this}function I(e){return this.__data__.has(e)}function R(e){this.__data__=new m(e)}function F(){this.__data__=new m}function j(e){return this.__data__["delete"](e)}function N(e){return this.__data__.get(e)}function k(e){return this.__data__.has(e)}function V(e,t){var n=this.__data__;if(n instanceof m){var r=n.__data__;if(!Zt||r.length<Le-1)return r.push([e,t]),this;n=this.__data__=new w(r)}return n.set(e,t),this}function B(e,t){for(var n=e.length;n--;)if(we(e[n][0],t))return n;return-1}function L(e,t,n,r){return dn(e,function(e,o,i){t(r,e,n(e),i)}),r}function U(e,t){return e&&hn(e,t,ke)}function H(e,t){t=ge(t,e)?[t]:ne(t);for(var n=0,r=t.length;null!=e&&n<r;)e=e[Te(t[n++])];return n&&n==r?e:void 0}function W(e){return qt.call(e)}function q(e,t){return null!=e&&(Wt.call(e,t)||"object"==typeof e&&t in e&&null===yn(e))}function G(e,t){return null!=e&&t in Object(e)}function z(e,t,n,r,o){return e===t||(null==e||null==t||!Me(e)&&!Ae(t)?e!==e&&t!==t:K(e,t,z,n,r,o))}function K(e,t,n,r,o,i){var u=Tn(e),s=Tn(t),l=$e,c=$e;u||(l=mn(e),l=l==Ke?nt:l),s||(c=mn(t),c=c==Ke?nt:c);var p=l==nt&&!a(e),f=c==nt&&!a(t),d=l==c;if(d&&!p)return i||(i=new R),u||_n(e)?ue(e,t,n,r,o,i):se(e,t,l,n,r,o,i);if(!(o&qe)){var h=p&&Wt.call(e,"__wrapped__"),g=f&&Wt.call(t,"__wrapped__");if(h||g){var v=h?e.value():e,y=g?t.value():t;return i||(i=new R),n(v,y,r,o,i)}}return!!d&&(i||(i=new R),ae(e,t,n,r,o,i))}function $(e,t,n,r){var o=n.length,i=o,u=!r;if(null==e)return!i;for(e=Object(e);o--;){var s=n[o];if(u&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++o<i;){s=n[o];var a=s[0],l=e[a],c=s[1];if(u&&s[2]){if(void 0===l&&!(a in e))return!1}else{var p=new R;if(r)var f=r(l,c,a,e,t,p);if(!(void 0===f?z(c,l,r,We|qe,p):f))return!1}}return!0}function Y(e){if(!Me(e)||ye(e))return!1;var t=Se(e)||a(e)?Gt:Ot;return t.test(_e(e))}function X(e){return Ae(e)&&Pe(e.length)&&!!St[qt.call(e)]}function Q(e){return"function"==typeof e?e:null==e?Ve:"object"==typeof e?Tn(e)?Z(e[0],e[1]):J(e):Be(e)}function J(e){var t=ce(e);return 1==t.length&&t[0][2]?Ee(t[0][0],t[0][1]):function(n){return n===e||$(n,e,t)}}function Z(e,t){return ge(e)&&be(t)?Ee(Te(e),t):function(n){var r=je(n,e);return void 0===r&&r===t?Ne(n,e):z(t,r,void 0,We|qe)}}function ee(e){return function(t){return H(t,e)}}function te(e){if("string"==typeof e)return e;if(Re(e))return fn?fn.call(e):"";var t=e+"";return"0"==t&&1/e==-Ge?"-0":t}function ne(e){return Tn(e)?e:bn(e)}function re(e,t){return function(r,o){var i=Tn(r)?n:L,u=t?t():{};return i(r,e,Q(o,2),u)}}function oe(e,t){return function(n,r){if(null==n)return n;if(!Oe(n))return e(n,r);for(var o=n.length,i=t?o:-1,u=Object(n);(t?i--:++i<o)&&r(u[i],i,u)!==!1;);return n}}function ie(e){return function(t,n,r){for(var o=-1,i=Object(t),u=r(t),s=u.length;s--;){var a=u[e?s:++o];if(n(i[a],a,i)===!1)break}return t}}function ue(e,t,n,o,i,u){var s=i&qe,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return!1;var c=u.get(e);if(c&&u.get(t))return c==t;var p=-1,f=!0,d=i&We?new M:void 0;for(u.set(e,t),u.set(t,e);++p<a;){var h=e[p],g=t[p];if(o)var v=s?o(g,h,p,t,e,u):o(h,g,p,e,t,u);if(void 0!==v){if(v)continue;f=!1;break}if(d){if(!r(t,function(e,t){if(!d.has(t)&&(h===e||n(h,e,o,i,u)))return d.add(t)})){f=!1;break}}else if(h!==g&&!n(h,g,o,i,u)){f=!1;break}}return u["delete"](e),u["delete"](t),f}function se(e,t,n,r,o,i,u){switch(n){case ct:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case lt:return!(e.byteLength!=t.byteLength||!r(new Kt(e),new Kt(t)));case Ye:case Xe:case tt:return we(+e,+t);case Qe:return e.name==t.name&&e.message==t.message;case ot:case ut:return e==t+"";case et:var s=l;case it:var a=i&qe;if(s||(s=p),e.size!=t.size&&!a)return!1;var c=u.get(e);if(c)return c==t;i|=We,u.set(e,t);var f=ue(s(e),s(t),r,o,i,u);return u["delete"](e),f;case st:if(pn)return pn.call(e)==pn.call(t)}return!1}function ae(e,t,n,r,o,i){var u=o&qe,s=ke(e),a=s.length,l=ke(t),c=l.length;if(a!=c&&!u)return!1;for(var p=a;p--;){var f=s[p];if(!(u?f in t:q(t,f)))return!1}var d=i.get(e);if(d&&i.get(t))return d==t;var h=!0;i.set(e,t),i.set(t,e);for(var g=u;++p<a;){f=s[p];var v=e[f],y=t[f];if(r)var m=u?r(y,v,f,t,e,i):r(v,y,f,e,t,i);if(!(void 0===m?v===y||n(v,y,r,o,i):m)){h=!1;break}g||(g="constructor"==f)}if(h&&!g){var b=e.constructor,E=t.constructor;b!=E&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof E&&E instanceof E)&&(h=!1)}return i["delete"](e),i["delete"](t),h}function le(e,t){var n=e.__data__;return ve(t)?n["string"==typeof t?"string":"hash"]:n.map}function ce(e){for(var t=ke(e),n=t.length;n--;){var r=t[n],o=e[r];t[n]=[r,o,be(o)]}return t}function pe(e,t){var n=s(e,t);return Y(n)?n:void 0}function fe(e,t,n){t=ge(t,e)?[t]:ne(t);for(var r,o=-1,i=t.length;++o<i;){var u=Te(t[o]);if(!(r=null!=e&&n(e,u)))break;e=e[u]}if(r)return r;var i=e?e.length:0;return!!i&&Pe(i)&&he(u,i)&&(Tn(e)||Ie(e)||Ce(e))}function de(e){var t=e?e.length:void 0;return Pe(t)&&(Tn(e)||Ie(e)||Ce(e))?i(t,String):null}function he(e,t){return t=null==t?ze:t,!!t&&("number"==typeof e||xt.test(e))&&e>-1&&e%1==0&&e<t}function ge(e,t){if(Tn(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Re(e))||(Tt.test(e)||!Et.test(e)||null!=t&&e in Object(t))}function ve(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function ye(e){return!!Ut&&Ut in e}function me(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||Bt;return e===n}function be(e){return e===e&&!Me(e)}function Ee(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}function Te(e){if("string"==typeof e||Re(e))return e;var t=e+"";return"0"==t&&1/e==-Ge?"-0":t}function _e(e){if(null!=e){try{return Ht.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function De(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(Ue);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var u=e.apply(this,r);return n.cache=i.set(o,u),u};return n.cache=new(De.Cache||w),n}function we(e,t){return e===t||e!==e&&t!==t}function Ce(e){return xe(e)&&Wt.call(e,"callee")&&(!$t.call(e,"callee")||qt.call(e)==Ke)}function Oe(e){return null!=e&&Pe(vn(e))&&!Se(e)}function xe(e){return Ae(e)&&Oe(e)}function Se(e){var t=Me(e)?qt.call(e):"";return t==Je||t==Ze}function Pe(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=ze}function Me(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ae(e){return!!e&&"object"==typeof e}function Ie(e){return"string"==typeof e||!Tn(e)&&Ae(e)&&qt.call(e)==ut}function Re(e){return"symbol"==typeof e||Ae(e)&&qt.call(e)==st}function Fe(e){return null==e?"":te(e)}function je(e,t,n){var r=null==e?void 0:H(e,t);return void 0===r?n:r}function Ne(e,t){return null!=e&&fe(e,t,G)}function ke(e){var t=me(e);if(!t&&!Oe(e))return gn(e);var n=de(e),r=!!n,o=n||[],i=o.length;for(var u in e)!q(e,u)||r&&("length"==u||he(u,i))||t&&"constructor"==u||o.push(u);return o}function Ve(e){return e}function Be(e){return ge(e)?o(Te(e)):ee(e)}var Le=200,Ue="Expected a function",He="__lodash_hash_undefined__",We=1,qe=2,Ge=1/0,ze=9007199254740991,Ke="[object Arguments]",$e="[object Array]",Ye="[object Boolean]",Xe="[object Date]",Qe="[object Error]",Je="[object Function]",Ze="[object GeneratorFunction]",et="[object Map]",tt="[object Number]",nt="[object Object]",rt="[object Promise]",ot="[object RegExp]",it="[object Set]",ut="[object String]",st="[object Symbol]",at="[object WeakMap]",lt="[object ArrayBuffer]",ct="[object DataView]",pt="[object Float32Array]",ft="[object Float64Array]",dt="[object Int8Array]",ht="[object Int16Array]",gt="[object Int32Array]",vt="[object Uint8Array]",yt="[object Uint8ClampedArray]",mt="[object Uint16Array]",bt="[object Uint32Array]",Et=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Tt=/^\w*$/,_t=/^\./,Dt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,wt=/[\\^$.*+?()[\]{}|]/g,Ct=/\\(\\)?/g,Ot=/^\[object .+?Constructor\]$/,xt=/^(?:0|[1-9]\d*)$/,St={};St[pt]=St[ft]=St[dt]=St[ht]=St[gt]=St[vt]=St[yt]=St[mt]=St[bt]=!0,St[Ke]=St[$e]=St[lt]=St[Ye]=St[ct]=St[Xe]=St[Qe]=St[Je]=St[et]=St[tt]=St[nt]=St[ot]=St[it]=St[ut]=St[at]=!1;var Pt="object"==typeof window&&window&&window.Object===Object&&window,Mt="object"==typeof self&&self&&self.Object===Object&&self,At=Pt||Mt||Function("return this")(),It="object"==typeof t&&t&&!t.nodeType&&t,Rt=It&&"object"==typeof e&&e&&!e.nodeType&&e,Ft=Rt&&Rt.exports===It,jt=Ft&&Pt.process,Nt=function(){try{return jt&&jt.binding("util")}catch(e){}}(),kt=Nt&&Nt.isTypedArray,Vt=Array.prototype,Bt=Object.prototype,Lt=At["__core-js_shared__"],Ut=function(){var e=/[^.]+$/.exec(Lt&&Lt.keys&&Lt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),Ht=Function.prototype.toString,Wt=Bt.hasOwnProperty,qt=Bt.toString,Gt=RegExp("^"+Ht.call(Wt).replace(wt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),zt=At.Symbol,Kt=At.Uint8Array,$t=Bt.propertyIsEnumerable,Yt=Vt.splice,Xt=Object.getPrototypeOf,Qt=Object.keys,Jt=pe(At,"DataView"),Zt=pe(At,"Map"),en=pe(At,"Promise"),tn=pe(At,"Set"),nn=pe(At,"WeakMap"),rn=pe(Object,"create"),on=_e(Jt),un=_e(Zt),sn=_e(en),an=_e(tn),ln=_e(nn),cn=zt?zt.prototype:void 0,pn=cn?cn.valueOf:void 0,fn=cn?cn.toString:void 0;f.prototype.clear=d,f.prototype["delete"]=h,f.prototype.get=g,f.prototype.has=v,f.prototype.set=y,m.prototype.clear=b,m.prototype["delete"]=E,m.prototype.get=T,m.prototype.has=_,m.prototype.set=D,w.prototype.clear=C,w.prototype["delete"]=O,w.prototype.get=x,w.prototype.has=S,w.prototype.set=P,M.prototype.add=M.prototype.push=A,M.prototype.has=I,R.prototype.clear=F,R.prototype["delete"]=j,R.prototype.get=N,R.prototype.has=k,R.prototype.set=V;var dn=oe(U),hn=ie(),gn=c(Qt,Object),vn=o("length"),yn=c(Xt,Object),mn=W;(Jt&&mn(new Jt(new ArrayBuffer(1)))!=ct||Zt&&mn(new Zt)!=et||en&&mn(en.resolve())!=rt||tn&&mn(new tn)!=it||nn&&mn(new nn)!=at)&&(mn=function(e){var t=qt.call(e),n=t==nt?e.constructor:void 0,r=n?_e(n):void 0;if(r)switch(r){case on:return ct;case un:return et;case sn:return rt;case an:return it;case ln:return at}return t});var bn=De(function(e){e=Fe(e);var t=[];return _t.test(e)&&t.push(""),e.replace(Dt,function(e,n,r,o){t.push(r?o.replace(Ct,"$1"):n||e)}),t}),En=re(function(e,t,n){Wt.call(e,n)?e[n].push(t):e[n]=[t]});De.Cache=w;var Tn=Array.isArray,_n=kt?u(kt):X;e.exports=En}).call(t,n(252)(e))},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(169),i=n(170),u=n(171),s=n(172),a=n(173);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(179),i=n(180),u=n(181),s=n(182),a=n(183);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t,n){var r=n(27),o=n(16),i=r(o,"Map");e.exports=i},function(e,t,n){var r=n(27),o=n(16),i=r(o,"Set");e.exports=i},function(e,t,n){var r=n(16),o=r.Symbol;e.exports=o},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0,o=0,i=[];++n<r;){var u=e[n];t(u,n,e)&&(i[o++]=u)}return i}e.exports=n},function(e,t,n){function r(e,t){var n=u(e)||i(e)?o(e.length,String):[],r=n.length,a=!!r;for(var c in e)!t&&!l.call(e,c)||a&&("length"==c||s(c,r))||n.push(c);return n}var o=n(159),i=n(55),u=n(5),s=n(53),a=Object.prototype,l=a.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t,n,r){return void 0===e||o(e,i[n])&&!u.call(r,n)?t:e}var o=n(17),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t,n){var r=e[t];u.call(e,t)&&o(r,n)&&(void 0!==n||t in e)||(e[t]=n)}var o=n(17),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t){function n(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}e.exports=n},function(e,t,n){function r(e,t,n,u,s){var a=-1,l=e.length;for(n||(n=i),s||(s=[]);++a<l;){var c=e[a];t>0&&n(c)?t>1?r(c,t-1,n,u,s):o(s,c):u||(s[s.length]=c)}return s}var o=n(48),i=n(174);e.exports=r},function(e,t,n){function r(e,t,n){if(t!==t)return o(e,i,n);for(var r=n-1,u=e.length;++r<u;)if(e[r]===t)return r;return-1}var o=n(152),i=n(156);e.exports=r},function(e,t,n){function r(e,t,n){for(var r=n?u:i,p=e[0].length,f=e.length,d=f,h=Array(f),g=1/0,v=[];d--;){var y=e[d];d&&t&&(y=s(y,a(t))),g=c(y.length,g),h[d]=!n&&(t||p>=120&&y.length>=120)?new o(d&&y):void 0}y=e[0];var m=-1,b=h[0];e:for(;++m<p&&v.length<g;){var E=y[m],T=t?t(E):E;if(E=n||0!==E?E:0,!(b?l(b,T):r(v,T,n))){for(d=f;--d;){var _=h[d];if(!(_?l(_,T):r(e[d],T,n)))continue e}b&&b.push(T),v.push(E)}}return v}var o=n(22),i=n(23),u=n(24),s=n(25),a=n(50),l=n(26),c=Math.min;e.exports=r},function(e,t){function n(e){return e!==e}e.exports=n},function(e,t,n){function r(e){if(!s(e)||u(e))return!1;var t=o(e)||i(e)?g:c;return t.test(a(e))}var o=n(56),i=n(52),u=n(177),s=n(10),a=n(193),l=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,p=Function.prototype,f=Object.prototype,d=p.toString,h=f.hasOwnProperty,g=RegExp("^"+d.call(h).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){if(!o(e))return u(e);var t=i(e),n=[];for(var r in e)("constructor"!=r||!t&&a.call(e,r))&&n.push(r);return n}var o=n(10),i=n(178),u=n(189),s=Object.prototype,a=s.hasOwnProperty;e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}e.exports=n},function(e,t,n){function r(e,t,n){for(var r=-1,s=e.length;++r<s;)var a=a?o(i(a,e[r],t,n),i(e[r],a,t,n)):e[r];return a&&a.length?u(a,t,n):[]}var o=n(48),i=n(49),u=n(51);e.exports=r},function(e,t,n){function r(e){return o(e)?e:[]}var o=n(9);e.exports=r},function(e,t,n){function r(e,t,n,r){n||(n={});for(var i=-1,u=t.length;++i<u;){var s=t[i],a=r?r(n[s],e[s],s,n,e):void 0;o(n,s,void 0===a?e[s]:a)}return n}var o=n(151);e.exports=r},function(e,t,n){var r=n(16),o=r["__core-js_shared__"];e.exports=o},function(e,t,n){function r(e){return o(function(t,n){var r=-1,o=n.length,u=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(u=e.length>3&&"function"==typeof u?(o--,u):void 0,s&&i(n[0],n[1],s)&&(u=o<3?void 0:u,o=1),t=Object(t);++r<o;){var a=n[r];a&&e(t,a,r,u)}return t})}var o=n(6),i=n(175);e.exports=r},function(e,t,n){var r=n(146),o=n(58),i=n(54),u=1/0,s=r&&1/i(new r([,-0]))[1]==u?function(e){return new r(e)}:o;e.exports=s},function(e,t,n){var r="object"==typeof window&&window&&window.Object===Object&&window;e.exports=r},function(e,t,n){var r=n(190),o=r(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function n(e,t){return null==e?void 0:e[t]}e.exports=n},function(e,t,n){function r(){this.__data__=o?o(null):{}}var o=n(15);e.exports=r},function(e,t){function n(e){return this.has(e)&&delete this.__data__[e]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__;if(o){var n=t[e];return n===i?void 0:n}return s.call(t,e)?t[e]:void 0}var o=n(15),i="__lodash_hash_undefined__",u=Object.prototype,s=u.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){var t=this.__data__;return o?void 0!==t[e]:u.call(t,e)}var o=n(15),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__;return n[e]=o&&void 0===t?i:t,this}var o=n(15),i="__lodash_hash_undefined__";e.exports=r},function(e,t,n){function r(e){return u(e)||i(e)||!!(s&&e&&e[s])}var o=n(147),i=n(55),u=n(5),s=o?o.isConcatSpreadable:void 0;e.exports=r},function(e,t,n){function r(e,t,n){if(!s(n))return!1;var r=typeof t;return!!("number"==r?i(n)&&u(t,n.length):"string"==r&&t in n)&&o(n[t],e)}var o=n(17),i=n(28),u=n(53),s=n(10);e.exports=r},function(e,t){function n(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=n},function(e,t,n){function r(e){return!!i&&i in e}var o=n(163),i=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=r},function(e,t){function n(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||r;return e===n}var r=Object.prototype;e.exports=n},function(e,t){function n(){this.__data__=[]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():u.call(t,n,1),!0}var o=n(13),i=Array.prototype,u=i.splice;e.exports=r},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return n<0?void 0:t[n][1]}var o=n(13);e.exports=r},function(e,t,n){function r(e){return o(this.__data__,e)>-1}var o=n(13);e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__,r=o(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}var o=n(13);e.exports=r},function(e,t,n){function r(){this.__data__={hash:new o,map:new(u||i),string:new o}}var o=n(143),i=n(144),u=n(145);e.exports=r},function(e,t,n){function r(e){return o(this,e)["delete"](e)}var o=n(14);e.exports=r},function(e,t,n){function r(e){return o(this,e).get(e)}var o=n(14);e.exports=r},function(e,t,n){function r(e){return o(this,e).has(e)}var o=n(14);e.exports=r},function(e,t,n){function r(e,t){return o(this,e).set(e,t),this}var o=n(14);e.exports=r},function(e,t){function n(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}e.exports=n},function(e,t){function n(e,t){return function(n){return e(t(n))}}e.exports=n},function(e,t){function n(e){return this.__data__.set(e,r),this}var r="__lodash_hash_undefined__";e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t){function n(e){if(null!=e){try{return o.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var r=Function.prototype,o=r.toString;e.exports=n},function(e,t,n){var r=n(162),o=n(164),i=n(198),u=o(function(e,t,n,o){r(t,i(t),e,o)});e.exports=u},function(e,t,n){var r=n(47),o=n(150),i=n(194),u=n(6),s=u(function(e){return e.push(void 0,o),r(i,void 0,e)});e.exports=s},function(e,t,n){var r=n(25),o=n(155),i=n(6),u=n(161),s=i(function(e){var t=r(e,u);return t.length&&t[0]===e[0]?o(t):[]});e.exports=s},function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=r}var r=9007199254740991;e.exports=n},function(e,t,n){function r(e){return u(e)?o(e,!0):i(e)}var o=n(149),i=n(158),u=n(28);e.exports=r},function(e,t,n){function r(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);
var u=e.apply(this,r);return n.cache=i.set(o,u),u};return n.cache=new(r.Cache||o),n}var o=n(46),i="Expected a function";r.Cache=o,e.exports=r},function(e,t,n){var r=n(153),o=n(6),i=n(51),u=n(9),s=o(function(e){return i(r(e,1,u,!0))});e.exports=s},function(e,t,n){var r=n(148),o=n(6),i=n(160),u=n(9),s=o(function(e){return i(r(e,u))});e.exports=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=function(e){var t=e.displayName||e.name||"Component";return u["default"].createClass({displayName:"ContextMenuConnector("+t+")",getInitialState:function(){return{item:a["default"].getState().currentItem}},componentDidMount:function(){this.unsubscribe=a["default"].subscribe(this.handleUpdate)},componentWillUnmount:function(){this.unsubscribe()},handleUpdate:function(){this.setState(this.getInitialState())},render:function(){return u["default"].createElement(e,o({},this.props,{item:this.state.item}))}})};var i=n(1),u=r(i),s=n(18),a=r(s)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(18),a=r(s),l=n(204),c=r(l),p=u["default"].PropTypes,f=u["default"].createClass({displayName:"ContextMenu",propTypes:{identifier:p.string.isRequired},getInitialState:function(){return a["default"].getState()},componentDidMount:function(){this.unsubscribe=a["default"].subscribe(this.handleUpdate)},componentWillUnmount:function(){this.unsubscribe&&this.unsubscribe()},handleUpdate:function(){this.setState(this.getInitialState())},render:function(){return u["default"].createElement(c["default"],o({},this.props,this.state))}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(29),a=r(s),l=n(232),c=r(l),p={position:"fixed",zIndex:1040,top:0,bottom:0,left:0,right:0},f=o({},p,{zIndex:"auto",backgroundColor:"transparent"}),d={position:"fixed",zIndex:"auto"},h=u["default"].createClass({displayName:"ContextMenuWrapper",getInitialState:function(){return{left:0,top:0}},componentWillReceiveProps:function(e){var t=this;if(e.isVisible===e.identifier){var n=window.requestAnimationFrame||setTimeout;n(function(){t.setState(t.getMenuPosition(e.x,e.y)),t.menu.parentNode.addEventListener("contextmenu",t.hideMenu)})}},shouldComponentUpdate:function(e){return this.props.isVisible!==e.visible},hideMenu:function(e){e.preventDefault(),this.menu.parentNode.removeEventListener("contextmenu",this.hideMenu),a["default"].hideMenu()},getMenuPosition:function(e,t){var n=document.documentElement.scrollTop,r=document.documentElement.scrollLeft,o=window,i=o.innerWidth,u=o.innerHeight,s=this.menu.getBoundingClientRect(),a={top:t+r,left:e+n};return t+s.height>u&&(a.top-=s.height),e+s.width>i&&(a.left-=s.width),a},render:function(){var e=this,t=this.props,n=t.isVisible,r=t.identifier,i=t.children,s=o({},d,this.state);return u["default"].createElement(c["default"],{style:p,backdropStyle:f,show:n===r,onHide:function(){return a["default"].hideMenu()}},u["default"].createElement("nav",{ref:function(t){return e.menu=t},style:s,className:"react-context-menu"},i))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=function(e,t){return function(n){var r=n.displayName||n.name||"Component";return(0,l["default"])(e&&("string"==typeof e||"symbol"===("undefined"==typeof e?"undefined":i(e))||"function"==typeof e),"Expected identifier to be string, symbol or function. See %s",r),t&&(0,l["default"])("function"==typeof t,"Expected configure to be a function. See %s",r),s["default"].createClass({displayName:r+"ContextMenuLayer",getDefaultProps:function(){return{renderTag:"div",attributes:{}}},mouseDown:!1,handleMouseDown:function(e){var t=this;this.props.holdToDisplay>=0&&0===e.button&&(e.persist(),this.mouseDown=!0,setTimeout(function(){t.mouseDown&&t.handleContextClick(e)},this.props.holdToDisplay))},handleTouchstart:function(e){var t=this;e.persist(),this.mouseDown=!0,setTimeout(function(){t.mouseDown&&t.handleContextClick(e)},this.props.holdToDisplay)},handleTouchEnd:function(e){e.preventDefault(),this.mouseDown=!1},handleMouseUp:function(e){0===e.button&&(this.mouseDown=!1)},handleContextClick:function(n){var o="function"==typeof t?t(this.props):{};(0,l["default"])((0,p["default"])(o),"Expected configure to return an object. See %s",r),n.preventDefault();var i=n.clientX||n.touches&&n.touches[0].pageX,u=n.clientY||n.touches&&n.touches[0].pageY;d["default"].dispatch({type:"SET_PARAMS",data:{x:i,y:u,currentItem:o,isVisible:"function"==typeof e?e(this.props):e}})},render:function(){var e=this.props,t=e.attributes,r=t.className,i=void 0===r?"":r,u=o(t,["className"]),a=e.renderTag,l=o(e,["attributes","renderTag"]);return u.className="react-context-menu-wrapper "+i,u.onContextMenu=this.handleContextClick,u.onMouseDown=this.handleMouseDown,u.onMouseUp=this.handleMouseUp,u.onTouchStart=this.handleTouchstart,u.onTouchEnd=this.handleTouchEnd,u.onMouseOut=this.handleMouseUp,s["default"].createElement(a,u,s["default"].createElement(n,l))}})}};var u=n(1),s=r(u),a=n(2),l=r(a),c=n(142),p=r(c),f=n(18),d=r(f)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),s=r(u),a=n(61),l=r(a),c=n(62),p=r(c),f=n(29),d=r(f),h=s["default"].PropTypes,g=s["default"].createClass({displayName:"MenuItem",propTypes:{onClick:h.func.isRequired,data:h.object,disabled:h.bool,preventClose:h.bool},getDefaultProps:function(){return{disabled:!1,data:{},attributes:{}}},handleClick:function(e){var t=this.props,n=t.disabled,r=t.onClick,o=t.data,i=t.preventClose;e.preventDefault(),n||((0,p["default"])(o,d["default"].getItem()),"function"==typeof r&&r(e,o),i||d["default"].hideMenu())},render:function(){var e=this.props,t=e.disabled,n=e.children,r=e.attributes,u=r.className,a=void 0===u?"":u,c=o(r,["className"]),p="react-context-menu-item "+a,f=(0,l["default"])({"react-context-menu-link":!0,disabled:t});return s["default"].createElement("div",i({className:p},c),s["default"].createElement("a",{href:"#",className:f,onClick:this.handleClick},n))}});t["default"]=g},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?u:arguments[0],t=arguments[1];return"SET_PARAMS"===t.type?(0,i["default"])({},e,t.data):e};var o=n(62),i=r(o),u={x:0,y:0,isVisible:!1,currentItem:{}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),u=n(61),s=r(u),a=n(209),l=r(a),c={position:"relative",zIndex:"auto"},p=i["default"].createClass({displayName:"SubMenu",propTypes:{title:i["default"].PropTypes.string.isRequired,disabled:i["default"].PropTypes.bool,hoverDelay:i["default"].PropTypes.number},getDefaultProps:function(){return{hoverDelay:500}},getInitialState:function(){return{visible:!1}},shouldComponentUpdate:function(e,t){return this.state.isVisible!==t.visible},componentWillUnmount:function(){this.opentimer&&clearTimeout(this.opentimer),this.closetimer&&clearTimeout(this.closetimer)},handleClick:function(e){e.preventDefault()},handleMouseEnter:function(){var e=this;this.closetimer&&clearTimeout(this.closetimer),this.props.disabled||this.state.visible||(this.opentimer=setTimeout(function(){return e.setState({visible:!0})},this.props.hoverDelay))},handleMouseLeave:function(){var e=this;this.opentimer&&clearTimeout(this.opentimer),this.state.visible&&(this.closetimer=setTimeout(function(){return e.setState({visible:!1})},this.props.hoverDelay))},render:function(){var e=this,t=this.props,n=t.disabled,r=t.children,o=t.title,u=this.state.visible,a=(0,s["default"])({"react-context-menu-link":!0,disabled:n,active:u}),p="react-context-menu-item submenu";return i["default"].createElement("div",{ref:function(t){return e.item=t},className:p,style:c,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave},i["default"].createElement("a",{href:"#",className:a,onClick:this.handleClick},o),i["default"].createElement(l["default"],{visible:u},r))}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=u["default"].createClass({displayName:"SubMenuWrapper",propTypes:{visible:u["default"].PropTypes.bool},getInitialState:function(){return{position:{top:!0,right:!0}}},componentWillReceiveProps:function(e){var t=this;if(e.visible){var n=window.requestAnimationFrame||setTimeout;n(function(){t.setState(t.getMenuPosition()),t.forceUpdate()})}else this.setState(this.getInitialState())},shouldComponentUpdate:function(e){return this.props.visible!==e.visible},getMenuPosition:function(){var e=window,t=e.innerWidth,n=e.innerHeight,r=this.menu.getBoundingClientRect(),o={};return r.bottom>n?o.bottom=!0:o.top=!0,r.right>t?o.left=!0:o.right=!0,{position:o}},getPositionStyles:function(){var e={},t=this.state.position;return t.top&&(e.top=0),t.bottom&&(e.bottom=0),t.right&&(e.left="100%"),t.left&&(e.right="100%"),e},render:function(){var e=this,t=this.props,n=t.children,r=t.visible,i=o({display:r?"block":"none",position:"absolute"},this.getPositionStyles());return u["default"].createElement("nav",{ref:function(t){return e.menu=t},style:i,className:"react-context-menu"},n)}});t["default"]=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var i=n(200),u=r(i),s=n(59),a=r(s),l=function(){function e(){o(this,e),this.entered=[]}return e.prototype.enter=function(e){var t=this.entered.length;return this.entered=u["default"](this.entered.filter(function(t){return document.documentElement.contains(t)&&(!t.contains||t.contains(e))}),[e]),0===t&&this.entered.length>0},e.prototype.leave=function(e){var t=this.entered.length;return this.entered=a["default"](this.entered.filter(function(e){return document.documentElement.contains(e)}),e),t>0&&0===this.entered.length},e.prototype.reset=function(){this.entered=[]},e}();t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var u=n(195),s=o(u),a=n(217),l=o(a),c=n(210),p=o(c),f=n(63),d=n(214),h=n(213),g=n(30),v=r(g),y=function(){function e(t){i(this,e),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.sourcePreviewNodes={},this.sourcePreviewNodeOptions={},this.sourceNodes={},this.sourceNodeOptions={},this.enterLeaveCounter=new p["default"],this.getSourceClientOffset=this.getSourceClientOffset.bind(this),this.handleTopDragStart=this.handleTopDragStart.bind(this),this.handleTopDragStartCapture=this.handleTopDragStartCapture.bind(this),this.handleTopDragEndCapture=this.handleTopDragEndCapture.bind(this),this.handleTopDragEnter=this.handleTopDragEnter.bind(this),this.handleTopDragEnterCapture=this.handleTopDragEnterCapture.bind(this),this.handleTopDragLeaveCapture=this.handleTopDragLeaveCapture.bind(this),this.handleTopDragOver=this.handleTopDragOver.bind(this),this.handleTopDragOverCapture=this.handleTopDragOverCapture.bind(this),this.handleTopDrop=this.handleTopDrop.bind(this),this.handleTopDropCapture=this.handleTopDropCapture.bind(this),this.handleSelectStart=this.handleSelectStart.bind(this),this.endDragIfSourceWasRemovedFromDOM=this.endDragIfSourceWasRemovedFromDOM.bind(this),this.endDragNativeItem=this.endDragNativeItem.bind(this)}return e.prototype.setup=function(){if("undefined"!=typeof window){if(this.constructor.isSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");this.constructor.isSetUp=!0,this.addEventListeners(window)}},e.prototype.teardown=function(){"undefined"!=typeof window&&(this.constructor.isSetUp=!1,this.removeEventListeners(window),this.clearCurrentDragSourceNode())},e.prototype.addEventListeners=function(e){e.addEventListener("dragstart",this.handleTopDragStart),e.addEventListener("dragstart",this.handleTopDragStartCapture,!0),e.addEventListener("dragend",this.handleTopDragEndCapture,!0),e.addEventListener("dragenter",this.handleTopDragEnter),e.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.addEventListener("dragover",this.handleTopDragOver),e.addEventListener("dragover",this.handleTopDragOverCapture,!0),e.addEventListener("drop",this.handleTopDrop),e.addEventListener("drop",this.handleTopDropCapture,!0)},e.prototype.removeEventListeners=function(e){e.removeEventListener("dragstart",this.handleTopDragStart),e.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),e.removeEventListener("dragend",this.handleTopDragEndCapture,!0),e.removeEventListener("dragenter",this.handleTopDragEnter),e.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.removeEventListener("dragover",this.handleTopDragOver),e.removeEventListener("dragover",this.handleTopDragOverCapture,!0),e.removeEventListener("drop",this.handleTopDrop),e.removeEventListener("drop",this.handleTopDropCapture,!0)},e.prototype.connectDragPreview=function(e,t,n){var r=this;return this.sourcePreviewNodeOptions[e]=n,this.sourcePreviewNodes[e]=t,function(){delete r.sourcePreviewNodes[e],delete r.sourcePreviewNodeOptions[e]}},e.prototype.connectDragSource=function(e,t,n){var r=this;this.sourceNodes[e]=t,this.sourceNodeOptions[e]=n;var o=function(t){return r.handleDragStart(t,e)},i=function(t){return r.handleSelectStart(t,e)};return t.setAttribute("draggable",!0),t.addEventListener("dragstart",o),t.addEventListener("selectstart",i),function(){delete r.sourceNodes[e],delete r.sourceNodeOptions[e],t.removeEventListener("dragstart",o),t.removeEventListener("selectstart",i),t.setAttribute("draggable",!1)}},e.prototype.connectDropTarget=function(e,t){var n=this,r=function(t){return n.handleDragEnter(t,e)},o=function(t){return n.handleDragOver(t,e)},i=function(t){return n.handleDrop(t,e)};return t.addEventListener("dragenter",r),t.addEventListener("dragover",o),t.addEventListener("drop",i),function(){t.removeEventListener("dragenter",r),t.removeEventListener("dragover",o),t.removeEventListener("drop",i)}},e.prototype.getCurrentSourceNodeOptions=function(){var e=this.monitor.getSourceId(),t=this.sourceNodeOptions[e];return s["default"](t||{},{dropEffect:"move"})},e.prototype.getCurrentDropEffect=function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect},e.prototype.getCurrentSourcePreviewNodeOptions=function(){var e=this.monitor.getSourceId(),t=this.sourcePreviewNodeOptions[e];return s["default"](t||{},{anchorX:.5,anchorY:.5,captureDraggingState:!1})},e.prototype.getSourceClientOffset=function(e){return d.getNodeClientOffset(this.sourceNodes[e])},e.prototype.isDraggingNativeItem=function(){var e=this.monitor.getItemType();return Object.keys(v).some(function(t){return v[t]===e})},e.prototype.beginDragNativeItem=function(e){this.clearCurrentDragSourceNode();var t=h.createNativeDragSource(e);this.currentNativeSource=new t,this.currentNativeHandle=this.registry.addSource(e,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle]),f.isFirefox()&&window.addEventListener("mousemove",this.endDragNativeItem,!0)},e.prototype.endDragNativeItem=function(){this.isDraggingNativeItem()&&(f.isFirefox()&&window.removeEventListener("mousemove",this.endDragNativeItem,!0),this.actions.endDrag(),this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},e.prototype.endDragIfSourceWasRemovedFromDOM=function(){var e=this.currentDragSourceNode;document.body.contains(e)||this.clearCurrentDragSourceNode()&&this.actions.endDrag()},e.prototype.setCurrentDragSourceNode=function(e){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=e,this.currentDragSourceNodeOffset=d.getNodeClientOffset(e),this.currentDragSourceNodeOffsetChanged=!1,window.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},e.prototype.clearCurrentDragSourceNode=function(){return!!this.currentDragSourceNode&&(this.currentDragSourceNode=null,this.currentDragSourceNodeOffset=null,this.currentDragSourceNodeOffsetChanged=!1,window.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0),!0)},e.prototype.checkIfCurrentDragSourceRectChanged=function(){var e=this.currentDragSourceNode;return!!e&&(!!this.currentDragSourceNodeOffsetChanged||(this.currentDragSourceNodeOffsetChanged=!l["default"](d.getNodeClientOffset(e),this.currentDragSourceNodeOffset),this.currentDragSourceNodeOffsetChanged))},e.prototype.handleTopDragStartCapture=function(){this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},e.prototype.handleDragStart=function(e,t){this.dragStartSourceIds.unshift(t)},e.prototype.handleTopDragStart=function(e){var t=this,n=this.dragStartSourceIds;this.dragStartSourceIds=null;var r=d.getEventClientOffset(e);this.actions.beginDrag(n,{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:r});var o=e.dataTransfer,i=h.matchNativeItemType(o);if(this.monitor.isDragging()){if("function"==typeof o.setDragImage){var u=this.monitor.getSourceId(),s=this.sourceNodes[u],a=this.sourcePreviewNodes[u]||s,l=this.getCurrentSourcePreviewNodeOptions(),c=l.anchorX,p=l.anchorY,f={anchorX:c,anchorY:p},g=d.getDragPreviewOffset(s,a,r,f);o.setDragImage(a,g.x,g.y)}try{o.setData("application/json",{})}catch(v){}this.setCurrentDragSourceNode(e.target);var y=this.getCurrentSourcePreviewNodeOptions(),m=y.captureDraggingState;m?this.actions.publishDragSource():setTimeout(function(){return t.actions.publishDragSource()})}else if(i)this.beginDragNativeItem(i);else{if(!(o.types||e.target.hasAttribute&&e.target.hasAttribute("draggable")))return;e.preventDefault()}},e.prototype.handleTopDragEndCapture=function(){this.clearCurrentDragSourceNode()&&this.actions.endDrag()},e.prototype.handleTopDragEnterCapture=function(e){this.dragEnterTargetIds=[];var t=this.enterLeaveCounter.enter(e.target);if(t&&!this.monitor.isDragging()){var n=e.dataTransfer,r=h.matchNativeItemType(n);r&&this.beginDragNativeItem(r)}},e.prototype.handleDragEnter=function(e,t){this.dragEnterTargetIds.unshift(t)},e.prototype.handleTopDragEnter=function(e){var t=this,n=this.dragEnterTargetIds;if(this.dragEnterTargetIds=[],this.monitor.isDragging()){f.isFirefox()||this.actions.hover(n,{clientOffset:d.getEventClientOffset(e)});var r=n.some(function(e){return t.monitor.canDropOnTarget(e)});r&&(e.preventDefault(),e.dataTransfer.dropEffect=this.getCurrentDropEffect())}},e.prototype.handleTopDragOverCapture=function(){this.dragOverTargetIds=[]},e.prototype.handleDragOver=function(e,t){this.dragOverTargetIds.unshift(t)},e.prototype.handleTopDragOver=function(e){var t=this,n=this.dragOverTargetIds;if(this.dragOverTargetIds=[],!this.monitor.isDragging())return e.preventDefault(),void(e.dataTransfer.dropEffect="none");this.actions.hover(n,{clientOffset:d.getEventClientOffset(e)});var r=n.some(function(e){return t.monitor.canDropOnTarget(e)});r?(e.preventDefault(),e.dataTransfer.dropEffect=this.getCurrentDropEffect()):this.isDraggingNativeItem()?(e.preventDefault(),e.dataTransfer.dropEffect="none"):this.checkIfCurrentDragSourceRectChanged()&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},e.prototype.handleTopDragLeaveCapture=function(e){this.isDraggingNativeItem()&&e.preventDefault();var t=this.enterLeaveCounter.leave(e.target);t&&this.isDraggingNativeItem()&&this.endDragNativeItem()},e.prototype.handleTopDropCapture=function(e){this.dropTargetIds=[],e.preventDefault(),this.isDraggingNativeItem()&&this.currentNativeSource.mutateItemByReadingDataTransfer(e.dataTransfer),this.enterLeaveCounter.reset()},e.prototype.handleDrop=function(e,t){this.dropTargetIds.unshift(t)},e.prototype.handleTopDrop=function(e){var t=this.dropTargetIds;this.dropTargetIds=[],this.actions.hover(t,{clientOffset:d.getEventClientOffset(e)}),this.actions.drop(),this.isDraggingNativeItem()?this.endDragNativeItem():this.endDragIfSourceWasRemovedFromDOM()},e.prototype.handleSelectStart=function(e){var t=e.target;"function"==typeof t.dragDrop&&("INPUT"===t.tagName||"SELECT"===t.tagName||"TEXTAREA"===t.tagName||t.isContentEditable||(e.preventDefault(),t.dragDrop()))},e}();t["default"]=y,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(t,r){n(this,e);for(var o=t.length,i=[],u=0;u<o;u++)i.push(u);i.sort(function(e,n){return t[e]<t[n]?-1:1});for(var s=[],a=[],l=[],c=void 0,p=void 0,u=0;u<o-1;u++)c=t[u+1]-t[u],p=r[u+1]-r[u],a.push(c),s.push(p),l.push(p/c);for(var f=[l[0]],u=0;u<a.length-1;u++){var d=l[u],h=l[u+1];if(d*h<=0)f.push(0);else{c=a[u];var g=a[u+1],v=c+g;f.push(3*v/((v+g)/d+(v+c)/h))}}f.push(l[l.length-1]);for(var y=[],m=[],b=void 0,u=0;u<f.length-1;u++){b=l[u];var E=f[u],T=1/a[u],v=E+f[u+1]-b-b;y.push((b-E-v)*T),m.push(v*T*T)}this.xs=t,this.ys=r,this.c1s=f,this.c2s=y,this.c3s=m}return e.prototype.interpolate=function(e){var t=this.xs,n=this.ys,r=this.c1s,o=this.c2s,i=this.c3s,u=t.length-1;if(e===t[u])return n[u];for(var s=0,a=i.length-1,l=void 0;s<=a;){l=Math.floor(.5*(s+a));var c=t[l];if(c<e)s=l+1;else{if(!(c>e))return n[l];a=l-1}}u=Math.max(0,a);var p=e-t[u],f=p*p;return n[u]+r[u]*p+o[u]*f+i[u]*p*f},e}();t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t,n){var r=t.reduce(function(t,n){return t||e.getData(n)},null);return null!=r?r:n}function s(e){var t=f[e],n=t.exposeProperty,r=t.matchesTypes,u=t.getData;return function(){function e(){o(this,e),this.item=Object.defineProperties({},i({},n,{get:function(){return console.warn("Browser doesn't allow reading \""+n+'" until the drop event.'),null},configurable:!0,enumerable:!0}))}return e.prototype.mutateItemByReadingDataTransfer=function(e){delete this.item[n],this.item[n]=u(e,r)},e.prototype.canDrag=function(){return!0},e.prototype.beginDrag=function(){return this.item},e.prototype.isDragging=function(e,t){return t===e.getSourceId()},e.prototype.endDrag=function(){},e}()}function a(e){var t=Array.prototype.slice.call(e.types||[]);return Object.keys(f).filter(function(e){var n=f[e].matchesTypes;return n.some(function(e){return t.indexOf(e)>-1})})[0]||null}t.__esModule=!0;var l;t.createNativeDragSource=s,t.matchNativeItemType=a;var c=n(30),p=r(c),f=(l={},i(l,p.FILE,{exposeProperty:"files",matchesTypes:["Files"],getData:function(e){return Array.prototype.slice.call(e.files)}}),i(l,p.URL,{exposeProperty:"urls",matchesTypes:["Url","text/uri-list"],getData:function(e,t){return u(e,t,"").split("\n")}}),i(l,p.TEXT,{exposeProperty:"text",matchesTypes:["Text","text/plain"],getData:function(e,t){return u(e,t,"")}}),l)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.nodeType===c?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,o=n.left;return{x:o,y:r}}function i(e){return{x:e.clientX,y:e.clientY}}function u(e,t,n,r){var i="IMG"===t.nodeName&&(s.isFirefox()||!document.documentElement.contains(t)),u=i?e:t,a=o(u),c={x:n.x-a.x,y:n.y-a.y},p=e.offsetWidth,f=e.offsetHeight,d=r.anchorX,h=r.anchorY,g=i?t.width:p,v=i?t.height:f;s.isSafari()&&i?(v/=window.devicePixelRatio,g/=window.devicePixelRatio):s.isFirefox()&&!i&&(v*=window.devicePixelRatio,g*=window.devicePixelRatio);var y=new l["default"]([0,.5,1],[c.x,c.x/p*g,c.x+g-p]),m=new l["default"]([0,.5,1],[c.y,c.y/f*v,c.y+v-f]),b=y.interpolate(d),E=m.interpolate(h);return s.isSafari()&&i&&(E+=(window.devicePixelRatio-1)*v),{x:b,y:E}}t.__esModule=!0,t.getNodeClientOffset=o,t.getEventClientOffset=i,t.getDragPreviewOffset=u;var s=n(63),a=n(212),l=r(a),c=1},function(e,t){"use strict";function n(){return r||(r=new Image,r.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),r}t.__esModule=!0,t["default"]=n;var r=void 0;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e){return new s["default"](e)}t.__esModule=!0,t["default"]=i;var u=n(211),s=o(u),a=n(215),l=o(a),c=n(30),p=r(c);t.NativeTypes=p,t.getEmptyImage=l["default"]},32,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){v["default"].apply(void 0,["DragDropContext","backend"].concat(a.call(arguments)));var t=void 0;t="object"==typeof e&&"function"==typeof e["default"]?e["default"]:e,h["default"]("function"==typeof t,"Expected the backend to be a function or an ES6 module exporting a default function. Read more: http://gaearon.github.io/react-dnd/docs-drag-drop-context.html");var n={dragDropManager:new f.DragDropManager(t)};return function(e){var t=e.displayName||e.name||"Component";return function(r){function u(){o(this,u),r.apply(this,arguments)}return i(u,r),u.prototype.getDecoratedComponentInstance=function(){return this.refs.child},u.prototype.getManager=function(){return n.dragDropManager},u.prototype.getChildContext=function(){return n},u.prototype.render=function(){return p["default"].createElement(e,s({},this.props,{ref:"child"}))},l(u,null,[{key:"DecoratedComponent",value:e,enumerable:!0},{key:"displayName",value:"DragDropContext("+t+")",enumerable:!0},{key:"childContextTypes",value:{dragDropManager:c.PropTypes.object.isRequired},enumerable:!0}]),u}(c.Component)}}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=Array.prototype.slice,l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var c=n(1),p=r(c),f=n(120),d=n(2),h=r(d),g=n(19),v=r(g);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return T["default"].apply(void 0,["DragLayer","collect[, options]"].concat(a.call(arguments))),b["default"]("function"==typeof e,'Expected "collect" provided as the first argument to DragLayer to be a function that collects props to inject into the component. ',"Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html",e),b["default"](y["default"](t),'Expected "options" provided as the second argument to DragLayer to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html',t),function(n){var r=t.arePropsEqual,u=void 0===r?g["default"]:r,a=n.displayName||n.name||"Component";return function(t){function r(e,n){o(this,r),t.call(this,e),this.handleChange=this.handleChange.bind(this),this.manager=n.dragDropManager,b["default"]("object"==typeof this.manager,"Could not find the drag and drop manager in the context of %s. Make sure to wrap the top-level component of your app with DragDropContext. Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context",a,a),this.state=this.getCurrentState()}return i(r,t),r.prototype.getDecoratedComponentInstance=function(){return this.refs.child},r.prototype.shouldComponentUpdate=function(e,t){return!u(e,this.props)||!d["default"](t,this.state)},l(r,null,[{key:"DecoratedComponent",value:n,enumerable:!0},{key:"displayName",value:"DragLayer("+a+")",enumerable:!0},{key:"contextTypes",value:{dragDropManager:c.PropTypes.object.isRequired},enumerable:!0}]),r.prototype.componentDidMount=function(){this.isCurrentlyMounted=!0;var e=this.manager.getMonitor();this.unsubscribeFromOffsetChange=e.subscribeToOffsetChange(this.handleChange),this.unsubscribeFromStateChange=e.subscribeToStateChange(this.handleChange),this.handleChange()},r.prototype.componentWillUnmount=function(){this.isCurrentlyMounted=!1,this.unsubscribeFromOffsetChange(),this.unsubscribeFromStateChange()},r.prototype.handleChange=function(){if(this.isCurrentlyMounted){var e=this.getCurrentState();d["default"](e,this.state)||this.setState(e)}},r.prototype.getCurrentState=function(){var t=this.manager.getMonitor();return e(t)},r.prototype.render=function(){return p["default"].createElement(n,s({},this.props,this.state,{ref:"child"}))},r}(c.Component)}}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=Array.prototype.slice,l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];
r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var c=n(1),p=r(c),f=n(32),d=r(f),h=n(67),g=r(h),v=n(3),y=r(v),m=n(2),b=r(m),E=n(19),T=r(E);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3];p["default"].apply(void 0,["DragSource","type, spec, collect[, options]"].concat(i.call(arguments)));var o=e;"function"!=typeof e&&(s["default"](D["default"](e),'Expected "type" provided as the first argument to DragSource to be a string, or a function that returns a string given the current props. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',e),o=function(){return e}),s["default"](l["default"](t),'Expected "spec" provided as the second argument to DragSource to be a plain object. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',t);var u=y["default"](t);return s["default"]("function"==typeof n,'Expected "collect" provided as the third argument to DragSource to be a function that returns a plain object of props to inject. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',n),s["default"](l["default"](r),'Expected "options" provided as the fourth argument to DragSource to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',n),function(e){return d["default"]({connectBackend:function(e,t){return e.connectDragSource(t)},containerDisplayName:"DragSource",createHandler:u,registerHandler:g["default"],createMonitor:b["default"],createConnector:T["default"],DecoratedComponent:e,getType:o,collect:n,options:r})}}t.__esModule=!0;var i=Array.prototype.slice;t["default"]=o;var u=n(2),s=r(u),a=n(3),l=r(a),c=n(19),p=r(c),f=n(65),d=r(f),h=n(228),g=r(h),v=n(223),y=r(v),m=n(224),b=r(m),E=n(222),T=r(E),_=n(66),D=r(_);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3];p["default"].apply(void 0,["DropTarget","type, spec, collect[, options]"].concat(i.call(arguments)));var o=e;"function"!=typeof e&&(s["default"](D["default"](e,!0),'Expected "type" provided as the first argument to DropTarget to be a string, an array of strings, or a function that returns either given the current props. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',e),o=function(){return e}),s["default"](l["default"](t),'Expected "spec" provided as the second argument to DropTarget to be a plain object. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',t);var u=y["default"](t);return s["default"]("function"==typeof n,'Expected "collect" provided as the third argument to DropTarget to be a function that returns a plain object of props to inject. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',n),s["default"](l["default"](r),'Expected "options" provided as the fourth argument to DropTarget to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',n),function(e){return d["default"]({connectBackend:function(e,t){return e.connectDropTarget(t)},containerDisplayName:"DropTarget",createHandler:u,registerHandler:g["default"],createMonitor:b["default"],createConnector:T["default"],DecoratedComponent:e,getType:o,collect:n,options:r})}}t.__esModule=!0;var i=Array.prototype.slice;t["default"]=o;var u=n(2),s=r(u),a=n(3),l=r(a),c=n(19),p=r(c),f=n(65),d=r(f),h=n(229),g=r(h),v=n(226),y=r(v),m=n(227),b=r(m),E=n(225),T=r(E),_=n(66),D=r(_);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){function t(){l&&(l(),l=null),o&&i&&(l=e.connectDragSource(o,i,s))}function n(){f&&(f(),f=null),o&&c&&(f=e.connectDragPreview(o,c,p))}function r(e){e!==o&&(o=e,t(),n())}var o=void 0,i=void 0,s=void 0,l=void 0,c=void 0,p=void 0,f=void 0,d=u["default"]({dragSource:function(e,n){e===i&&a["default"](n,s)||(i=e,s=n,t())},dragPreview:function(e,t){e===c&&a["default"](t,p)||(c=e,p=t,n())}});return{receiveHandlerId:r,hooks:d}}t.__esModule=!0,t["default"]=o;var i=n(68),u=r(i),s=n(64),a=r(s);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){Object.keys(e).forEach(function(t){s["default"](l.indexOf(t)>-1,'Expected the drag source specification to only have some of the following keys: %s. Instead received a specification with an unexpected "%s" key. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',l.join(", "),t),s["default"]("function"==typeof e[t],"Expected %s in the drag source specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html",t,t,e[t])}),c.forEach(function(t){s["default"]("function"==typeof e[t],"Expected %s in the drag source specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html",t,t,e[t])});var t=function(){function t(e){o(this,t),this.monitor=e,this.props=null,this.component=null}return t.prototype.receiveProps=function(e){this.props=e},t.prototype.receiveComponent=function(e){this.component=e},t.prototype.canDrag=function(){return!e.canDrag||e.canDrag(this.props,this.monitor)},t.prototype.isDragging=function(t,n){return e.isDragging?e.isDragging(this.props,this.monitor):n===t.getSourceId()},t.prototype.beginDrag=function(){var t=e.beginDrag(this.props,this.monitor,this.component);return t},t.prototype.endDrag=function(){e.endDrag&&e.endDrag(this.props,this.monitor,this.component)},t}();return function(e){return new t(e)}}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=n(3),l=(r(a),["canDrag","beginDrag","canDrag","isDragging","endDrag"]),c=["beginDrag"];e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new c(e)}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=!1,l=!1,c=function(){function e(t){o(this,e),this.internalMonitor=t.getMonitor()}return e.prototype.receiveHandlerId=function(e){this.sourceId=e},e.prototype.canDrag=function(){s["default"](!a,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html");try{return a=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{a=!1}},e.prototype.isDragging=function(){s["default"](!l,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html");try{return l=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{l=!1}},e.prototype.getItemType=function(){return this.internalMonitor.getItemType()},e.prototype.getItem=function(){return this.internalMonitor.getItem()},e.prototype.getDropResult=function(){return this.internalMonitor.getDropResult()},e.prototype.didDrop=function(){return this.internalMonitor.didDrop()},e.prototype.getInitialClientOffset=function(){return this.internalMonitor.getInitialClientOffset()},e.prototype.getInitialSourceClientOffset=function(){return this.internalMonitor.getInitialSourceClientOffset()},e.prototype.getSourceClientOffset=function(){return this.internalMonitor.getSourceClientOffset()},e.prototype.getClientOffset=function(){return this.internalMonitor.getClientOffset()},e.prototype.getDifferenceFromInitialOffset=function(){return this.internalMonitor.getDifferenceFromInitialOffset()},e}();e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){function t(){s&&(s(),s=null),r&&o&&(s=e.connectDropTarget(r,o,i))}function n(e){e!==r&&(r=e,t())}var r=void 0,o=void 0,i=void 0,s=void 0,l=u["default"]({dropTarget:function(e,n){e===o&&a["default"](n,i)||(o=e,i=n,t())}});return{receiveHandlerId:n,hooks:l}}t.__esModule=!0,t["default"]=o;var i=n(68),u=r(i),s=n(64),a=r(s);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){Object.keys(e).forEach(function(t){s["default"](l.indexOf(t)>-1,'Expected the drop target specification to only have some of the following keys: %s. Instead received a specification with an unexpected "%s" key. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',l.join(", "),t),s["default"]("function"==typeof e[t],"Expected %s in the drop target specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html",t,t,e[t])});var t=function(){function t(e){o(this,t),this.monitor=e,this.props=null,this.component=null}return t.prototype.receiveProps=function(e){this.props=e},t.prototype.receiveMonitor=function(e){this.monitor=e},t.prototype.receiveComponent=function(e){this.component=e},t.prototype.canDrop=function(){return!e.canDrop||e.canDrop(this.props,this.monitor)},t.prototype.hover=function(){e.hover&&e.hover(this.props,this.monitor,this.component)},t.prototype.drop=function(){if(e.drop){var t=e.drop(this.props,this.monitor,this.component);return t}},t}();return function(e){return new t(e)}}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=n(3),l=(r(a),["canDrop","hover","drop"]);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new l(e)}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=!1,l=function(){function e(t){o(this,e),this.internalMonitor=t.getMonitor()}return e.prototype.receiveHandlerId=function(e){this.targetId=e},e.prototype.canDrop=function(){s["default"](!a,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drop-target-monitor.html");try{return a=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{a=!1}},e.prototype.isOver=function(e){return this.internalMonitor.isOverTarget(this.targetId,e)},e.prototype.getItemType=function(){return this.internalMonitor.getItemType()},e.prototype.getItem=function(){return this.internalMonitor.getItem()},e.prototype.getDropResult=function(){return this.internalMonitor.getDropResult()},e.prototype.didDrop=function(){return this.internalMonitor.didDrop()},e.prototype.getInitialClientOffset=function(){return this.internalMonitor.getInitialClientOffset()},e.prototype.getInitialSourceClientOffset=function(){return this.internalMonitor.getInitialSourceClientOffset()},e.prototype.getSourceClientOffset=function(){return this.internalMonitor.getSourceClientOffset()},e.prototype.getClientOffset=function(){return this.internalMonitor.getClientOffset()},e.prototype.getDifferenceFromInitialOffset=function(){return this.internalMonitor.getDifferenceFromInitialOffset()},e}();e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){function r(){o.removeSource(i)}var o=n.getRegistry(),i=o.addSource(e,t);return{handlerId:i,unregister:r}}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){function r(){o.removeTarget(i)}var o=n.getRegistry(),i=o.addTarget(e,t);return{handlerId:i,unregister:r}}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=e.ref;return u["default"]("string"!=typeof n,"Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute"),n?s.cloneElement(e,{ref:function(e){t(e),n&&n(e)}}):s.cloneElement(e,{ref:t})}t.__esModule=!0,t["default"]=o;var i=n(2),u=r(i),s=n(1);e.exports=t["default"]},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i={position:"absolute",top:0,left:0,visibility:"hidden",height:0,overflow:"scroll",whiteSpace:"pre"},u=o.createClass({displayName:"AutosizeInput",propTypes:{className:o.PropTypes.string,defaultValue:o.PropTypes.any,inputClassName:o.PropTypes.string,inputStyle:o.PropTypes.object,minWidth:o.PropTypes.oneOfType([o.PropTypes.number,o.PropTypes.string]),onChange:o.PropTypes.func,placeholder:o.PropTypes.string,placeholderIsMinWidth:o.PropTypes.bool,style:o.PropTypes.object,value:o.PropTypes.any},getDefaultProps:function(){return{minWidth:1}},getInitialState:function(){return{inputWidth:this.props.minWidth}},componentDidMount:function(){this.copyInputStyles(),this.updateInputWidth()},componentDidUpdate:function(){this.updateInputWidth()},copyInputStyles:function(){if(this.isMounted()&&window.getComputedStyle){var e=window.getComputedStyle(this.refs.input);if(e){var t=this.refs.sizer;if(t.style.fontSize=e.fontSize,t.style.fontFamily=e.fontFamily,t.style.fontWeight=e.fontWeight,t.style.fontStyle=e.fontStyle,t.style.letterSpacing=e.letterSpacing,this.props.placeholder){var n=this.refs.placeholderSizer;n.style.fontSize=e.fontSize,n.style.fontFamily=e.fontFamily,n.style.fontWeight=e.fontWeight,n.style.fontStyle=e.fontStyle,n.style.letterSpacing=e.letterSpacing}}}},updateInputWidth:function(){if(this.isMounted()&&"undefined"!=typeof this.refs.sizer.scrollWidth){var e=void 0;e=this.props.placeholder&&(!this.props.value||this.props.value&&this.props.placeholderIsMinWidth)?Math.max(this.refs.sizer.scrollWidth,this.refs.placeholderSizer.scrollWidth)+2:this.refs.sizer.scrollWidth+2,e<this.props.minWidth&&(e=this.props.minWidth),e!==this.state.inputWidth&&this.setState({inputWidth:e})}},getInput:function(){return this.refs.input},focus:function(){this.refs.input.focus()},blur:function(){this.refs.input.blur()},select:function(){this.refs.input.select()},render:function(){var e=this.props.defaultValue||this.props.value||"",t=this.props.style||{};t.display||(t.display="inline-block");var n=r({},this.props.inputStyle);n.width=this.state.inputWidth+"px",n.boxSizing="content-box";var u=r({},this.props);return u.className=this.props.inputClassName,u.style=n,delete u.inputClassName,delete u.inputStyle,delete u.minWidth,delete u.placeholderIsMinWidth,o.createElement("div",{className:this.props.className,style:t},o.createElement("input",r({},u,{ref:"input"})),o.createElement("div",{ref:"sizer",style:i},e),this.props.placeholder?o.createElement("div",{ref:"placeholderSizer",style:i},this.props.placeholder):null)}});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(251),a=r(s),l=n(71),c=r(l),p=n(239),f=r(p),d=n(234),h=r(d),g=n(233),v=r(g),y=n(70),m=r(y),b=n(235),E=r(b),T=n(236),_=r(T),D=n(8),w=r(D),C=n(126),O=r(C),x=n(132),S=r(x),P=n(69),M=r(P),A=new v["default"],I=u["default"].createClass({displayName:"Modal",propTypes:o({},h["default"].propTypes,{show:u["default"].PropTypes.bool,container:u["default"].PropTypes.oneOfType([c["default"],u["default"].PropTypes.func]),onShow:u["default"].PropTypes.func,onHide:u["default"].PropTypes.func,backdrop:u["default"].PropTypes.oneOfType([u["default"].PropTypes.bool,u["default"].PropTypes.oneOf(["static"])]),onEscapeKeyUp:u["default"].PropTypes.func,onBackdropClick:u["default"].PropTypes.func,backdropStyle:u["default"].PropTypes.object,backdropClassName:u["default"].PropTypes.string,containerClassName:u["default"].PropTypes.string,keyboard:u["default"].PropTypes.bool,transition:f["default"],dialogTransitionTimeout:u["default"].PropTypes.number,backdropTransitionTimeout:u["default"].PropTypes.number,autoFocus:u["default"].PropTypes.bool,enforceFocus:u["default"].PropTypes.bool,onEnter:u["default"].PropTypes.func,onEntering:u["default"].PropTypes.func,onEntered:u["default"].PropTypes.func,onExit:u["default"].PropTypes.func,onExiting:u["default"].PropTypes.func,onExited:u["default"].PropTypes.func}),getDefaultProps:function(){var e=function(){};return{show:!1,backdrop:!0,keyboard:!0,autoFocus:!0,enforceFocus:!0,onHide:e}},getInitialState:function(){return{exited:!this.props.show}},render:function(){var e=this.props,t=e.show,n=e.container,r=e.children,o=e.transition,s=e.backdrop,a=e.dialogTransitionTimeout,l=e.className,c=e.style,p=e.onExit,f=e.onExiting,d=e.onEnter,g=e.onEntering,v=e.onEntered,y=u["default"].Children.only(r),m=t||o&&!this.state.exited;if(!m)return null;var b=y.props,E=b.role,T=b.tabIndex;return void 0!==E&&void 0!==T||(y=(0,i.cloneElement)(y,{role:void 0===E?"document":E,tabIndex:null==T?"-1":T})),o&&(y=u["default"].createElement(o,{transitionAppear:!0,unmountOnExit:!0,"in":t,timeout:a,onExit:p,onExiting:f,onExited:this.handleHidden,onEnter:d,onEntering:g,onEntered:v},y)),u["default"].createElement(h["default"],{ref:this.setMountNode,container:n},u["default"].createElement("div",{ref:"modal",role:E||"dialog",style:c,className:l},s&&this.renderBackdrop(),y))},renderBackdrop:function(){var e=this.props,t=e.transition,n=e.backdropTransitionTimeout,r=u["default"].createElement("div",{ref:"backdrop",style:this.props.backdropStyle,className:this.props.backdropClassName,onClick:this.handleBackdropClick});return t&&(r=u["default"].createElement(t,{transitionAppear:!0,"in":this.props.show,timeout:n},r)),r},componentWillReceiveProps:function(e){e.show?this.setState({exited:!1}):e.transition||this.setState({exited:!0})},componentWillUpdate:function(e){!this.props.show&&e.show&&this.checkForFocus()},componentDidMount:function(){this.props.show&&this.onShow()},componentDidUpdate:function(e){var t=this.props.transition;!e.show||this.props.show||t?!e.show&&this.props.show&&this.onShow():this.onHide()},componentWillUnmount:function(){var e=this.props,t=e.show,n=e.transition;(t||n&&!this.state.exited)&&this.onHide()},onShow:function(){var e=(0,m["default"])(this),t=(0,M["default"])(this.props.container,e.body);A.add(this,t,this.props.containerClassName),this._onDocumentKeyupListener=(0,E["default"])(e,"keyup",this.handleDocumentKeyUp),this._onFocusinListener=(0,_["default"])(this.enforceFocus),this.focus(),this.props.onShow&&this.props.onShow()},onHide:function(){A.remove(this),this._onDocumentKeyupListener.remove(),this._onFocusinListener.remove(),this.restoreLastFocus()},setMountNode:function(e){this.mountNode=e?e.getMountNode():e},handleHidden:function(){if(this.setState({exited:!0}),this.onHide(),this.props.onExited){var e;(e=this.props).onExited.apply(e,arguments)}},handleBackdropClick:function(e){e.target===e.currentTarget&&(this.props.onBackdropClick&&this.props.onBackdropClick(e),this.props.backdrop===!0&&this.props.onHide())},handleDocumentKeyUp:function(e){this.props.keyboard&&27===e.keyCode&&this.isTopModal()&&(this.props.onEscapeKeyUp&&this.props.onEscapeKeyUp(e),this.props.onHide())},checkForFocus:function(){w["default"]&&(this.lastFocus=(0,O["default"])())},focus:function(){var e=this.props.autoFocus,t=this.getDialogElement(),n=(0,O["default"])((0,m["default"])(this)),r=n&&(0,S["default"])(t,n);t&&e&&!r&&(this.lastFocus=n,t.hasAttribute("tabIndex")||(t.setAttribute("tabIndex",-1),(0,a["default"])(!1,'The modal content node does not accept focus. For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".')),t.focus())},restoreLastFocus:function(){this.lastFocus&&this.lastFocus.focus&&(this.lastFocus.focus(),this.lastFocus=null)},enforceFocus:function R(){var R=this.props.enforceFocus;if(R&&this.isMounted()&&this.isTopModal()){var e=(0,O["default"])((0,m["default"])(this)),t=this.getDialogElement();t&&t!==e&&!(0,S["default"])(t,e)&&t.focus()}},getDialogElement:function(){var e=this.refs.modal;return e&&e.lastChild},isTopModal:function(){return A.isTopModal(this)}});I.manager=A,t["default"]=I,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){var n=-1;return e.some(function(e,r){if(t(e,r))return n=r,!0}),n}function u(e,t){return i(e,function(e){return e.modals.indexOf(t)!==-1})}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=n(135),l=r(a),c=n(128),p=r(c),f=n(140),d=r(f),h=n(237),g=r(h),v=n(238),y=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0];o(this,e),this.hideSiblingNodes=t,this.modals=[],this.containers=[],this.data=[]}return s(e,[{key:"add",value:function(e,t,n){var r=this.modals.indexOf(e),o=this.containers.indexOf(t);if(r!==-1)return r;if(r=this.modals.length,this.modals.push(e),this.hideSiblingNodes&&(0,v.hideSiblings)(t,e.mountNode),o!==-1)return this.data[o].modals.push(e),r;var i={modals:[e],classes:n?n.split(/\s+/):[],style:{overflow:t.style.overflow,paddingRight:t.style.paddingRight}},u={overflow:"hidden"};return i.overflowing=(0,g["default"])(t),i.overflowing&&(u.paddingRight=parseInt((0,l["default"])(t,"paddingRight")||0,10)+(0,d["default"])()+"px"),(0,l["default"])(t,u),i.classes.forEach(p["default"].addClass.bind(null,t)),this.containers.push(t),this.data.push(i),r}},{key:"remove",value:function(e){var t=this.modals.indexOf(e);if(t!==-1){var n=u(this.data,e),r=this.data[n],o=this.containers[n];r.modals.splice(r.modals.indexOf(e),1),this.modals.splice(t,1),0===r.modals.length?(Object.keys(r.style).forEach(function(e){return o.style[e]=r.style[e]}),r.classes.forEach(p["default"].removeClass.bind(null,o)),this.hideSiblingNodes&&(0,v.showSiblings)(o,e.mountNode),this.containers.splice(n,1),this.data.splice(n,1)):this.hideSiblingNodes&&(0,v.ariaHidden)(!1,r.modals[r.modals.length-1].mountNode)}}},{key:"isTopModal",value:function(e){return!!this.modals.length&&this.modals[this.modals.length-1]===e}}]),e}();t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),u=n(4),s=r(u),a=n(71),l=r(a),c=n(70),p=r(c),f=n(69),d=r(f),h=i["default"].createClass({displayName:"Portal",propTypes:{container:i["default"].PropTypes.oneOfType([l["default"],i["default"].PropTypes.func])},componentDidMount:function(){this._renderOverlay()},componentDidUpdate:function(){this._renderOverlay()},componentWillReceiveProps:function(e){this._overlayTarget&&e.container!==this.props.container&&(this._portalContainerNode.removeChild(this._overlayTarget),this._portalContainerNode=(0,d["default"])(e.container,(0,p["default"])(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},componentWillUnmount:function(){this._unrenderOverlay(),this._unmountOverlayTarget()},_mountOverlayTarget:function(){this._overlayTarget||(this._overlayTarget=document.createElement("div"),this._portalContainerNode=(0,d["default"])(this.props.container,(0,p["default"])(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},_unmountOverlayTarget:function(){this._overlayTarget&&(this._portalContainerNode.removeChild(this._overlayTarget),this._overlayTarget=null),this._portalContainerNode=null},_renderOverlay:function(){var e=this.props.children?i["default"].Children.only(this.props.children):null;null!==e?(this._mountOverlayTarget(),this._overlayInstance=s["default"].unstable_renderSubtreeIntoContainer(this,e,this._overlayTarget)):(this._unrenderOverlay(),this._unmountOverlayTarget())},_unrenderOverlay:function(){this._overlayTarget&&(s["default"].unmountComponentAtNode(this._overlayTarget),this._overlayInstance=null)},render:function(){return null},getMountNode:function(){return this._overlayTarget},getOverlayDOMNode:function(){if(!this.isMounted())throw new Error("getOverlayDOMNode(): A component must be mounted to have a DOM node.");return this._overlayInstance?this._overlayInstance.getWrappedDOMNode?this._overlayInstance.getWrappedDOMNode():s["default"].findDOMNode(this._overlayInstance):null}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(e,t,n){return(0,i["default"])(e,t,n),{remove:function(){(0,s["default"])(e,t,n)}}};var o=n(131),i=r(o),u=n(130),s=r(u);e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=!document.addEventListener,n=void 0;return t?(document.attachEvent("onfocusin",e),n=function(){return document.detachEvent("onfocusin",e)}):(document.addEventListener("focus",e,!0),n=function(){return document.removeEventListener("focus",e,!0)}),{remove:n}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e&&"body"===e.tagName.toLowerCase()}function i(e){var t=(0,c["default"])(e),n=(0,a["default"])(t),r=n.innerWidth;if(!r){var o=t.documentElement.getBoundingClientRect();r=o.right-Math.abs(o.left)}return t.body.clientWidth<r}function u(e){var t=(0,a["default"])(e);return t||o(e)?i(e):e.scrollHeight>e.clientHeight}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var s=n(133),a=r(s),l=n(21),c=r(l);e.exports=t["default"]},function(e,t){"use strict";function n(e,t){t&&(e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}function r(e,t){s(e,t,function(e){return n(!0,e)})}function o(e,t){s(e,t,function(e){return n(!1,e)})}Object.defineProperty(t,"__esModule",{value:!0}),t.ariaHidden=n,t.hideSiblings=r,t.showSiblings=o;var i=["template","script","style"],u=function(e){var t=e.nodeType,n=e.tagName;return 1===t&&i.indexOf(n.toLowerCase())===-1},s=function(e,t,n){t=[].concat(t),[].forEach.call(e.children,function(e){t.indexOf(e)===-1&&u(e)&&n(e)})}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var u=e[t],a="undefined"==typeof u?"undefined":i(u);return s["default"].isValidElement(u)?new Error("Invalid "+r+" `"+o+"` of type ReactElement "+("supplied to `"+n+"`, expected an element type (a string ")+"or a ReactClass)."):"function"!==a&&"string"!==a?new Error("Invalid "+r+" `"+o+"` of value `"+u+"` "+("supplied to `"+n+"`, expected an element type (a string ")+"or a ReactClass)."):null}t.__esModule=!0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},u=n(1),s=r(u),a=n(72),l=r(a);t["default"]=(0,l["default"])(o)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e&&"object"!=typeof e&&(e={}),e?e:null}function i(e,t,n){e&&(e[t]=n)}function u(e,t){if(e)for(var n=t.length;n>=0;--n){var r=t.slice(0,n);if(e[r]&&(t===r||e[r].complete))return e[r]}}function s(e,t){if(e&&"function"==typeof e.then)return e.then(function(e){t(null,e)},function(e){t(e)})}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),c=r(l),p=n(73),f=r(p),d=n(74),h=r(d),g=0,v=c["default"].PropTypes.oneOfType([c["default"].PropTypes.string,c["default"].PropTypes.node]),y=c["default"].createClass({displayName:"Async",propTypes:{cache:c["default"].PropTypes.any,ignoreAccents:c["default"].PropTypes.bool,ignoreCase:c["default"].PropTypes.bool,isLoading:c["default"].PropTypes.bool,loadOptions:c["default"].PropTypes.func.isRequired,loadingPlaceholder:c["default"].PropTypes.string,minimumInput:c["default"].PropTypes.number,noResultsText:v,onInputChange:c["default"].PropTypes.func,placeholder:v,searchPromptText:v,searchingText:c["default"].PropTypes.string},getDefaultProps:function(){return{cache:!0,ignoreAccents:!0,ignoreCase:!0,loadingPlaceholder:"Loading...",minimumInput:0,searchingText:"Searching...",searchPromptText:"Type to search"}},getInitialState:function(){return{cache:o(this.props.cache),isLoading:!1,options:[]}},componentWillMount:function(){this._lastInput=""},componentDidMount:function(){this.loadOptions("")},componentWillReceiveProps:function(e){e.cache!==this.props.cache&&this.setState({cache:o(e.cache)})},focus:function(){this.refs.select.focus()},resetState:function(){this._currentRequestId=-1,this.setState({isLoading:!1,options:[]})},getResponseHandler:function(e){var t=this,n=this._currentRequestId=g++;return function(r,o){if(r)throw r;t.isMounted()&&(i(t.state.cache,e,o),n===t._currentRequestId&&t.setState({isLoading:!1,options:o&&o.options||[]}))}},loadOptions:function(e){if(this.props.onInputChange){var t=this.props.onInputChange(e);null!=t&&(e=""+t)}if(this.props.ignoreAccents&&(e=(0,h["default"])(e)),this.props.ignoreCase&&(e=e.toLowerCase()),this._lastInput=e,e.length<this.props.minimumInput)return this.resetState();var n=u(this.state.cache,e);if(n)return this.setState({options:n.options});this.setState({isLoading:!0});var r=this.getResponseHandler(e),o=s(this.props.loadOptions(e,r),r);return o?o.then(function(){return e}):e},render:function(){var e=this.props.noResultsText,t=this.state,n=t.isLoading,r=t.options;this.props.isLoading&&(n=!0);var o=n?this.props.loadingPlaceholder:this.props.placeholder;return n?e=this.props.searchingText:!r.length&&this._lastInput.length<this.props.minimumInput&&(e=this.props.searchPromptText),c["default"].createElement(f["default"],a({},this.props,{ref:"select",isLoading:n,noResultsText:e,onInputChange:this.loadOptions,options:r,placeholder:o}))}});e.exports=y},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=r(o),u=n(33),s=r(u),a=i["default"].createClass({displayName:"Option",propTypes:{children:i["default"].PropTypes.node,className:i["default"].PropTypes.string,instancePrefix:i["default"].PropTypes.string.isRequired,isDisabled:i["default"].PropTypes.bool,isFocused:i["default"].PropTypes.bool,isSelected:i["default"].PropTypes.bool,onFocus:i["default"].PropTypes.func,onSelect:i["default"].PropTypes.func,onUnfocus:i["default"].PropTypes.func,option:i["default"].PropTypes.object.isRequired,optionIndex:i["default"].PropTypes.number},blockEvent:function(e){e.preventDefault(),e.stopPropagation(),"A"===e.target.tagName&&"href"in e.target&&(e.target.target?window.open(e.target.href,e.target.target):window.location.href=e.target.href)},handleMouseDown:function(e){e.preventDefault(),e.stopPropagation(),this.props.onSelect(this.props.option,e)},handleMouseEnter:function(e){this.onFocus(e)},handleMouseMove:function(e){this.onFocus(e)},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},onFocus:function(e){this.props.isFocused||this.props.onFocus(this.props.option,e)},render:function(){var e=this.props,t=e.option,n=e.instancePrefix,r=e.optionIndex,o=(0,
s["default"])(this.props.className,t.className);return t.disabled?i["default"].createElement("div",{className:o,onMouseDown:this.blockEvent,onClick:this.blockEvent},this.props.children):i["default"].createElement("div",{className:o,style:t.style,role:"option",onMouseDown:this.handleMouseDown,onMouseEnter:this.handleMouseEnter,onMouseMove:this.handleMouseMove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEnd,id:n+"-option-"+r,title:t.title},this.props.children)}});e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=r(o),u=n(33),s=r(u),a=i["default"].createClass({displayName:"Value",propTypes:{children:i["default"].PropTypes.node,disabled:i["default"].PropTypes.bool,id:i["default"].PropTypes.string,onClick:i["default"].PropTypes.func,onRemove:i["default"].PropTypes.func,value:i["default"].PropTypes.object.isRequired},handleMouseDown:function(e){if("mousedown"!==e.type||0===e.button)return this.props.onClick?(e.stopPropagation(),void this.props.onClick(this.props.value,e)):void(this.props.value.href&&e.stopPropagation())},onRemove:function(e){e.preventDefault(),e.stopPropagation(),this.props.onRemove(this.props.value)},handleTouchEndRemove:function(e){this.dragging||this.onRemove(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},renderRemoveIcon:function(){if(!this.props.disabled&&this.props.onRemove)return i["default"].createElement("span",{className:"Select-value-icon","aria-hidden":"true",onMouseDown:this.onRemove,onTouchEnd:this.handleTouchEndRemove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},"×")},renderLabel:function(){var e="Select-value-label";return this.props.onClick||this.props.value.href?i["default"].createElement("a",{className:e,href:this.props.value.href,target:this.props.value.target,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleMouseDown},this.props.children):i["default"].createElement("span",{className:e,role:"option","aria-selected":"true",id:this.props.id},this.props.children)},render:function(){return i["default"].createElement("div",{className:(0,s["default"])("Select-value",this.props.value.className),style:this.props.value.style,title:this.props.value.title},this.renderRemoveIcon(),this.renderLabel())}});e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){return function(n,r,o){var u=e(n,r,o),a=u.dispatch,l=[],c={getState:u.getState,dispatch:function(e){return a(e)}};return l=t.map(function(e){return e(c)}),a=s["default"].apply(void 0,l)(u.dispatch),i({},u,{dispatch:a})}}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o;var u=n(75),s=r(u)},function(e,t){"use strict";function n(e,t){return function(){return t(e.apply(void 0,arguments))}}function r(e,t){if("function"==typeof e)return n(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var r=Object.keys(e),o={},i=0;i<r.length;i++){var u=r[i],s=e[u];"function"==typeof s&&(o[u]=n(s,t))}return o}t.__esModule=!0,t["default"]=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=t&&t.type,r=n&&'"'+n.toString()+'"'||"an action";return"Given action "+r+', reducer "'+e+'" returned undefined. To ignore an action, you must explicitly return the previous state.'}function i(e){Object.keys(e).forEach(function(t){var n=e[t],r=n(void 0,{type:s.ActionTypes.INIT});if("undefined"==typeof r)throw new Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var o="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof n(void 0,{type:o}))throw new Error('Reducer "'+t+'" returned undefined when probed with a random type. '+("Don't try to handle "+s.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}function u(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++){var u=t[r];"function"==typeof e[u]&&(n[u]=e[u])}var s,a=Object.keys(n);try{i(n)}catch(l){s=l}return function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments[1];if(s)throw s;for(var r=!1,i={},u=0;u<a.length;u++){var l=a[u],c=n[l],p=e[l],f=c(p,t);if("undefined"==typeof f){var d=o(l,t);throw new Error(d)}i[l]=f,r=r||f!==p}return r?i:e}}t.__esModule=!0,t["default"]=u;var s=n(34),a=n(3),l=(r(a),n(76));r(l)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.compose=t.applyMiddleware=t.bindActionCreators=t.combineReducers=t.createStore=void 0;var o=n(34),i=r(o),u=n(245),s=r(u),a=n(244),l=r(a),c=n(243),p=r(c),f=n(75),d=r(f),h=n(76);r(h);t.createStore=i["default"],t.combineReducers=s["default"],t.bindActionCreators=l["default"],t.applyMiddleware=p["default"],t.compose=d["default"]},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function r(e,t){return e===t}function o(e){var t=arguments.length<=1||void 0===arguments[1]?r:arguments[1],n=null,o=null;return function(){for(var r=arguments.length,i=Array(r),u=0;u<r;u++)i[u]=arguments[u];return null!==n&&n.length===i.length&&i.every(function(e,r){return t(e,n[r])})?o:(o=e.apply(void 0,i),n=i,o)}}function i(e){var t=Array.isArray(e[0])?e[0]:e;if(!t.every(function(e){return"function"==typeof e})){var n=t.map(function(e){return typeof e}).join(", ");throw new Error("Selector creators expect all input-selectors to be functions, "+("instead received the following types: ["+n+"]"))}return t}function u(e){for(var t=arguments.length,r=Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return function(){for(var t=arguments.length,o=Array(t),u=0;u<t;u++)o[u]=arguments[u];var s=0,a=o.pop(),l=i(o),c=e.apply(void 0,[function(){return s++,a.apply(void 0,arguments)}].concat(r)),p=function(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];var u=l.map(function(n){return n.apply(void 0,[e,t].concat(o))});return c.apply(void 0,n(u))};return p.resultFunc=a,p.recomputations=function(){return s},p.resetRecomputations=function(){return s=0},p}}function s(){return u(o).apply(void 0,arguments)}function a(e){var t=arguments.length<=1||void 0===arguments[1]?s:arguments[1];if("object"!=typeof e)throw new Error("createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);var n=Object.keys(e);return t(n.map(function(t){return e[t]}),function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.reduce(function(e,t,r){return e[n[r]]=t,e},{})})}t.__esModule=!0,t.defaultMemoize=o,t.createSelectorCreator=u,t.createSelector=s,t.createStructuredSelector=a},function(e,t,n){!function(t,r){e.exports=r(n(1))}(this,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e,t,n){if(!e)return n(null,[]);t=new RegExp(t,"i");for(var r=[],o=0,i=e.length;o<i;o++)t.exec(e[o].title)&&r.push(e[o]);n(null,r)}var o=n(1),i=n(2),u=o.createClass({displayName:"Autocomplete",propTypes:{options:o.PropTypes.any,search:o.PropTypes.func,resultRenderer:o.PropTypes.oneOfType([o.PropTypes.component,o.PropTypes.func]),value:o.PropTypes.object,onChange:o.PropTypes.func,onError:o.PropTypes.func,onFocus:o.PropTypes.func},getDefaultProps:function(){return{search:r}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=i(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return o.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},o.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.onSearchInputFocus,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),o.createElement(s,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onSearchInputFocus:function(){this.props.onFocus&&this.props.onFocus(),this.showAllResults()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var n=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[n]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;e<t;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),s=o.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,n=t.className,r=function(e,t){var n={},r=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var o in e)r.call(e,o)&&!r.call(t,o)&&(n[o]=e[o]);return n}(t,{className:1});return o.createElement("ul",o.__spread({},r,{style:e,className:n+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),n=this.props.renderer||a;return o.createElement(n,{ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),n=t.scrollTop,r=t.offsetHeight,o=e.getDOMNode(),i=o.offsetTop,u=i+o.offsetHeight;i<n?(this.ignoreFocus=!0,t.scrollTop=i):u-n>r&&(this.ignoreFocus=!0,t.scrollTop=u-r)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var n=this.getDOMNode(),r=n.scrollTop,o=n.offsetHeight,i=e.target,u=i.offsetTop,s=u+i.offsetHeight;s>r&&u<r+o&&this.props.onFocus(t)}}}),a=o.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=i({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return o.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},o.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=u},function(t,n){t.exports=e},function(e,t,n){function r(){for(var e,t="",n=0;n<arguments.length;n++)if(e=arguments[n])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+r.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,i;"undefined"!=typeof e&&e.exports&&(e.exports=r),o=[],i=function(){return r}.apply(t,o),!(void 0!==i&&(e.exports=i))}])})},function(e,t,n){"use strict";e.exports=n(250)(window||window||this)},function(e,t){"use strict";e.exports=function(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}}]))}); |
src/components/Terms/index.js | chejen/GoodJobShare | import React from 'react';
import Helmet from 'react-helmet';
import { Section, Wrapper } from 'common/base';
import PageBanner from 'common/PageBanner';
import editorStyles from 'common/Editor.module.css';
import { HELMET_DATA } from '../../constants/helmetData';
const Terms = () => (
<main>
<Helmet {...HELMET_DATA.USER_TERMS} />
<PageBanner heading="使用者條款" />
<Section padding>
<Wrapper size="m" className={editorStyles.editor}>
<p>
GoodJob 歡迎您! 一旦您使用 GoodJob 的產品、軟體、網站或服務(以下簡稱「本服務」),即代表您同意遵守以下條款,及其未來修訂公告的最新版本。
</p>
<h2>
使用者對其提供之內容自負法律責任
</h2>
<p>
由使用者上載至本服務的薪資、工時、工作評價、面試經驗等一切內容,均由提供該內容的使用者自負法律責任。GoodJob 對於使用者經由本服務張貼之內容,不保證其正確性、完整性或品質。在任何情況下,GoodJob 均不為任何使用者提供之內容負責,包含但不限於任何錯誤或遺漏,及其衍生之任何損失或損害。
</p>
<h2>GoodJob 有權利、但無義務移除不當內容</h2>
<p>GoodJob 並未針對使用者提供之內容事先加以審查,但 GoodJob 有權(但無義務)依其自行之考量,拒絕或移除使用者經由本服務提供之內容,包括有違法、侵權、虛偽不實之虞或其他 GoodJob 認為不適當之內容。</p>
<h2>使用者承諾遵守法律與契約義務</h2>
<p>
您承諾絕不為任何非法目的或以任何非法方式使用本服務,並承諾遵守中華民國相關法規及一切使用網際網路之國際慣例。您若是中華民國以外之使用者,並同意遵守所屬國家或地域之法令。您同意並保證不得利用本服務從事侵害他人權益或違法之行為,包括但不限於:
</p>
<ul>
<li>於本服務上載任何不實、誹謗、侮辱、具威脅性、攻擊性、不雅、猥褻或其他不法的內容</li>
<li>侵害他人名譽、隱私權、營業秘密、商標權、著作權、專利權、其他智慧財產權及其他權利</li>
<li>違反依法律或契約所應負之保密義務</li>
<li>冒用他人名義或帳號使用本服務</li>
<li>其他 GoodJob 有正當理由認為不適當之行為</li>
</ul>
<h2>服務中斷或故障時</h2>
<p>本服務如因維修或其他原因出現中斷或故障,使用者宜自行採取適當防護措施,GoodJob 對使用本服務造成的資料喪失或其他損害,不負損害賠償責任。</p>
<h2>準據法與管轄法院</h2>
<p>本使用者條款之解釋、適用與相關爭議,除法律另有規定者外,均應依照中華民國法律處理,並以台灣台北地方法院為第一審管轄法院。</p>
</Wrapper>
</Section>
</main>
);
export default Terms;
|
src/components/modals/Newproject/Newproject.js | Convicted202/PixelShape | import React, { Component } from 'react';
import ModalWindow from '../../modalwindow/Modalwindow';
import ToggleCheckbox from '../../togglecheckbox/Togglecheckbox';
import StateLoader from '../../../statemanager/StateLoader';
import { projectExtension } from '../../../defaults/constants';
import './newproject.styl';
class NewProjectModal extends Component {
constructor (props) {
super(props);
this.state = {
importedFileName: null,
importedData: null,
loading: false,
progress: 0
};
}
onFileLoaded (data) {
this.setState({
importedFileName: data.file.name,
importedData: data.json,
loading: false,
progress: 0
});
}
onStep (current, total) {
this.setState({
progress: Math.round(100 * current / total)
});
}
startLoading () {
this.setState({
loading: true
});
}
handleUpload () {
const file = this._input.files[0],
callback = this.onFileLoaded.bind(this),
stepCallback = this.onStep.bind(this);
// IE11 fix
if (!file) return;
this.startLoading();
if (file.type.match(/image\/gif/)) StateLoader.uploadGif(file, callback, stepCallback);
if (file.name.match(projectExtension)) StateLoader.upload(file, callback);
}
getFileNotification () {
if (this.state.importedFileName) {
return (
<p className="newproject-import__info-file">{ this.state.importedFileName }</p>
);
}
if (this.state.loading) return this.getFileLoadingTracking();
return [
<p key="info" className="newproject-import__info-row">No file imported.</p>,
<p key="note" className="newproject-import__info-row newproject-import__info-row__note">New project will be created.</p>
];
}
getFileLoadingTracking () {
return [
<div key="spinner" className="newproject-import__info-spinner"></div>,
<div key="tracking" className="newproject-import__info-tracking">{`${this.state.progress}%`}</div>
];
}
dropImportedFile () {
this.setState({
importedFileName: null,
importedData: null
});
this._input.value = '';
}
confirm () {
if (this.state.importedData)
this.props.uploadProject(this.state.importedData);
else {
if (this.props.resetPaletteOn) this.props.resetUserColors();
this.props.resetFramesState(this.props.imageSize.width, this.props.imageSize.height);
}
this.dropImportedFile();
this.props.closeModal();
}
cancel () {
this.dropImportedFile();
this.props.closeModal();
}
render () {
return (
<ModalWindow
title="New project"
ok={{ text: 'Create', action: this.confirm.bind(this) }}
cancel={{ text: 'Cancel', action: this.cancel.bind(this) }}
isShown={this.props.isShown}>
<ToggleCheckbox
value={this.props.resetPaletteOn}
onChange={this.props.toggleResetPalette.bind(this)}>
Reset palette
</ToggleCheckbox>
<div className="newproject-import">
<div className="newproject-import__upload">
<input
id="project-import"
type="file"
accept={[projectExtension, '.gif'].join()}
ref={input => this._input = input}
style={{ display: 'none' }}
onChange={this.handleUpload.bind(this)} />
<label htmlFor="project-import" className="newproject-import__upload-btn">
Import
<svg className="newproject-import__upload-btn__icon" viewBox="0 0 24 24" width="24" height="24">
<use xlinkHref={'#upload'}></use>
</svg>
</label>
</div>
<div className="newproject-import__info">
{ this.getFileNotification() }
</div>
</div>
<div className="newproject-import__warning">You are allowed to load only files of <strong>.gif</strong> and <strong>.pxlsh</strong> formats</div>
</ModalWindow>
);
}
}
export default NewProjectModal;
|
ajax/libs/forerunnerdb/1.3.643/fdb-core+views.js | honestree/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('./core'),
View = _dereq_('../lib/View');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Crc,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: updated
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback(); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback(false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
self.chainSend('insert', doc, {index: index});
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
case '2d':
index = new Index2d(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":31}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, data, options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":27}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":27}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload: ', def);
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":31}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":31}],30:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Handler for Date() objects
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
// Handler for RegExp() objects
this.registerEncoder('$regexp', function (data) {
if (data instanceof RegExp) {
return {
source: data.source,
params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '')
};
}
});
this.registerDecoder('$regexp', function (data) {
var type = typeof data;
if (type === 'object') {
return new RegExp(data.source, data.params);
} else if (type === 'string') {
return new RegExp(data);
}
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
if (data) {
return this._parse(JSON.parse(data));
}
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],31:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.643',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}],33:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload');
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
// Hook our own join change event and refresh after change
this.on('joinChange', function () {
self.refresh();
});
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
// Check if we have an existing reactor io
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._privateData.deferEmit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._privateData.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._privateData.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
}
});
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
pubData,
refreshResults,
joinArr,
i, k;
if (this._from) {
pubData = this.publicData();
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this.publicData().indexOf.apply(this.publicData(), arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
|
src/js/components/icons/base/StandardsDevice.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-standards-device`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'standards-device');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M17.4191981,5.86998785 L22.2891859,1 L17.0692588,1 L12.0145808,6.05467801 L6.95018226,1 L1.73025516,1 L6.60024301,5.86998785 L0,5.86998785 L0,23.6488457 L3.47023086,23.6488457 L7.23207776,23.6488457 L8.68043742,23.6488457 L11.9951397,20.3341434 L15.309842,23.6488457 L17.2345079,23.6488457 L20.5297691,23.6488457 L24,23.6488457 L24,5.86998785 L17.4191981,5.86998785 L17.4191981,5.86998785 Z M12.0048603,15.1044957 L7.16403402,19.9550425 L3.69380316,19.9550425 L3.69380316,9.56379101 L20.3256379,9.56379101 L20.3256379,19.9550425 L16.855407,19.9550425 L12.0048603,15.1044957 L12.0048603,15.1044957 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'StandardsDevice';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
docs/app/Examples/elements/Button/Groups/ButtonGroupIconExample.js | jcarbo/stardust | import React from 'react'
import { Button } from 'stardust'
const ButtonIconButtonsExample = () => (
<div>
<Button.Group>
<Button icon='align left' />
<Button icon='align center' />
<Button icon='align right' />
<Button icon='align justify' />
</Button.Group>
{' '}
<Button.Group>
<Button icon='bold' />
<Button icon='underline' />
<Button icon='text width' />
</Button.Group>
</div>
)
export default ButtonIconButtonsExample
|
packages/mineral-ui-icons/src/IconMood.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconMood(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</g>
</Icon>
);
}
IconMood.displayName = 'IconMood';
IconMood.category = 'social';
|
packages/editor/src/components/Icons/Superscript.js | strues/boldr | import React from 'react';
import Icon from './Icon';
const Superscript = props => (
<Icon viewBox="0 0 512 512" {...props}>
<path d="M500.065 270.691H383.611c3.092-18.342 24.015-34.022 47.984-50.038 34.415-22.995 76.138-50.642 76.138-103.222 0-50.301-38.48-85.431-93.577-85.431-37.629 0-72.116 19.458-90.794 50.314-3.321 5.486-1.706 12.623 3.631 16.18l24.42 16.276c5.32 3.546 12.556 2.364 16.309-2.812 10.243-14.13 24.825-24.68 42.168-24.68 26.189 0 37.912 17.288 37.912 34.421 0 21.219-22.471 36.854-48.49 54.956-35.769 24.886-80.283 55.857-80.283 114.931 0 5.562.558 11.025 1.433 17.915.762 5.997 5.861 10.499 11.906 10.499H500c6.627 0 12-5.373 12-12v-25.375c0-6.591-5.343-11.934-11.935-11.934zM245.92 432H276c6.627 0 12 5.373 12 12v24c0 6.627-5.373 12-12 12h-59.675a12 12 0 0 1-10.19-5.662l-54.204-87.153c-3.262-4.892-6.132-10.128-7.99-13.714-1.773 3.559-4.575 8.823-8.129 14.317l-53.058 86.488A12.005 12.005 0 0 1 72.524 480H12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h31.728l65.48-100.449L48.755 240H12c-6.627 0-12-5.373-12-12v-24c0-6.627 5.373-12 12-12h66.764a12 12 0 0 1 10.234 5.734l47.525 77.624c2.986 4.976 5.742 10.45 7.54 14.194 1.856-3.636 4.718-8.991 7.984-14.217l48.63-77.701A12 12 0 0 1 210.849 192H276c6.627 0 12 5.373 12 12v24c0 6.627-5.373 12-12 12h-36.769l-60.974 90.984L245.92 432z" />
</Icon>
);
Superscript.defaultProps = { name: 'Superscript' };
export default Superscript;
|
js/src/Connection/connection.js | destenson/ethcore--parity | // 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 React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import GradientBg from '@parity/ui/lib/GradientBg';
import Input from '@parity/ui/lib/Form/Input';
import { CompareIcon, ComputerIcon, DashboardIcon, VpnIcon } from '@parity/ui/lib/Icons';
import styles from './connection.css';
class Connection extends Component {
static contextTypes = {
api: PropTypes.object.isRequired
}
static propTypes = {
isConnected: PropTypes.bool,
isConnecting: PropTypes.bool,
needsToken: PropTypes.bool
}
state = {
loading: false,
token: '',
validToken: false
}
render () {
const { isConnecting, isConnected, needsToken } = this.props;
if (!isConnecting && isConnected) {
return null;
}
return (
<div>
<div className={ styles.overlay } />
<div className={ styles.modal }>
<GradientBg className={ styles.body }>
<div className={ styles.icons }>
<div className={ styles.icon }>
<ComputerIcon className={ styles.svg } />
</div>
<div className={ styles.iconSmall }>
<CompareIcon className={ `${styles.svg} ${styles.pulse}` } />
</div>
<div className={ styles.icon }>
{
needsToken
? <VpnIcon className={ styles.svg } />
: <DashboardIcon className={ styles.svg } />
}
</div>
</div>
{
needsToken
? this.renderSigner()
: this.renderPing()
}
</GradientBg>
</div>
</div>
);
}
renderSigner () {
const { loading, token, validToken } = this.state;
const { isConnecting, needsToken } = this.props;
if (needsToken && !isConnecting) {
return (
<div className={ styles.info }>
<div>
<FormattedMessage
id='connection.noConnection'
defaultMessage='Unable to make a connection to the Parity Secure API. To update your secure token or to generate a new one, run: {newToken} and paste the generated token into the space below.'
values={ {
newToken: <div className={ styles.console }>parity signer new-token</div>
} }
/>
</div>
<div className={ styles.timestamp }>
<FormattedMessage
id='connection.timestamp'
defaultMessage='Ensure that both the Parity node and this machine connecting have computer clocks in-sync with each other and with a timestamp server, ensuring both successful token validation and block operations.'
/>
</div>
<div className={ styles.form }>
<Input
className={ styles.formInput }
autoFocus
disabled={ loading }
error={
validToken || (!token || !token.length)
? null
: (
<FormattedMessage
id='connection.invalidToken'
defaultMessage='invalid signer token'
/>
)
}
hint={
<FormattedMessage
id='connection.token.hint'
defaultMessage='Insert the generated token here'
/>
}
onChange={ this.onChangeToken }
value={ token }
/>
</div>
</div>
);
}
return (
<div className={ styles.info }>
<FormattedMessage
id='connection.connectingAPI'
defaultMessage='Connecting to the Parity Secure API.'
/>
</div>
);
}
renderPing () {
return (
<div className={ styles.info }>
<FormattedMessage
id='connection.connectingNode'
defaultMessage='Connecting to the Parity Node. If this informational message persists, please ensure that your Parity node is running and reachable on the network.'
/>
</div>
);
}
validateToken = (_token) => {
const token = _token.trim();
const validToken = /^[a-zA-Z0-9]{4}(-)?[a-zA-Z0-9]{4}(-)?[a-zA-Z0-9]{4}(-)?[a-zA-Z0-9]{4}$/.test(token);
return {
token,
validToken
};
}
onChangeToken = (event, _token) => {
const { token, validToken } = this.validateToken(_token || event.target.value);
this.setState({ token, validToken }, () => {
validToken && this.setToken();
});
}
setToken = () => {
const { api } = this.context;
const { token } = this.state;
this.setState({ loading: true });
return api
.updateToken(token, 0)
.then((isValid) => {
this.setState({
loading: isValid || false,
validToken: isValid
});
});
}
}
function mapStateToProps (state) {
const { isConnected, isConnecting, needsToken } = state.nodeStatus;
return {
isConnected,
isConnecting,
needsToken
};
}
export default connect(
mapStateToProps,
null
)(Connection);
|
packages/ui-toolkit/src/section-list/index.js | geek/joyent-portal | import React from 'react';
import styled from 'styled-components';
import remcalc from 'remcalc';
import Baseline from '../baseline';
const UnorderedList = styled.ul`
background: ${props => props.theme.disabled};
list-style-type: none;
padding: ${remcalc(13)} ${remcalc(0)};
margin: ${remcalc(18)} 0 0 0;
max-height: ${remcalc(50)};
overflow-x: auto;
overflow-y: hidden;
box-sizing: border-box;
display: inline-flex;
position: relative;
&:after {
width: 100%;
height: ${remcalc(1)};
background: ${props => props.theme.grey};
content: '';
position: absolute;
bottom: 0;
left: 0;
z-index: 1;
}
`;
/**
* @example ./usage.md
*/
const SectionList = ({ children, mode, ...rest }) => (
<UnorderedList {...rest}>{children}</UnorderedList>
);
export default Baseline(SectionList);
export { default as Item, Anchor } from './item';
|
react-flux-mui/js/material-ui/src/svg-icons/action/invert-colors.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInvertColors = (props) => (
<SvgIcon {...props}>
<path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/>
</SvgIcon>
);
ActionInvertColors = pure(ActionInvertColors);
ActionInvertColors.displayName = 'ActionInvertColors';
ActionInvertColors.muiName = 'SvgIcon';
export default ActionInvertColors;
|
app/containers/UserEdit/index.js | Princess310/antd-demo | /*
*
* UserEdit
*
* path --> userEdit
*
* page to show user detail info and edit for them
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { browserHistory } from 'react-router';
import pallete from 'styles/colors';
import { NavBar, List, WhiteSpace, Icon, Modal } from 'antd-mobile';
import Avatar from 'components/Avatar';
import AppContent from 'components/AppContent';
import { makeSelectCurrentUser } from './selectors';
const briefStyle = {
overflow: 'auto',
textOverflow: 'inherit',
whiteSpace: 'inherit',
};
const imgStyle = {
marginTop: '0.08rem',
marginRight: '0.08rem',
width: '2.2rem',
height: '2.2rem',
}
const Item = List.Item;
const Brief = Item.Brief;
const alert = Modal.alert;
export class UserEdit extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const { currentUser } = this.props;
return (
<div>
<NavBar
mode="light"
iconName={false}
leftContent={<Icon type={require('icons/ali/返回.svg')} size="sm" color={pallete.theme} />}
onLeftClick={() => browserHistory.goBack()}
>
{currentUser.nickname}
</NavBar>
<AppContent>
<WhiteSpace size="md" />
<List>
<Item
thumb={<Avatar
id={currentUser.id}
avatar={currentUser.avatar}
isVip={Number(currentUser.verify_status) === 2}
/>}
multipleLine
arrow="horizontal"
onClick={() => {
browserHistory.push('/userEditBasic');
}}
>
<div>{currentUser.nickname}</div>
<Brief>
<section style={{ marginTop: '0.04rem' }}>
{currentUser.position !== '' && <span>{currentUser.position}</span>}
{currentUser.company !== '' &&
<span
style={{
display: 'inline-block',
marginLeft: '0.24rem',
paddingLeft: '0.24rem',
borderLeft: `1px ${pallete.border.normal} solid`,
}}
>{currentUser.company}</span>}
</section>
</Brief>
</Item>
</List>
<WhiteSpace size="md" />
<List>
<Item
extra={currentUser.mobile === '' ? '未绑定' : currentUser.mobile}
arrow="horizontal"
onClick={() => {
browserHistory.push('/resetMobile');
}}
>绑定手机</Item>
</List>
<WhiteSpace size="md" />
<List>
<Item
extra={currentUser.tag_identity_name}
arrow="horizontal"
onClick={() => {
const editNumber = currentUser.role_edit_number;
if (editNumber && editNumber >= 2) {
alert('您已经修改过行业角色信息,不能再次修改', '', [
{ text: '我知道了', onPress: () => console.log('confirm') },
])
} else {
alert('行业角色信息只能修改一次,并且会清空您之前的所有信息,请谨慎修改', '', [
{ text: '我知道了', onPress: () => console.log('cancel') },
{ text: '确定修改', onPress: () => {
browserHistory.push('/userEditIdentity');
}, style: { fontWeight: 'bold' } },
]);
};
}}
>行业角色</Item>
<Item
extra={currentUser.main_service_name}
arrow="horizontal"
onClick={() => {
browserHistory.push('/userEditService');
}}
>主营类别</Item>
</List>
<WhiteSpace size="md" />
<List>
<Item
extra={currentUser.company_locate === '' ? '未设置' : currentUser.company_locate}
arrow="horizontal"
onClick={() => {
browserHistory.push('/selectAddress');
}}
>工作地区</Item>
<Item
arrow="horizontal"
multipleLine
onClick={() => {
browserHistory.push('/userEditCompany');
}}
>
公司地址
<Brief style={briefStyle}>
{currentUser.address === '' ? '请填写您的公司地址' : currentUser.address}
</Brief>
</Item>
</List>
<WhiteSpace size="md" />
<List>
<Item
arrow="horizontal"
multipleLine
wrap
onClick={() => {
browserHistory.push('/userEditIntro');
}}
>
业务介绍
<Brief style={briefStyle}>
{currentUser.business_intro === '' ? '完善您的业务介绍,让大家更容易了解您~' : currentUser.business_intro}
</Brief>
</Item>
</List>
<WhiteSpace size="md" />
<List>
<Item
arrow="horizontal"
onClick={() => {
browserHistory.push('/userEditPics');
}}
>展示图片</Item>
</List>
<div style={{ paddingLeft: '0.08rem' }}>
{currentUser.pictures && currentUser.pictures.map((p, i) => (
<img key={i} role="presentation" src={p} style={imgStyle} />
))}
</div>
<WhiteSpace size="md" />
</AppContent>
</div>
);
}
}
UserEdit.propTypes = {
/**
* reducer: the current user info
*/
currentUser: PropTypes.object,
};
const mapStateToProps = createStructuredSelector({
currentUser: makeSelectCurrentUser(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(UserEdit);
|
examples/todomvc/test/components/Footer.spec.js | camsong/redux | import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Footer from '../../components/Footer'
import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters'
function setup(propOverrides) {
const props = Object.assign({
completedCount: 0,
activeCount: 0,
filter: SHOW_ALL,
onClearCompleted: expect.createSpy(),
onShow: expect.createSpy()
}, propOverrides)
const renderer = TestUtils.createRenderer()
renderer.render(<Footer {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output
}
}
function getTextContent(elem) {
const children = Array.isArray(elem.props.children) ?
elem.props.children : [ elem.props.children ]
return children.reduce(function concatText(out, child) {
// Children are either elements or text strings
return out + (child.props ? getTextContent(child) : child)
}, '')
}
describe('components', () => {
describe('Footer', () => {
it('should render container', () => {
const { output } = setup()
expect(output.type).toBe('footer')
expect(output.props.className).toBe('footer')
})
it('should display active count when 0', () => {
const { output } = setup({ activeCount: 0 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('No items left')
})
it('should display active count when above 0', () => {
const { output } = setup({ activeCount: 1 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('1 item left')
})
it('should render filters', () => {
const { output } = setup()
const [ , filters ] = output.props.children
expect(filters.type).toBe('ul')
expect(filters.props.className).toBe('filters')
expect(filters.props.children.length).toBe(3)
filters.props.children.forEach(function checkFilter(filter, i) {
expect(filter.type).toBe('li')
const a = filter.props.children
expect(a.props.className).toBe(i === 0 ? 'selected' : '')
expect(a.props.children).toBe({
0: 'All',
1: 'Active',
2: 'Completed'
}[i])
})
})
it('should call onShow when a filter is clicked', () => {
const { output, props } = setup()
const [ , filters ] = output.props.children
const filterLink = filters.props.children[1].props.children
filterLink.props.onClick({})
expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE)
})
it('shouldnt show clear button when no completed todos', () => {
const { output } = setup({ completedCount: 0 })
const [ , , clear ] = output.props.children
expect(clear).toBe(undefined)
})
it('should render clear button when completed todos', () => {
const { output } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
expect(clear.type).toBe('button')
expect(clear.props.children).toBe('Clear completed')
})
it('should call onClearCompleted on clear button click', () => {
const { output, props } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
clear.props.onClick({})
expect(props.onClearCompleted).toHaveBeenCalled()
})
})
})
|
imports/ui/components/InputHint/InputHint.js | haraneesh/mydev | import React from 'react';
import PropTypes from 'prop-types';
import './InputHint.scss';
const InputHint = ({ children }) => (
<div className="InputHint">
{children}
</div>
);
InputHint.propTypes = {
children: PropTypes.node.isRequired,
};
export default InputHint;
|
ajax/libs/swagger-ui/3.44.1/swagger-ui-es-bundle-core.js | cdnjs/cdnjs | /*! For license information please see swagger-ui-es-bundle-core.js.LICENSE.txt */
module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/dist",n(n.s=412)}([function(e,t){e.exports=require("react")},function(e,t){e.exports=require("immutable")},function(e,t,n){e.exports=n(444)},function(e,t,n){var r=n(194);e.exports=function(e,t,n){return t in e?r(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(473)},function(e,t,n){"use strict";(function(e){n.d(t,"t",(function(){return be})),n.d(t,"A",(function(){return Ee})),n.d(t,"i",(function(){return xe})),n.d(t,"w",(function(){return Se})),n.d(t,"r",(function(){return we})),n.d(t,"u",(function(){return je})),n.d(t,"s",(function(){return Oe})),n.d(t,"p",(function(){return Ce})),n.d(t,"v",(function(){return _e})),n.d(t,"y",(function(){return Ae})),n.d(t,"z",(function(){return ke})),n.d(t,"K",(function(){return Ie})),n.d(t,"f",(function(){return Pe})),n.d(t,"n",(function(){return Te})),n.d(t,"h",(function(){return Re})),n.d(t,"E",(function(){return Ne})),n.d(t,"L",(function(){return De})),n.d(t,"o",(function(){return ze})),n.d(t,"D",(function(){return Fe})),n.d(t,"a",(function(){return Je})),n.d(t,"I",(function(){return We})),n.d(t,"b",(function(){return He})),n.d(t,"H",(function(){return $e})),n.d(t,"G",(function(){return Ye})),n.d(t,"F",(function(){return Ke})),n.d(t,"k",(function(){return Ge})),n.d(t,"d",(function(){return Ze})),n.d(t,"g",(function(){return Xe})),n.d(t,"m",(function(){return Qe})),n.d(t,"l",(function(){return et})),n.d(t,"e",(function(){return tt})),n.d(t,"J",(function(){return nt})),n.d(t,"x",(function(){return rt})),n.d(t,"B",(function(){return at})),n.d(t,"C",(function(){return ot})),n.d(t,"j",(function(){return it})),n.d(t,"c",(function(){return st})),n.d(t,"q",(function(){return ut}));var r=n(15),a=n.n(r),o=(n(16),n(45)),i=n.n(o),s=n(19),c=n.n(s),u=n(13),l=n.n(u),p=n(4),f=n.n(p),d=n(71),h=n.n(d),m=n(2),v=n.n(m),g=n(18),y=n.n(g),b=n(12),E=n.n(b),x=n(17),S=n.n(x),w=(n(29),n(21)),j=n.n(w),O=n(22),C=n.n(O),_=n(160),A=n.n(_),k=n(23),I=n.n(k),P=n(33),T=n.n(P),R=(n(35),n(30)),N=n.n(R),M=n(14),D=n.n(M),q=n(56),B=n.n(q),L=n(133),U=n.n(L),V=n(84),z=n.n(V),F=n(1),J=n.n(F),W=n(378),H=n(379),$=n.n(H),Y=n(211),K=n.n(Y),G=n(212),Z=n.n(G),X=n(161),Q=n.n(X),ee=n(269),te=n.n(ee),ne=n(101),re=n.n(ne),ae=n(55),oe=n.n(ae),ie=n(111),se=n(26),ce=n(381),ue=n.n(ce),le=n(113),pe=n(382),fe=n.n(pe),de=n(383),he=n.n(de),me=n(65),ve=n.n(me),ge="default",ye=function(e){return J.a.Iterable.isIterable(e)};function be(e){try{var t=JSON.parse(e);if(t&&"object"===c()(t))return t}catch(e){}return!1}function Ee(e){return je(e)?ye(e)?e.toJS():e:{}}function xe(e){var t,n;if(ye(e))return e;if(e instanceof se.a.File)return e;if(!je(e))return e;if(l()(e))return f()(n=J.a.Seq(e)).call(n,xe).toList();if(oe()(h()(e))){var r,a=function(e){if(!oe()(h()(e)))return e;var t,n={},r="_**[]",a={},o=i()(h()(e).call(e));try{for(o.s();!(t=o.n()).done;){var s=t.value;if(n[s[0]]||a[s[0]]&&a[s[0]].containsMultiple){var c,u,l,p;if(!a[s[0]])a[s[0]]={containsMultiple:!0,length:1},n[v()(l=v()(p="".concat(s[0])).call(p,r)).call(l,a[s[0]].length)]=n[s[0]],delete n[s[0]];a[s[0]].length+=1,n[v()(c=v()(u="".concat(s[0])).call(u,r)).call(c,a[s[0]].length)]=s[1]}else n[s[0]]=s[1]}}catch(e){o.e(e)}finally{o.f()}return n}(e);return f()(r=J.a.OrderedMap(a)).call(r,xe)}return f()(t=J.a.OrderedMap(e)).call(t,xe)}function Se(e){return l()(e)?e:[e]}function we(e){return"function"==typeof e}function je(e){return!!e&&"object"===c()(e)}function Oe(e){return"function"==typeof e}function Ce(e){return l()(e)}var _e=Z.a;function Ae(e,t){var n;return j()(n=S()(e)).call(n,(function(n,r){return n[r]=t(e[r],r),n}),{})}function ke(e,t){var n;return j()(n=S()(e)).call(n,(function(n,r){var a=t(e[r],r);return a&&"object"===c()(a)&&C()(n,a),n}),{})}function Ie(e){return function(t){t.dispatch,t.getState;return function(t){return function(n){return"function"==typeof n?n(e()):t(n)}}}}function Pe(e){var t,n=e.keySeq();return n.contains(ge)?ge:A()(t=E()(n).call(n,(function(e){return"2"===(e+"")[0]}))).call(t).first()}function Te(e,t){if(!J.a.Iterable.isIterable(e))return J.a.List();var n=e.getIn(l()(t)?t:[t]);return J.a.List.isList(n)?n:J.a.List()}function Re(e){var t,n=[/filename\*=[^']+'\w*'"([^"]+)";?/i,/filename\*=[^']+'\w*'([^;]+);?/i,/filename="([^;]*);?"/i,/filename=([^;]*);?/i];if(T()(n).call(n,(function(n){return null!==(t=n.exec(e))})),null!==t&&t.length>1)try{return decodeURIComponent(t[1])}catch(e){console.error(e)}return null}function Ne(e){return t=e.replace(/\.[^./]*$/,""),K()($()(t));var t}function Me(e,t,n,r,o){if(!t)return[];var i=[],s=t.get("nullable"),u=t.get("required"),p=t.get("maximum"),d=t.get("minimum"),h=t.get("type"),m=t.get("format"),g=t.get("maxLength"),b=t.get("minLength"),x=t.get("uniqueItems"),S=t.get("maxItems"),w=t.get("minItems"),j=t.get("pattern"),O=n||u;if(s&&null===e||!h||!(O||"array"===h||!(!O&&!(null!=e))))return[];var C="string"===h&&e,_="array"===h&&l()(e)&&e.length,A="array"===h&&J.a.List.isList(e)&&e.count(),k=[C,_,A,"array"===h&&"string"==typeof e&&e,"file"===h&&e instanceof se.a.File,"boolean"===h&&(e||!1===e),"number"===h&&(e||0===e),"integer"===h&&(e||0===e),"object"===h&&"object"===c()(e)&&null!==e,"object"===h&&"string"==typeof e&&e],I=T()(k).call(k,(function(e){return!!e}));if(O&&!I&&!r)return i.push("Required field is not provided"),i;if("object"===h&&(null===o||"application/json"===o)){var P,R=e;if("string"==typeof e)try{R=JSON.parse(e)}catch(e){return i.push("Parameter string value must be valid JSON"),i}if(t&&t.has("required")&&Oe(u.isList)&&u.isList()&&y()(u).call(u,(function(e){void 0===R[e]&&i.push({propKey:e,error:"Required property not found"})})),t&&t.has("properties"))y()(P=t.get("properties")).call(P,(function(e,t){var n=Me(R[t],e,!1,r,o);i.push.apply(i,a()(f()(n).call(n,(function(e){return{propKey:t,error:e}}))))}))}if(j){var N=function(e,t){if(!new RegExp(t).test(e))return"Value must follow pattern "+t}(e,j);N&&i.push(N)}if(w&&"array"===h){var M=function(e,t){var n;if(!e&&t>=1||e&&e.length<t)return v()(n="Array must contain at least ".concat(t," item")).call(n,1===t?"":"s")}(e,w);M&&i.push(M)}if(S&&"array"===h){var D=function(e,t){var n;if(e&&e.length>t)return v()(n="Array must not contain more then ".concat(t," item")).call(n,1===t?"":"s")}(e,S);D&&i.push({needRemove:!0,error:D})}if(x&&"array"===h){var q=function(e,t){if(e&&("true"===t||!0===t)){var n=Object(F.fromJS)(e),r=n.toSet();if(e.length>r.size){var a=Object(F.Set)();if(y()(n).call(n,(function(e,t){E()(n).call(n,(function(t){return Oe(t.equals)?t.equals(e):t===e})).size>1&&(a=a.add(t))})),0!==a.size)return f()(a).call(a,(function(e){return{index:e,error:"No duplicates allowed."}})).toArray()}}}(e,x);q&&i.push.apply(i,a()(q))}if(g||0===g){var B=function(e,t){var n;if(e.length>t)return v()(n="Value must be no longer than ".concat(t," character")).call(n,1!==t?"s":"")}(e,g);B&&i.push(B)}if(b){var L=function(e,t){var n;if(e.length<t)return v()(n="Value must be at least ".concat(t," character")).call(n,1!==t?"s":"")}(e,b);L&&i.push(L)}if(p||0===p){var U=function(e,t){if(e>t)return"Value must be less than ".concat(t)}(e,p);U&&i.push(U)}if(d||0===d){var V=function(e,t){if(e<t)return"Value must be greater than ".concat(t)}(e,d);V&&i.push(V)}if("string"===h){var z;if(!(z="date-time"===m?function(e){if(isNaN(Date.parse(e)))return"Value must be a DateTime"}(e):"uuid"===m?function(e){if(e=e.toString().toLowerCase(),!/^[{(]?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[)}]?$/.test(e))return"Value must be a Guid"}(e):function(e){if(e&&"string"!=typeof e)return"Value must be a string"}(e)))return i;i.push(z)}else if("boolean"===h){var W=function(e){if("true"!==e&&"false"!==e&&!0!==e&&!1!==e)return"Value must be a boolean"}(e);if(!W)return i;i.push(W)}else if("number"===h){var H=function(e){if(!/^-?\d+(\.?\d+)?$/.test(e))return"Value must be a number"}(e);if(!H)return i;i.push(H)}else if("integer"===h){var $=function(e){if(!/^-?\d+$/.test(e))return"Value must be an integer"}(e);if(!$)return i;i.push($)}else if("array"===h){if(!_&&!A)return i;e&&y()(e).call(e,(function(e,n){var s=Me(e,t.get("items"),!1,r,o);i.push.apply(i,a()(f()(s).call(s,(function(e){return{index:n,error:e}}))))}))}else if("file"===h){var Y=function(e){if(e&&!(e instanceof se.a.File))return"Value must be a file"}(e);if(!Y)return i;i.push(Y)}return i}var De=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.isOAS3,a=void 0!==r&&r,o=n.bypassRequiredCheck,i=void 0!==o&&o,s=e.get("required"),c=Object(le.a)(e,{isOAS3:a}),u=c.schema,l=c.parameterContentMediaType;return Me(t,u,s,i,l)},qe=function(e,t,n){if(e&&(!e.xml||!e.xml.name)){if(e.xml=e.xml||{},!e.$$ref)return e.type||e.items||e.properties||e.additionalProperties?'<?xml version="1.0" encoding="UTF-8"?>\n\x3c!-- XML example cannot be generated; root element name is undefined --\x3e':null;var r=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=r[1]}return Object(ie.memoizedCreateXMLExample)(e,t,n)},Be=[{when:/json/,shouldStringifyTypes:["string"]}],Le=["object"],Ue=function(e,t,n,r){var o=Object(ie.memoizedSampleFromSchema)(e,t,r),i=c()(o),s=j()(Be).call(Be,(function(e,t){var r;return t.when.test(n)?v()(r=[]).call(r,a()(e),a()(t.shouldStringifyTypes)):e}),Le);return te()(s,(function(e){return e===i}))?N()(o,null,2):o},Ve=function(e,t,n,r){var a,o=Ue(e,t,n,r);try{"\n"===(a=ve.a.safeDump(ve.a.safeLoad(o),{lineWidth:-1}))[a.length-1]&&(a=I()(a).call(a,0,a.length-1))}catch(e){return console.error(e),"error: could not generate yaml example"}return a.replace(/\t/g," ")},ze=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;return e&&Oe(e.toJS)&&(e=e.toJS()),r&&Oe(r.toJS)&&(r=r.toJS()),/xml/.test(t)?qe(e,n,r):/(yaml|yml)/.test(t)?Ve(e,n,t,r):Ue(e,n,t,r)},Fe=function(){var e={},t=se.a.location.search;if(!t)return{};if(""!=t){var n=t.substr(1).split("&");for(var r in n)n.hasOwnProperty(r)&&(r=n[r].split("="),e[decodeURIComponent(r[0])]=r[1]&&decodeURIComponent(r[1])||"")}return e},Je=function(t){return(t instanceof e?t:e.from(t.toString(),"utf-8")).toString("base64")},We={operationsSorter:{alpha:function(e,t){return e.get("path").localeCompare(t.get("path"))},method:function(e,t){return e.get("method").localeCompare(t.get("method"))}},tagsSorter:{alpha:function(e,t){return e.localeCompare(t)}}},He=function(e){var t=[];for(var n in e){var r=e[n];void 0!==r&&""!==r&&t.push([n,"=",encodeURIComponent(r).replace(/%20/g,"+")].join(""))}return t.join("&")},$e=function(e,t,n){return!!Q()(n,(function(n){return re()(e[n],t[n])}))};function Ye(e){return"string"!=typeof e||""===e?"":Object(W.sanitizeUrl)(e)}function Ke(e){return!(!e||D()(e).call(e,"localhost")>=0||D()(e).call(e,"127.0.0.1")>=0||"none"===e)}function Ge(e){if(!J.a.OrderedMap.isOrderedMap(e))return null;if(!e.size)return null;var t=B()(e).call(e,(function(e,t){return U()(t).call(t,"2")&&S()(e.get("content")||{}).length>0})),n=e.get("default")||J.a.OrderedMap(),r=(n.get("content")||J.a.OrderedMap()).keySeq().toJS().length?n:null;return t||r}var Ze=function(e){return"string"==typeof e||e instanceof String?z()(e).call(e).replace(/\s/g,"%20"):""},Xe=function(e){return ue()(Ze(e).replace(/%20/g,"_"))},Qe=function(e){return E()(e).call(e,(function(e,t){return/^x-/.test(t)}))},et=function(e){return E()(e).call(e,(function(e,t){return/^pattern|maxLength|minLength|maximum|minimum/.test(t)}))};function tt(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0};if("object"!==c()(e)||l()(e)||null===e||!t)return e;var a=C()({},e);return y()(n=S()(a)).call(n,(function(e){e===t&&r(a[e],e)?delete a[e]:a[e]=tt(a[e],t,r)})),a}function nt(e){if("string"==typeof e)return e;if(e&&e.toJS&&(e=e.toJS()),"object"===c()(e)&&null!==e)try{return N()(e,null,2)}catch(t){return String(e)}return null==e?"":e.toString()}function rt(e){return"number"==typeof e?e.toString():e}function at(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.returnAll,r=void 0!==n&&n,a=t.allowHashes,o=void 0===a||a;if(!J.a.Map.isMap(e))throw new Error("paramToIdentifier: received a non-Im.Map parameter as input");var i,s,c,u=e.get("name"),l=e.get("in"),p=[];e&&e.hashCode&&l&&u&&o&&p.push(v()(i=v()(s="".concat(l,".")).call(s,u,".hash-")).call(i,e.hashCode()));l&&u&&p.push(v()(c="".concat(l,".")).call(c,u));return p.push(u),r?p:p[0]||""}function ot(e,t){var n,r=at(e,{returnAll:!0});return E()(n=f()(r).call(r,(function(e){return t[e]}))).call(n,(function(e){return void 0!==e}))[0]}function it(){return ct(fe()(32).toString("base64"))}function st(e){return ct(he()("sha256").update(e).digest("base64"))}function ct(e){return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}var ut=function(e){return!e||!(!ye(e)||!e.isEmpty())}}).call(this,n(477).Buffer)},function(e,t){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(194);function a(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),r(e,a.key,a)}}e.exports=function(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(669),a=n(672);e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=r(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(365),a=n(159),o=n(683),i=n(684);e.exports=function(e){var t=o();return function(){var n,o=a(e);if(t){var s=a(this).constructor;n=r(o,arguments,s)}else n=o.apply(this,arguments);return i(this,n)}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=require("prop-types")},function(e,t,n){e.exports=n(447)},function(e,t,n){e.exports=n(466)},function(e,t,n){e.exports=n(517)},function(e,t,n){var r=n(481),a=n(304),o=n(145),i=n(490);e.exports=function(e){return r(e)||a(e)||o(e)||i()},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(312),a=n(491),o=n(145),i=n(315);e.exports=function(e,t){return r(e)||a(e,t)||o(e,t)||i()},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(450)},function(e,t,n){e.exports=n(316)},function(e,t,n){var r=n(137),a=n(439);function o(t){return"function"==typeof r&&"symbol"==typeof a?(e.exports=o=function(e){return typeof e},e.exports.default=e.exports,e.exports.__esModule=!0):(e.exports=o=function(e){return e&&"function"==typeof r&&e.constructor===r&&e!==r.prototype?"symbol":typeof e},e.exports.default=e.exports,e.exports.__esModule=!0),o(t)}e.exports=o,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=require("reselect")},function(e,t,n){e.exports=n(468)},function(e,t,n){e.exports=n(461)},function(e,t,n){e.exports=n(463)},function(e,t,n){"use strict";var r=n(38),a=n(89).f,o=n(283),i=n(31),s=n(91),c=n(59),u=n(48),l=function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t};e.exports=function(e,t){var n,p,f,d,h,m,v,g,y=e.target,b=e.global,E=e.stat,x=e.proto,S=b?r:E?r[y]:(r[y]||{}).prototype,w=b?i:i[y]||(i[y]={}),j=w.prototype;for(f in t)n=!o(b?f:y+(E?".":"#")+f,e.forced)&&S&&u(S,f),h=w[f],n&&(m=e.noTargetGet?(g=a(S,f))&&g.value:S[f]),d=n&&m?m:t[f],n&&typeof h==typeof d||(v=e.bind&&n?s(d,r):e.wrap&&n?l(d):x&&"function"==typeof d?s(Function.call,d):d,(e.sham||d&&d.sham||h&&h.sham)&&c(v,"sham",!0),w[f]=v,x&&(u(i,p=y+"Prototype")||c(i,p,{}),i[p][f]=d,e.real&&j&&!j[f]&&c(j,f,d)))}},function(e,t,n){var r=n(345),a=n(346),o=n(628),i=n(347),s=n(633),c=n(635),u=n(640),l=n(194),p=n(3);function f(e,t){var n=r(e);if(a){var s=a(e);t&&(s=o(s).call(s,(function(t){return i(e,t).enumerable}))),n.push.apply(n,s)}return n}e.exports=function(e){for(var t=1;t<arguments.length;t++){var n,r=null!=arguments[t]?arguments[t]:{};if(t%2)s(n=f(Object(r),!0)).call(n,(function(t){p(e,t,r[t])}));else if(c)u(e,c(r));else{var a;s(a=f(Object(r))).call(a,(function(t){l(e,t,i(r,t))}))}}return e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";t.a=function(){var e={location:{},history:{},open:function(){},close:function(){},File:function(){}};if("undefined"==typeof window)return e;try{e=window;for(var t=0,n=["File","Blob","FormData"];t<n.length;t++){var r=n[t];r in window&&(e[r]=window[r])}}catch(e){console.error(e)}return e}()},function(e,t){e.exports=require("react-immutable-proptypes")},function(e,t,n){var r=n(667);function a(){return e.exports=a=r||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},e.exports.default=e.exports,e.exports.__esModule=!0,a.apply(this,arguments)}e.exports=a,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(457)},function(e,t,n){e.exports=n(452)},function(e,t){e.exports={}},function(e,t,n){"use strict";n.r(t),n.d(t,"isOAS3",(function(){return u})),n.d(t,"isSwagger2",(function(){return l})),n.d(t,"OAS3ComponentWrapFactory",(function(){return p}));var r=n(28),a=n.n(r),o=n(133),i=n.n(o),s=n(0),c=n.n(s);function u(e){var t=e.get("openapi");return"string"==typeof t&&(i()(t).call(t,"3.0.")&&t.length>4)}function l(e){var t=e.get("swagger");return"string"==typeof t&&i()(t).call(t,"2.0")}function p(e){return function(t,n){return function(r){return n&&n.specSelectors&&n.specSelectors.specJson?u(n.specSelectors.specJson())?c.a.createElement(e,a()({},r,n,{Ori:t})):c.a.createElement(t,r):(console.warn("OAS3 wrapper: couldn't get spec"),null)}}}},function(e,t,n){e.exports=n(506)},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){e.exports=n(510)},function(e,t,n){var r=n(38),a=n(180),o=n(48),i=n(141),s=n(182),c=n(284),u=a("wks"),l=r.Symbol,p=c?l:l&&l.withoutSetter||i;e.exports=function(e){return o(u,e)&&(s||"string"==typeof u[e])||(s&&o(l,e)?u[e]=l[e]:u[e]=p("Symbol."+e)),u[e]}},function(e,t,n){e.exports=n(657)},function(e,t,n){(function(t){var n=function(e){return e&&e.Math==Math&&e};e.exports=n("object"==typeof globalThis&&globalThis)||n("object"==typeof window&&window)||n("object"==typeof self&&self)||n("object"==typeof t&&t)||function(){return this}()||Function("return this")()}).call(this,n(177))},function(e,t,n){var r=n(31);e.exports=function(e){return r[e+"Prototype"]}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){var r=n(155);e.exports=function(e,t,n){var a=null==e?void 0:r(e,t);return void 0===a?n:a}},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_SPEC",(function(){return te})),n.d(t,"UPDATE_URL",(function(){return ne})),n.d(t,"UPDATE_JSON",(function(){return re})),n.d(t,"UPDATE_PARAM",(function(){return ae})),n.d(t,"UPDATE_EMPTY_PARAM_INCLUSION",(function(){return oe})),n.d(t,"VALIDATE_PARAMS",(function(){return ie})),n.d(t,"SET_RESPONSE",(function(){return se})),n.d(t,"SET_REQUEST",(function(){return ce})),n.d(t,"SET_MUTATED_REQUEST",(function(){return ue})),n.d(t,"LOG_REQUEST",(function(){return le})),n.d(t,"CLEAR_RESPONSE",(function(){return pe})),n.d(t,"CLEAR_REQUEST",(function(){return fe})),n.d(t,"CLEAR_VALIDATE_PARAMS",(function(){return de})),n.d(t,"UPDATE_OPERATION_META_VALUE",(function(){return he})),n.d(t,"UPDATE_RESOLVED",(function(){return me})),n.d(t,"UPDATE_RESOLVED_SUBTREE",(function(){return ve})),n.d(t,"SET_SCHEME",(function(){return ge})),n.d(t,"updateSpec",(function(){return ye})),n.d(t,"updateResolved",(function(){return be})),n.d(t,"updateUrl",(function(){return Ee})),n.d(t,"updateJsonSpec",(function(){return xe})),n.d(t,"parseToJson",(function(){return Se})),n.d(t,"resolveSpec",(function(){return je})),n.d(t,"requestResolvedSubtree",(function(){return _e})),n.d(t,"changeParam",(function(){return Ae})),n.d(t,"changeParamByIdentity",(function(){return ke})),n.d(t,"updateResolvedSubtree",(function(){return Ie})),n.d(t,"invalidateResolvedSubtreeCache",(function(){return Pe})),n.d(t,"validateParams",(function(){return Te})),n.d(t,"updateEmptyParamInclusion",(function(){return Re})),n.d(t,"clearValidateParams",(function(){return Ne})),n.d(t,"changeConsumesValue",(function(){return Me})),n.d(t,"changeProducesValue",(function(){return De})),n.d(t,"setResponse",(function(){return qe})),n.d(t,"setRequest",(function(){return Be})),n.d(t,"setMutatedRequest",(function(){return Le})),n.d(t,"logRequest",(function(){return Ue})),n.d(t,"executeRequest",(function(){return Ve})),n.d(t,"execute",(function(){return ze})),n.d(t,"clearResponse",(function(){return Fe})),n.d(t,"clearRequest",(function(){return Je})),n.d(t,"setScheme",(function(){return We}));var r=n(25),a=n.n(r),o=n(49),i=n.n(o),s=n(66),c=n.n(s),u=n(19),l=n.n(u),p=n(37),f=n.n(p),d=n(13),h=n.n(d),m=n(4),v=n.n(m),g=n(271),y=n.n(g),b=n(21),E=n.n(b),x=n(85),S=n.n(x),w=n(57),j=n.n(w),O=n(12),C=n.n(O),_=n(162),A=n.n(_),k=n(14),I=n.n(k),P=n(18),T=n.n(P),R=n(2),N=n.n(R),M=n(17),D=n.n(M),q=n(22),B=n.n(q),L=n(272),U=n.n(L),V=n(65),z=n.n(V),F=n(1),J=n(79),W=n.n(J),H=n(110),$=n.n(H),Y=n(163),K=n.n(Y),G=n(385),Z=n.n(G),X=n(273),Q=n.n(X),ee=n(5),te="spec_update_spec",ne="spec_update_url",re="spec_update_json",ae="spec_update_param",oe="spec_update_empty_param_inclusion",ie="spec_validate_param",se="spec_set_response",ce="spec_set_request",ue="spec_set_mutated_request",le="spec_log_request",pe="spec_clear_response",fe="spec_clear_request",de="spec_clear_validate_param",he="spec_update_operation_meta_value",me="spec_update_resolved",ve="spec_update_resolved_subtree",ge="set_scheme";function ye(e){var t,n=(t=e,K()(t)?t:"").replace(/\t/g," ");if("string"==typeof e)return{type:te,payload:n}}function be(e){return{type:me,payload:e}}function Ee(e){return{type:ne,payload:e}}function xe(e){return{type:re,payload:e}}var Se=function(e){return function(t){var n=t.specActions,r=t.specSelectors,a=t.errActions,o=r.specStr,i=null;try{e=e||o(),a.clear({source:"parser"}),i=z.a.safeLoad(e)}catch(e){return console.error(e),a.newSpecErr({source:"parser",level:"error",message:e.reason,line:e.mark&&e.mark.line?e.mark.line+1:void 0})}return i&&"object"===l()(i)?n.updateJsonSpec(i):{}}},we=!1,je=function(e,t){return function(n){var r=n.specActions,a=n.specSelectors,o=n.errActions,i=n.fn,s=i.fetch,c=i.resolve,u=i.AST,l=void 0===u?{}:u,p=n.getConfigs;we||(console.warn("specActions.resolveSpec is deprecated since v3.10.0 and will be removed in v4.0.0; use requestResolvedSubtree instead!"),we=!0);var f=p(),d=f.modelPropertyMacro,m=f.parameterMacro,g=f.requestInterceptor,b=f.responseInterceptor;void 0===e&&(e=a.specJson()),void 0===t&&(t=a.url());var E=l.getLineNumberForPath?l.getLineNumberForPath:function(){},x=a.specStr();return c({fetch:s,spec:e,baseDoc:t,modelPropertyMacro:d,parameterMacro:m,requestInterceptor:g,responseInterceptor:b}).then((function(e){var t=e.spec,n=e.errors;if(o.clear({type:"thrown"}),h()(n)&&n.length>0){var a=v()(n).call(n,(function(e){return console.error(e),e.line=e.fullPath?E(x,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",y()(e,"message",{enumerable:!0,value:e.message}),e}));o.newThrownErrBatch(a)}return r.updateResolved(t)}))}},Oe=[],Ce=Z()(c()(f.a.mark((function e(){var t,n,r,a,o,i,s,u,l,p,d,m,g,b,x,w,O,_;return f.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=Oe.system){e.next=4;break}return console.error("debResolveSubtrees: don't have a system to operate on, aborting."),e.abrupt("return");case 4:if(n=t.errActions,r=t.errSelectors,a=t.fn,o=a.resolveSubtree,i=a.fetch,s=a.AST,u=void 0===s?{}:s,l=t.specSelectors,p=t.specActions,o){e.next=8;break}return console.error("Error: Swagger-Client did not provide a `resolveSubtree` method, doing nothing."),e.abrupt("return");case 8:return d=u.getLineNumberForPath?u.getLineNumberForPath:function(){},m=l.specStr(),g=t.getConfigs(),b=g.modelPropertyMacro,x=g.parameterMacro,w=g.requestInterceptor,O=g.responseInterceptor,e.prev=11,e.next=14,E()(Oe).call(Oe,function(){var e=c()(f.a.mark((function e(t,a){var s,u,p,g,E,_,k,I,P;return f.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t;case 2:return s=e.sent,u=s.resultMap,p=s.specWithCurrentSubtrees,e.next=7,o(p,a,{baseDoc:l.url(),modelPropertyMacro:b,parameterMacro:x,requestInterceptor:w,responseInterceptor:O});case 7:if(g=e.sent,E=g.errors,_=g.spec,r.allErrors().size&&n.clearBy((function(e){var t;return"thrown"!==e.get("type")||"resolver"!==e.get("source")||!S()(t=e.get("fullPath")).call(t,(function(e,t){return e===a[t]||void 0===a[t]}))})),h()(E)&&E.length>0&&(k=v()(E).call(E,(function(e){return e.line=e.fullPath?d(m,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",y()(e,"message",{enumerable:!0,value:e.message}),e})),n.newThrownErrBatch(k)),!_||!l.isOAS3()||"components"!==a[0]||"securitySchemes"!==a[1]){e.next=15;break}return e.next=15,j.a.all(v()(I=C()(P=A()(_)).call(P,(function(e){return"openIdConnect"===e.type}))).call(I,function(){var e=c()(f.a.mark((function e(t){var n,r;return f.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={url:t.openIdConnectUrl,requestInterceptor:w,responseInterceptor:O},e.prev=1,e.next=4,i(n);case 4:(r=e.sent)instanceof Error||r.status>=400?console.error(r.statusText+" "+n.url):t.openIdConnectData=JSON.parse(r.text),e.next=11;break;case 8:e.prev=8,e.t0=e.catch(1),console.error(e.t0);case 11:case"end":return e.stop()}}),e,null,[[1,8]])})));return function(t){return e.apply(this,arguments)}}()));case 15:return Q()(u,a,_),Q()(p,a,_),e.abrupt("return",{resultMap:u,specWithCurrentSubtrees:p});case 18:case"end":return e.stop()}}),e)})));return function(t,n){return e.apply(this,arguments)}}(),j.a.resolve({resultMap:(l.specResolvedSubtree([])||Object(F.Map)()).toJS(),specWithCurrentSubtrees:l.specJson().toJS()}));case 14:_=e.sent,delete Oe.system,Oe=[],e.next=22;break;case 19:e.prev=19,e.t0=e.catch(11),console.error(e.t0);case 22:p.updateResolvedSubtree([],_.resultMap);case 23:case"end":return e.stop()}}),e,null,[[11,19]])}))),35),_e=function(e){return function(t){var n;I()(n=v()(Oe).call(Oe,(function(e){return e.join("@@")}))).call(n,e.join("@@"))>-1||(Oe.push(e),Oe.system=t,Ce())}};function Ae(e,t,n,r,a){return{type:ae,payload:{path:e,value:r,paramName:t,paramIn:n,isXml:a}}}function ke(e,t,n,r){return{type:ae,payload:{path:e,param:t,value:n,isXml:r}}}var Ie=function(e,t){return{type:ve,payload:{path:e,value:t}}},Pe=function(){return{type:ve,payload:{path:[],value:Object(F.Map)()}}},Te=function(e,t){return{type:ie,payload:{pathMethod:e,isOAS3:t}}},Re=function(e,t,n,r){return{type:oe,payload:{pathMethod:e,paramName:t,paramIn:n,includeEmptyValue:r}}};function Ne(e){return{type:de,payload:{pathMethod:e}}}function Me(e,t){return{type:he,payload:{path:e,value:t,key:"consumes_value"}}}function De(e,t){return{type:he,payload:{path:e,value:t,key:"produces_value"}}}var qe=function(e,t,n){return{payload:{path:e,method:t,res:n},type:se}},Be=function(e,t,n){return{payload:{path:e,method:t,req:n},type:ce}},Le=function(e,t,n){return{payload:{path:e,method:t,req:n},type:ue}},Ue=function(e){return{payload:e,type:le}},Ve=function(e){return function(t){var n,r,a=t.fn,o=t.specActions,i=t.specSelectors,s=t.getConfigs,u=t.oas3Selectors,l=e.pathName,p=e.method,d=e.operation,m=s(),g=m.requestInterceptor,y=m.responseInterceptor,b=d.toJS();d&&d.get("parameters")&&T()(n=C()(r=d.get("parameters")).call(r,(function(e){return e&&!0===e.get("allowEmptyValue")}))).call(n,(function(t){if(i.parameterInclusionSettingFor([l,p],t.get("name"),t.get("in"))){e.parameters=e.parameters||{};var n=Object(ee.C)(t,e.parameters);(!n||n&&0===n.size)&&(e.parameters[t.get("name")]="")}}));if(e.contextUrl=W()(i.url()).toString(),b&&b.operationId?e.operationId=b.operationId:b&&l&&p&&(e.operationId=a.opId(b,l,p)),i.isOAS3()){var E,x=N()(E="".concat(l,":")).call(E,p);e.server=u.selectedServer(x)||u.selectedServer();var S=u.serverVariables({server:e.server,namespace:x}).toJS(),w=u.serverVariables({server:e.server}).toJS();e.serverVariables=D()(S).length?S:w,e.requestContentType=u.requestContentType(l,p),e.responseContentType=u.responseContentType(l,p)||"*/*";var j=u.requestBodyValue(l,p),O=u.requestBodyInclusionSetting(l,p);if(Object(ee.t)(j))e.requestBody=JSON.parse(j);else if(j&&j.toJS){var _;e.requestBody=C()(_=v()(j).call(j,(function(e){return F.Map.isMap(e)?e.get("value"):e}))).call(_,(function(e,t){return(h()(e)?0!==e.length:!Object(ee.q)(e))||O.get(t)})).toJS()}else e.requestBody=j}var A=B()({},e);A=a.buildRequest(A),o.setRequest(e.pathName,e.method,A);var k=function(){var t=c()(f.a.mark((function t(n){var r,a;return f.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,g.apply(undefined,[n]);case 2:return r=t.sent,a=B()({},r),o.setMutatedRequest(e.pathName,e.method,a),t.abrupt("return",r);case 6:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();e.requestInterceptor=k,e.responseInterceptor=y;var I=U()();return a.execute(e).then((function(t){t.duration=U()()-I,o.setResponse(e.pathName,e.method,t)})).catch((function(t){"Failed to fetch"===t.message&&(t.name="",t.message='**Failed to fetch.** \n**Possible Reasons:** \n - CORS \n - Network Failure \n - URL scheme must be "http" or "https" for CORS request.'),o.setResponse(e.pathName,e.method,{error:!0,err:$()(t)})}))}},ze=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,n=e.method,r=i()(e,["path","method"]);return function(e){var o=e.fn.fetch,i=e.specSelectors,s=e.specActions,c=i.specJsonWithResolvedSubtrees().toJS(),u=i.operationScheme(t,n),l=i.contentTypeValues([t,n]).toJS(),p=l.requestContentType,f=l.responseContentType,d=/xml/i.test(p),h=i.parameterValues([t,n],d).toJS();return s.executeRequest(a()(a()({},r),{},{fetch:o,spec:c,pathName:t,method:n,parameters:h,requestContentType:p,scheme:u,responseContentType:f}))}};function Fe(e,t){return{type:pe,payload:{path:e,method:t}}}function Je(e,t){return{type:fe,payload:{path:e,method:t}}}function We(e,t,n){return{type:ge,payload:{scheme:e,path:t,method:n}}}},function(e,t,n){var r=n(31),a=n(48),o=n(189),i=n(60).f;e.exports=function(e){var t=r.Symbol||(r.Symbol={});a(t,e)||i(t,e,{value:o.f(e)})}},function(e,t,n){var r=n(34);e.exports=!r((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},function(e,t,n){var r=n(137),a=n(493),o=n(195),i=n(313),s=n(145);e.exports=function(e,t){var n;if(void 0===r||null==a(e)){if(o(e)||(n=s(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var c=0,u=function(){};return{s:u,n:function(){return c>=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:u}}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 l,p=!0,f=!1;return{s:function(){n=i(e)},n:function(){var e=n.next();return p=e.done,e},e:function(e){f=!0,l=e},f:function(){try{p||null==n.return||n.return()}finally{if(f)throw l}}}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(40);e.exports=function(e){if(!r(e))throw TypeError(String(e)+" is not an object");return e}},function(e,t){var n=Array.isArray;e.exports=n},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(346),a=n(348),o=n(645);e.exports=function(e,t){if(null==e)return{};var n,i,s=o(e,t);if(r){var c=r(e);for(i=0;i<c.length;i++)n=c[i],a(t).call(t,n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_SELECTED_SERVER",(function(){return r})),n.d(t,"UPDATE_REQUEST_BODY_VALUE",(function(){return a})),n.d(t,"UPDATE_REQUEST_BODY_VALUE_RETAIN_FLAG",(function(){return o})),n.d(t,"UPDATE_REQUEST_BODY_INCLUSION",(function(){return i})),n.d(t,"UPDATE_ACTIVE_EXAMPLES_MEMBER",(function(){return s})),n.d(t,"UPDATE_REQUEST_CONTENT_TYPE",(function(){return c})),n.d(t,"UPDATE_RESPONSE_CONTENT_TYPE",(function(){return u})),n.d(t,"UPDATE_SERVER_VARIABLE_VALUE",(function(){return l})),n.d(t,"SET_REQUEST_BODY_VALIDATE_ERROR",(function(){return p})),n.d(t,"CLEAR_REQUEST_BODY_VALIDATE_ERROR",(function(){return f})),n.d(t,"CLEAR_REQUEST_BODY_VALUE",(function(){return d})),n.d(t,"setSelectedServer",(function(){return h})),n.d(t,"setRequestBodyValue",(function(){return m})),n.d(t,"setRetainRequestBodyValueFlag",(function(){return v})),n.d(t,"setRequestBodyInclusion",(function(){return g})),n.d(t,"setActiveExamplesMember",(function(){return y})),n.d(t,"setRequestContentType",(function(){return b})),n.d(t,"setResponseContentType",(function(){return E})),n.d(t,"setServerVariableValue",(function(){return x})),n.d(t,"setRequestBodyValidateError",(function(){return S})),n.d(t,"clearRequestBodyValidateError",(function(){return w})),n.d(t,"initRequestBodyValidateError",(function(){return j})),n.d(t,"clearRequestBodyValue",(function(){return O}));var r="oas3_set_servers",a="oas3_set_request_body_value",o="oas3_set_request_body_retain_flag",i="oas3_set_request_body_inclusion",s="oas3_set_active_examples_member",c="oas3_set_request_content_type",u="oas3_set_response_content_type",l="oas3_set_server_variable_value",p="oas3_set_request_body_validate_error",f="oas3_clear_request_body_validate_error",d="oas3_clear_request_body_value";function h(e,t){return{type:r,payload:{selectedServerUrl:e,namespace:t}}}function m(e){var t=e.value,n=e.pathMethod;return{type:a,payload:{value:t,pathMethod:n}}}var v=function(e){var t=e.value,n=e.pathMethod;return{type:o,payload:{value:t,pathMethod:n}}};function g(e){var t=e.value,n=e.pathMethod,r=e.name;return{type:i,payload:{value:t,pathMethod:n,name:r}}}function y(e){var t=e.name,n=e.pathMethod,r=e.contextType,a=e.contextName;return{type:s,payload:{name:t,pathMethod:n,contextType:r,contextName:a}}}function b(e){var t=e.value,n=e.pathMethod;return{type:c,payload:{value:t,pathMethod:n}}}function E(e){var t=e.value,n=e.path,r=e.method;return{type:u,payload:{value:t,path:n,method:r}}}function x(e){var t=e.server,n=e.namespace,r=e.key,a=e.val;return{type:l,payload:{server:t,namespace:n,key:r,val:a}}}var S=function(e){var t=e.path,n=e.method,r=e.validationErrors;return{type:p,payload:{path:t,method:n,validationErrors:r}}},w=function(e){var t=e.path,n=e.method;return{type:f,payload:{path:t,method:n}}},j=function(e){var t=e.pathMethod;return{type:f,payload:{path:t[0],method:t[1]}}},O=function(e){var t=e.pathMethod;return{type:d,payload:{pathMethod:t}}}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t,n){"use strict";n.d(t,"b",(function(){return b})),n.d(t,"e",(function(){return E})),n.d(t,"c",(function(){return S})),n.d(t,"a",(function(){return w})),n.d(t,"d",(function(){return j}));var r=n(45),a=n.n(r),o=n(18),i=n.n(o),s=n(33),c=n.n(s),u=n(2),l=n.n(u),p=n(19),f=n.n(p),d=n(51),h=n.n(d),m=n(278),v=n.n(m),g=function(e){return String.prototype.toLowerCase.call(e)},y=function(e){return e.replace(/[^\w]/gi,"_")};function b(e){var t=e.openapi;return!!t&&v()(t,"3")}function E(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},a=r.v2OperationIdCompatibilityMode;if(!e||"object"!==f()(e))return null;var o=(e.operationId||"").replace(/\s/g,"");return o.length?y(e.operationId):x(t,n,{v2OperationIdCompatibilityMode:a})}function x(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=r.v2OperationIdCompatibilityMode;if(a){var o,i,s=l()(o="".concat(t.toLowerCase(),"_")).call(o,e).replace(/[\s!@#$%^&*()_+=[{\]};:<>|./?,\\'""-]/g,"_");return(s=s||l()(i="".concat(e.substring(1),"_")).call(i,t)).replace(/((_){2,})/g,"_").replace(/^(_)*/g,"").replace(/([_])*$/g,"")}return l()(n="".concat(g(t))).call(n,y(e))}function S(e,t){var n;return l()(n="".concat(g(t),"-")).call(n,e)}function w(e,t){return e&&e.paths?function(e,t){return function(e,t,n){if(!e||"object"!==f()(e)||!e.paths||"object"!==f()(e.paths))return null;var r=e.paths;for(var a in r)for(var o in r[a])if("PARAMETERS"!==o.toUpperCase()){var i=r[a][o];if(i&&"object"===f()(i)){var s={spec:e,pathName:a,method:o.toUpperCase(),operation:i},c=t(s);if(n&&c)return s}}return}(e,t,!0)||null}(e,(function(e){var n,r=e.pathName,a=e.method,o=e.operation;if(!o||"object"!==f()(o))return!1;var i=o.operationId,s=E(o,r,a),u=S(r,a);return c()(n=[s,u,i]).call(n,(function(e){return e&&e===t}))})):null}function j(e){var t=e.spec,n=t.paths,r={};if(!n||t.$$normalized)return e;for(var o in n){var s=n[o];if(h()(s)){var u=s.parameters,p=function(e){var n=s[e];if(!h()(n))return"continue";var p=E(n,o,e);if(p){r[p]?r[p].push(n):r[p]=[n];var f=r[p];if(f.length>1)i()(f).call(f,(function(e,t){var n;e.__originalOperationId=e.__originalOperationId||e.operationId,e.operationId=l()(n="".concat(p)).call(n,t+1)}));else if(void 0!==n.operationId){var d=f[0];d.__originalOperationId=d.__originalOperationId||n.operationId,d.operationId=p}}if("parameters"!==e){var m=[],v={};for(var g in t)"produces"!==g&&"consumes"!==g&&"security"!==g||(v[g]=t[g],m.push(v));if(u&&(v.parameters=u,m.push(v)),m.length){var y,b=a()(m);try{for(b.s();!(y=b.n()).done;){var x=y.value;for(var S in x)if(n[S]){if("parameters"===S){var w,j=a()(x[S]);try{var O=function(){var e,t=w.value;c()(e=n[S]).call(e,(function(e){return e.name&&e.name===t.name||e.$ref&&e.$ref===t.$ref||e.$$ref&&e.$$ref===t.$$ref||e===t}))||n[S].push(t)};for(j.s();!(w=j.n()).done;)O()}catch(e){j.e(e)}finally{j.f()}}}else n[S]=x[S]}}catch(e){b.e(e)}finally{b.f()}}}};for(var f in s)p(f)}}return t.$$normalized=!0,e}},function(e,t,n){"use strict";n.r(t),n.d(t,"NEW_THROWN_ERR",(function(){return o})),n.d(t,"NEW_THROWN_ERR_BATCH",(function(){return i})),n.d(t,"NEW_SPEC_ERR",(function(){return s})),n.d(t,"NEW_SPEC_ERR_BATCH",(function(){return c})),n.d(t,"NEW_AUTH_ERR",(function(){return u})),n.d(t,"CLEAR",(function(){return l})),n.d(t,"CLEAR_BY",(function(){return p})),n.d(t,"newThrownErr",(function(){return f})),n.d(t,"newThrownErrBatch",(function(){return d})),n.d(t,"newSpecErr",(function(){return h})),n.d(t,"newSpecErrBatch",(function(){return m})),n.d(t,"newAuthErr",(function(){return v})),n.d(t,"clear",(function(){return g})),n.d(t,"clearBy",(function(){return y}));var r=n(110),a=n.n(r),o="err_new_thrown_err",i="err_new_thrown_err_batch",s="err_new_spec_err",c="err_new_spec_err_batch",u="err_new_auth_err",l="err_clear",p="err_clear_by";function f(e){return{type:o,payload:a()(e)}}function d(e){return{type:i,payload:e}}function h(e){return{type:s,payload:e}}function m(e){return{type:c,payload:e}}function v(e){return{type:u,payload:e}}function g(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:l,payload:e}}function y(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(){return!0};return{type:p,payload:e}}},function(e,t){e.exports=require("classnames")},function(e,t,n){var r=n(96),a=n(51);e.exports=function(e){if(!a(e))return!1;var t=r(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}},function(e,t,n){e.exports=n(520)},function(e,t,n){e.exports=n(659)},function(e,t,n){var r=n(139),a=n(104);e.exports=function(e){return r(a(e))}},function(e,t,n){var r=n(44),a=n(60),o=n(90);e.exports=r?function(e,t,n){return a.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(44),a=n(282),o=n(46),i=n(140),s=Object.defineProperty;t.f=r?s:function(e,t,n){if(o(e),t=i(t,!0),o(n),a)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(104);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(31),a=n(38),o=function(e){return"function"==typeof e?e:void 0};e.exports=function(e,t){return arguments.length<2?o(r[e])||o(a[e]):r[e]&&r[e][t]||a[e]&&a[e][t]}},function(e,t,n){n(125);var r=n(443),a=n(38),o=n(74),i=n(59),s=n(94),c=n(36)("toStringTag");for(var u in r){var l=a[u],p=l&&l.prototype;p&&o(p)!==c&&i(p,c,u),s[u]=s.Array}},function(e,t,n){var r=n(322),a="object"==typeof self&&self&&self.Object===Object&&self,o=r||a||Function("return this")();e.exports=o},function(e,t){e.exports=require("js-yaml")},function(e,t,n){var r=n(646);function a(e,t,n,a,o,i,s){try{var c=e[i](s),u=c.value}catch(e){return void n(e)}c.done?t(u):r.resolve(u).then(a,o)}e.exports=function(e){return function(){var t=this,n=arguments;return new r((function(r,o){var i=e.apply(t,n);function s(e){a(i,r,o,s,c,"next",e)}function c(e){a(i,r,o,s,c,"throw",e)}s(void 0)}))}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},function(e,t,n){var r=n(117),a=Math.min;e.exports=function(e){return e>0?a(r(e),9007199254740991):0}},function(e,t,n){var r,a,o,i=n(288),s=n(38),c=n(40),u=n(59),l=n(48),p=n(181),f=n(144),d=n(123),h=s.WeakMap;if(i){var m=p.state||(p.state=new h),v=m.get,g=m.has,y=m.set;r=function(e,t){return t.facade=e,y.call(m,e,t),t},a=function(e){return v.call(m,e)||{}},o=function(e){return g.call(m,e)}}else{var b=f("state");d[b]=!0,r=function(e,t){return t.facade=e,u(e,b,t),t},a=function(e){return l(e,b)?e[b]:{}},o=function(e){return l(e,b)}}e.exports={set:r,get:a,has:o,enforce:function(e){return o(e)?a(e):r(e,{})},getterFor:function(e){return function(t){var n;if(!c(t)||(n=a(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}}},function(e,t){e.exports=require("deep-extend")},function(e,t,n){e.exports=n(495)},function(e,t){e.exports=require("url")},function(e,t,n){"use strict";n.r(t),n.d(t,"SHOW_AUTH_POPUP",(function(){return d})),n.d(t,"AUTHORIZE",(function(){return h})),n.d(t,"LOGOUT",(function(){return m})),n.d(t,"PRE_AUTHORIZE_OAUTH2",(function(){return v})),n.d(t,"AUTHORIZE_OAUTH2",(function(){return g})),n.d(t,"VALIDATE",(function(){return y})),n.d(t,"CONFIGURE_AUTH",(function(){return b})),n.d(t,"RESTORE_AUTHORIZATION",(function(){return E})),n.d(t,"showDefinitions",(function(){return x})),n.d(t,"authorize",(function(){return S})),n.d(t,"authorizeWithPersistOption",(function(){return w})),n.d(t,"logout",(function(){return j})),n.d(t,"logoutWithPersistOption",(function(){return O})),n.d(t,"preAuthorizeImplicit",(function(){return C})),n.d(t,"authorizeOauth2",(function(){return _})),n.d(t,"authorizeOauth2WithPersistOption",(function(){return A})),n.d(t,"authorizePassword",(function(){return k})),n.d(t,"authorizeApplication",(function(){return I})),n.d(t,"authorizeAccessCodeWithFormParams",(function(){return P})),n.d(t,"authorizeAccessCodeWithBasicAuthentication",(function(){return T})),n.d(t,"authorizeRequest",(function(){return R})),n.d(t,"configureAuth",(function(){return N})),n.d(t,"restoreAuthorization",(function(){return M})),n.d(t,"persistAuthorizationIfNeeded",(function(){return D}));var r=n(19),a=n.n(r),o=n(30),i=n.n(o),s=n(22),c=n.n(s),u=n(79),l=n.n(u),p=n(26),f=n(5),d="show_popup",h="authorize",m="logout",v="pre_authorize_oauth2",g="authorize_oauth2",y="validate",b="configure_auth",E="restore_authorization";function x(e){return{type:d,payload:e}}function S(e){return{type:h,payload:e}}var w=function(e){return function(t){var n=t.authActions;n.authorize(e),n.persistAuthorizationIfNeeded()}};function j(e){return{type:m,payload:e}}var O=function(e){return function(t){var n=t.authActions;n.logout(e),n.persistAuthorizationIfNeeded()}},C=function(e){return function(t){var n=t.authActions,r=t.errActions,a=e.auth,o=e.token,s=e.isValid,c=a.schema,u=a.name,l=c.get("flow");delete p.a.swaggerUIRedirectOauth2,"accessCode"===l||s||r.newAuthErr({authId:u,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),o.error?r.newAuthErr({authId:u,source:"auth",level:"error",message:i()(o)}):n.authorizeOauth2WithPersistOption({auth:a,token:o})}};function _(e){return{type:g,payload:e}}var A=function(e){return function(t){var n=t.authActions;n.authorizeOauth2(e),n.persistAuthorizationIfNeeded()}},k=function(e){return function(t){var n=t.authActions,r=e.schema,a=e.name,o=e.username,i=e.password,s=e.passwordType,u=e.clientId,l=e.clientSecret,p={grant_type:"password",scope:e.scopes.join(" "),username:o,password:i},d={};switch(s){case"request-body":!function(e,t,n){t&&c()(e,{client_id:t});n&&c()(e,{client_secret:n})}(p,u,l);break;case"basic":d.Authorization="Basic "+Object(f.a)(u+":"+l);break;default:console.warn("Warning: invalid passwordType ".concat(s," was passed, not including client id and secret"))}return n.authorizeRequest({body:Object(f.b)(p),url:r.get("tokenUrl"),name:a,headers:d,query:{},auth:e})}};var I=function(e){return function(t){var n=t.authActions,r=e.schema,a=e.scopes,o=e.name,i=e.clientId,s=e.clientSecret,c={Authorization:"Basic "+Object(f.a)(i+":"+s)},u={grant_type:"client_credentials",scope:a.join(" ")};return n.authorizeRequest({body:Object(f.b)(u),name:o,url:r.get("tokenUrl"),auth:e,headers:c})}},P=function(e){var t=e.auth,n=e.redirectUrl;return function(e){var r=e.authActions,a=t.schema,o=t.name,i=t.clientId,s=t.clientSecret,c=t.codeVerifier,u={grant_type:"authorization_code",code:t.code,client_id:i,client_secret:s,redirect_uri:n,code_verifier:c};return r.authorizeRequest({body:Object(f.b)(u),name:o,url:a.get("tokenUrl"),auth:t})}},T=function(e){var t=e.auth,n=e.redirectUrl;return function(e){var r=e.authActions,a=t.schema,o=t.name,i=t.clientId,s=t.clientSecret,c={Authorization:"Basic "+Object(f.a)(i+":"+s)},u={grant_type:"authorization_code",code:t.code,client_id:i,redirect_uri:n};return r.authorizeRequest({body:Object(f.b)(u),name:o,url:a.get("tokenUrl"),auth:t,headers:c})}},R=function(e){return function(t){var n,r=t.fn,o=t.getConfigs,s=t.authActions,u=t.errActions,p=t.oas3Selectors,f=t.specSelectors,d=t.authSelectors,h=e.body,m=e.query,v=void 0===m?{}:m,g=e.headers,y=void 0===g?{}:g,b=e.name,E=e.url,x=e.auth,S=(d.getConfigs()||{}).additionalQueryStringParams;if(f.isOAS3()){var w=p.serverEffectiveValue(p.selectedServer());n=l()(E,w,!0)}else n=l()(E,f.url(),!0);"object"===a()(S)&&(n.query=c()({},n.query,S));var j=n.toString(),O=c()({Accept:"application/json, text/plain, */*","Content-Type":"application/x-www-form-urlencoded","X-Requested-With":"XMLHttpRequest"},y);r.fetch({url:j,method:"post",headers:O,query:v,body:h,requestInterceptor:o().requestInterceptor,responseInterceptor:o().responseInterceptor}).then((function(e){var t=JSON.parse(e.data),n=t&&(t.error||""),r=t&&(t.parseError||"");e.ok?n||r?u.newAuthErr({authId:b,level:"error",source:"auth",message:i()(t)}):s.authorizeOauth2WithPersistOption({auth:x,token:t}):u.newAuthErr({authId:b,level:"error",source:"auth",message:e.statusText})})).catch((function(e){var t=new Error(e).message;if(e.response&&e.response.data){var n=e.response.data;try{var r="string"==typeof n?JSON.parse(n):n;r.error&&(t+=", error: ".concat(r.error)),r.error_description&&(t+=", description: ".concat(r.error_description))}catch(e){}}u.newAuthErr({authId:b,level:"error",source:"auth",message:t})}))}};function N(e){return{type:b,payload:e}}function M(e){return{type:E,payload:e}}var D=function(){return function(e){var t=e.authSelectors;if((0,e.getConfigs)().persistAuthorization){var n=t.authorized();localStorage.setItem("authorized",i()(n.toJS()))}}}},function(e,t,n){var r=n(190),a=n(115),o=n(36)("toStringTag"),i="Arguments"==a(function(){return arguments}());e.exports=r?a:function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),o))?n:i?a(t):"Object"==(r=a(t))&&"function"==typeof t.callee?"Arguments":r}},function(e,t,n){var r=n(91),a=n(139),o=n(61),i=n(68),s=n(179),c=[].push,u=function(e){var t=1==e,n=2==e,u=3==e,l=4==e,p=6==e,f=7==e,d=5==e||p;return function(h,m,v,g){for(var y,b,E=o(h),x=a(E),S=r(m,v,3),w=i(x.length),j=0,O=g||s,C=t?O(h,w):n||f?O(h,0):void 0;w>j;j++)if((d||j in x)&&(b=S(y=x[j],j,E),e))if(t)C[j]=b;else if(b)switch(e){case 3:return!0;case 5:return y;case 6:return j;case 2:c.call(C,y)}else switch(e){case 4:return!1;case 7:c.call(C,y)}return p?-1:u||l?l:C}};e.exports={forEach:u(0),map:u(1),filter:u(2),some:u(3),every:u(4),find:u(5),findIndex:u(6),filterOut:u(7)}},function(e,t){e.exports=function(e){return null!=e&&"object"==typeof e}},function(e,t,n){var r=n(321);e.exports=function(e){return null==e?"":r(e)}},function(e,t,n){"use strict";n.r(t),n.d(t,"lastError",(function(){return N})),n.d(t,"url",(function(){return M})),n.d(t,"specStr",(function(){return D})),n.d(t,"specSource",(function(){return q})),n.d(t,"specJson",(function(){return B})),n.d(t,"specResolved",(function(){return L})),n.d(t,"specResolvedSubtree",(function(){return U})),n.d(t,"specJsonWithResolvedSubtrees",(function(){return z})),n.d(t,"spec",(function(){return F})),n.d(t,"isOAS3",(function(){return J})),n.d(t,"info",(function(){return W})),n.d(t,"externalDocs",(function(){return H})),n.d(t,"version",(function(){return $})),n.d(t,"semver",(function(){return Y})),n.d(t,"paths",(function(){return K})),n.d(t,"operations",(function(){return G})),n.d(t,"consumes",(function(){return Z})),n.d(t,"produces",(function(){return X})),n.d(t,"security",(function(){return Q})),n.d(t,"securityDefinitions",(function(){return ee})),n.d(t,"findDefinition",(function(){return te})),n.d(t,"definitions",(function(){return ne})),n.d(t,"basePath",(function(){return re})),n.d(t,"host",(function(){return ae})),n.d(t,"schemes",(function(){return oe})),n.d(t,"operationsWithRootInherited",(function(){return ie})),n.d(t,"tags",(function(){return se})),n.d(t,"tagDetails",(function(){return ce})),n.d(t,"operationsWithTags",(function(){return ue})),n.d(t,"taggedOperations",(function(){return le})),n.d(t,"responses",(function(){return pe})),n.d(t,"requests",(function(){return fe})),n.d(t,"mutatedRequests",(function(){return de})),n.d(t,"responseFor",(function(){return he})),n.d(t,"requestFor",(function(){return me})),n.d(t,"mutatedRequestFor",(function(){return ve})),n.d(t,"allowTryItOutFor",(function(){return ge})),n.d(t,"parameterWithMetaByIdentity",(function(){return ye})),n.d(t,"parameterInclusionSettingFor",(function(){return be})),n.d(t,"parameterWithMeta",(function(){return Ee})),n.d(t,"operationWithMeta",(function(){return xe})),n.d(t,"getParameter",(function(){return Se})),n.d(t,"hasHost",(function(){return we})),n.d(t,"parameterValues",(function(){return je})),n.d(t,"parametersIncludeIn",(function(){return Oe})),n.d(t,"parametersIncludeType",(function(){return Ce})),n.d(t,"contentTypeValues",(function(){return _e})),n.d(t,"currentProducesFor",(function(){return Ae})),n.d(t,"producesOptionsFor",(function(){return ke})),n.d(t,"consumesOptionsFor",(function(){return Ie})),n.d(t,"operationScheme",(function(){return Pe})),n.d(t,"canExecuteScheme",(function(){return Te})),n.d(t,"validateBeforeExecute",(function(){return Re})),n.d(t,"getOAS3RequiredRequestBodyContentType",(function(){return Ne})),n.d(t,"isMediaTypeSchemaPropertiesEqual",(function(){return Me}));var r=n(16),a=n.n(r),o=n(15),i=n.n(o),s=n(2),c=n.n(s),u=n(23),l=n.n(u),p=n(18),f=n.n(p),d=n(14),h=n.n(d),m=n(4),v=n.n(m),g=n(12),y=n.n(g),b=n(56),E=n.n(b),x=n(21),S=n.n(x),w=n(160),j=n.n(w),O=n(33),C=n.n(O),_=n(13),A=n.n(_),k=n(20),I=n(5),P=n(1),T=["get","put","post","delete","options","head","patch","trace"],R=function(e){return e||Object(P.Map)()},N=Object(k.createSelector)(R,(function(e){return e.get("lastError")})),M=Object(k.createSelector)(R,(function(e){return e.get("url")})),D=Object(k.createSelector)(R,(function(e){return e.get("spec")||""})),q=Object(k.createSelector)(R,(function(e){return e.get("specSource")||"not-editor"})),B=Object(k.createSelector)(R,(function(e){return e.get("json",Object(P.Map)())})),L=Object(k.createSelector)(R,(function(e){return e.get("resolved",Object(P.Map)())})),U=function(e,t){var n;return e.getIn(c()(n=["resolvedSubtrees"]).call(n,i()(t)),void 0)},V=function e(t,n){return P.Map.isMap(t)&&P.Map.isMap(n)?n.get("$$ref")?n:Object(P.OrderedMap)().mergeWith(e,t,n):n},z=Object(k.createSelector)(R,(function(e){return Object(P.OrderedMap)().mergeWith(V,e.get("json"),e.get("resolvedSubtrees"))})),F=function(e){return B(e)},J=Object(k.createSelector)(F,(function(){return!1})),W=Object(k.createSelector)(F,(function(e){return De(e&&e.get("info"))})),H=Object(k.createSelector)(F,(function(e){return De(e&&e.get("externalDocs"))})),$=Object(k.createSelector)(W,(function(e){return e&&e.get("version")})),Y=Object(k.createSelector)($,(function(e){var t;return l()(t=/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e)).call(t,1)})),K=Object(k.createSelector)(z,(function(e){return e.get("paths")})),G=Object(k.createSelector)(K,(function(e){if(!e||e.size<1)return Object(P.List)();var t=Object(P.List)();return e&&f()(e)?(f()(e).call(e,(function(e,n){if(!e||!f()(e))return{};f()(e).call(e,(function(e,r){var a;h()(T).call(T,r)<0||(t=t.push(Object(P.fromJS)({path:n,method:r,operation:e,id:c()(a="".concat(r,"-")).call(a,n)})))}))})),t):Object(P.List)()})),Z=Object(k.createSelector)(F,(function(e){return Object(P.Set)(e.get("consumes"))})),X=Object(k.createSelector)(F,(function(e){return Object(P.Set)(e.get("produces"))})),Q=Object(k.createSelector)(F,(function(e){return e.get("security",Object(P.List)())})),ee=Object(k.createSelector)(F,(function(e){return e.get("securityDefinitions")})),te=function(e,t){var n=e.getIn(["resolvedSubtrees","definitions",t],null),r=e.getIn(["json","definitions",t],null);return n||r||null},ne=Object(k.createSelector)(F,(function(e){var t=e.get("definitions");return P.Map.isMap(t)?t:Object(P.Map)()})),re=Object(k.createSelector)(F,(function(e){return e.get("basePath")})),ae=Object(k.createSelector)(F,(function(e){return e.get("host")})),oe=Object(k.createSelector)(F,(function(e){return e.get("schemes",Object(P.Map)())})),ie=Object(k.createSelector)(G,Z,X,(function(e,t,n){return v()(e).call(e,(function(e){return e.update("operation",(function(e){if(e){if(!P.Map.isMap(e))return;return e.withMutations((function(e){return e.get("consumes")||e.update("consumes",(function(e){return Object(P.Set)(e).merge(t)})),e.get("produces")||e.update("produces",(function(e){return Object(P.Set)(e).merge(n)})),e}))}return Object(P.Map)()}))}))})),se=Object(k.createSelector)(F,(function(e){var t=e.get("tags",Object(P.List)());return P.List.isList(t)?y()(t).call(t,(function(e){return P.Map.isMap(e)})):Object(P.List)()})),ce=function(e,t){var n,r=se(e)||Object(P.List)();return E()(n=y()(r).call(r,P.Map.isMap)).call(n,(function(e){return e.get("name")===t}),Object(P.Map)())},ue=Object(k.createSelector)(ie,se,(function(e,t){return S()(e).call(e,(function(e,t){var n=Object(P.Set)(t.getIn(["operation","tags"]));return n.count()<1?e.update("default",Object(P.List)(),(function(e){return e.push(t)})):S()(n).call(n,(function(e,n){return e.update(n,Object(P.List)(),(function(e){return e.push(t)}))}),e)}),S()(t).call(t,(function(e,t){return e.set(t.get("name"),Object(P.List)())}),Object(P.OrderedMap)()))})),le=function(e){return function(t){var n,r=(0,t.getConfigs)(),a=r.tagsSorter,o=r.operationsSorter;return v()(n=ue(e).sortBy((function(e,t){return t}),(function(e,t){var n="function"==typeof a?a:I.I.tagsSorter[a];return n?n(e,t):null}))).call(n,(function(t,n){var r="function"==typeof o?o:I.I.operationsSorter[o],a=r?j()(t).call(t,r):t;return Object(P.Map)({tagDetails:ce(e,n),operations:a})}))}},pe=Object(k.createSelector)(R,(function(e){return e.get("responses",Object(P.Map)())})),fe=Object(k.createSelector)(R,(function(e){return e.get("requests",Object(P.Map)())})),de=Object(k.createSelector)(R,(function(e){return e.get("mutatedRequests",Object(P.Map)())})),he=function(e,t,n){return pe(e).getIn([t,n],null)},me=function(e,t,n){return fe(e).getIn([t,n],null)},ve=function(e,t,n){return de(e).getIn([t,n],null)},ge=function(){return!0},ye=function(e,t,n){var r,a,o=z(e).getIn(c()(r=["paths"]).call(r,i()(t),["parameters"]),Object(P.OrderedMap)()),s=e.getIn(c()(a=["meta","paths"]).call(a,i()(t),["parameters"]),Object(P.OrderedMap)()),u=v()(o).call(o,(function(e){var t,r,a,o=s.get(c()(t="".concat(n.get("in"),".")).call(t,n.get("name"))),i=s.get(c()(r=c()(a="".concat(n.get("in"),".")).call(a,n.get("name"),".hash-")).call(r,n.hashCode()));return Object(P.OrderedMap)().merge(e,o,i)}));return E()(u).call(u,(function(e){return e.get("in")===n.get("in")&&e.get("name")===n.get("name")}),Object(P.OrderedMap)())},be=function(e,t,n,r){var a,o,s=c()(a="".concat(r,".")).call(a,n);return e.getIn(c()(o=["meta","paths"]).call(o,i()(t),["parameter_inclusions",s]),!1)},Ee=function(e,t,n,r){var a,o=z(e).getIn(c()(a=["paths"]).call(a,i()(t),["parameters"]),Object(P.OrderedMap)()),s=E()(o).call(o,(function(e){return e.get("in")===r&&e.get("name")===n}),Object(P.OrderedMap)());return ye(e,t,s)},xe=function(e,t,n){var r,a=z(e).getIn(["paths",t,n],Object(P.OrderedMap)()),o=e.getIn(["meta","paths",t,n],Object(P.OrderedMap)()),i=v()(r=a.get("parameters",Object(P.List)())).call(r,(function(r){return ye(e,[t,n],r)}));return Object(P.OrderedMap)().merge(a,o).set("parameters",i)};function Se(e,t,n,r){var a;t=t||[];var o=e.getIn(c()(a=["meta","paths"]).call(a,i()(t),["parameters"]),Object(P.fromJS)([]));return E()(o).call(o,(function(e){return P.Map.isMap(e)&&e.get("name")===n&&e.get("in")===r}))||Object(P.Map)()}var we=Object(k.createSelector)(F,(function(e){var t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}));function je(e,t,n){var r;t=t||[];var a=xe.apply(void 0,c()(r=[e]).call(r,i()(t))).get("parameters",Object(P.List)());return S()(a).call(a,(function(e,t){var r=n&&"body"===t.get("in")?t.get("value_xml"):t.get("value");return e.set(Object(I.B)(t,{allowHashes:!1}),r)}),Object(P.fromJS)({}))}function Oe(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(P.List.isList(e))return C()(e).call(e,(function(e){return P.Map.isMap(e)&&e.get("in")===t}))}function Ce(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(P.List.isList(e))return C()(e).call(e,(function(e){return P.Map.isMap(e)&&e.get("type")===t}))}function _e(e,t){var n,r;t=t||[];var a=z(e).getIn(c()(n=["paths"]).call(n,i()(t)),Object(P.fromJS)({})),o=e.getIn(c()(r=["meta","paths"]).call(r,i()(t)),Object(P.fromJS)({})),s=Ae(e,t),u=a.get("parameters")||new P.List,l=o.get("consumes_value")?o.get("consumes_value"):Ce(u,"file")?"multipart/form-data":Ce(u,"formData")?"application/x-www-form-urlencoded":void 0;return Object(P.fromJS)({requestContentType:l,responseContentType:s})}function Ae(e,t){var n,r;t=t||[];var a=z(e).getIn(c()(n=["paths"]).call(n,i()(t)),null);if(null!==a){var o=e.getIn(c()(r=["meta","paths"]).call(r,i()(t),["produces_value"]),null),s=a.getIn(["produces",0],null);return o||s||"application/json"}}function ke(e,t){var n;t=t||[];var r=z(e),o=r.getIn(c()(n=["paths"]).call(n,i()(t)),null);if(null!==o){var s=t,u=a()(s,1)[0],l=o.get("produces",null),p=r.getIn(["paths",u,"produces"],null),f=r.getIn(["produces"],null);return l||p||f}}function Ie(e,t){var n;t=t||[];var r=z(e),o=r.getIn(c()(n=["paths"]).call(n,i()(t)),null);if(null!==o){var s=t,u=a()(s,1)[0],l=o.get("consumes",null),p=r.getIn(["paths",u,"consumes"],null),f=r.getIn(["consumes"],null);return l||p||f}}var Pe=function(e,t,n){var r=e.get("url").match(/^([a-z][a-z0-9+\-.]*):/),a=A()(r)?r[1]:null;return e.getIn(["scheme",t,n])||e.getIn(["scheme","_defaultScheme"])||a||""},Te=function(e,t,n){var r;return h()(r=["http","https"]).call(r,Pe(e,t,n))>-1},Re=function(e,t){var n;t=t||[];var r=e.getIn(c()(n=["meta","paths"]).call(n,i()(t),["parameters"]),Object(P.fromJS)([])),a=!0;return f()(r).call(r,(function(e){var t=e.get("errors");t&&t.count()&&(a=!1)})),a},Ne=function(e,t){var n,r,a={requestBody:!1,requestContentType:{}},o=e.getIn(c()(n=["resolvedSubtrees","paths"]).call(n,i()(t),["requestBody"]),Object(P.fromJS)([]));return o.size<1||(o.getIn(["required"])&&(a.requestBody=o.getIn(["required"])),f()(r=o.getIn(["content"]).entrySeq()).call(r,(function(e){var t=e[0];if(e[1].getIn(["schema","required"])){var n=e[1].getIn(["schema","required"]).toJS();a.requestContentType[t]=n}}))),a},Me=function(e,t,n,r){var a;if((n||r)&&n===r)return!0;var o=e.getIn(c()(a=["resolvedSubtrees","paths"]).call(a,i()(t),["requestBody","content"]),Object(P.fromJS)([]));if(o.size<2||!n||!r)return!1;var s=o.getIn([n,"schema","properties"],Object(P.fromJS)([])),u=o.getIn([r,"schema","properties"],Object(P.fromJS)([]));return!!s.equals(u)};function De(e){return P.Map.isMap(e)?e:new P.Map}},function(e,t){e.exports=require("url-parse")},function(e,t,n){e.exports=n(742)},function(e,t){e.exports=!0},function(e,t,n){var r=n(190),a=n(60).f,o=n(59),i=n(48),s=n(417),c=n(36)("toStringTag");e.exports=function(e,t,n,u){if(e){var l=n?e:e.prototype;i(l,c)||a(l,c,{configurable:!0,value:t}),u&&!r&&o(l,"toString",s)}}},function(e,t,n){"use strict";var r=n(291).charAt,a=n(69),o=n(191),i="String Iterator",s=a.set,c=a.getterFor(i);o(String,"String",(function(e){s(this,{type:i,string:String(e),index:0})}),(function(){var e,t=c(this),n=t.string,a=t.index;return a>=n.length?{value:void 0,done:!0}:(e=r(n,a),t.index+=e.length,{value:e,done:!1})}))},function(e,t,n){e.exports=n(528)},function(e,t,n){e.exports=n(620)},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_LAYOUT",(function(){return a})),n.d(t,"UPDATE_FILTER",(function(){return o})),n.d(t,"UPDATE_MODE",(function(){return i})),n.d(t,"SHOW",(function(){return s})),n.d(t,"updateLayout",(function(){return c})),n.d(t,"updateFilter",(function(){return u})),n.d(t,"show",(function(){return l})),n.d(t,"changeMode",(function(){return p}));var r=n(5),a="layout_update_layout",o="layout_update_filter",i="layout_update_mode",s="layout_show";function c(e){return{type:a,payload:e}}function u(e){return{type:o,payload:e}}function l(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=Object(r.w)(e),{type:s,payload:{thing:e,shown:t}}}function p(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e=Object(r.w)(e),{type:i,payload:{thing:e,mode:t}}}},function(e,t,n){var r=n(336),a=n(128),o=n(152),i=n(47),s=n(99),c=n(153),u=n(127),l=n(202),p=Object.prototype.hasOwnProperty;e.exports=function(e){if(null==e)return!0;if(s(e)&&(i(e)||"string"==typeof e||"function"==typeof e.splice||c(e)||l(e)||o(e)))return!e.length;var t=a(e);if("[object Map]"==t||"[object Set]"==t)return!e.size;if(u(e))return!r(e).length;for(var n in e)if(p.call(e,n))return!1;return!0}},function(e,t){e.exports=require("react-syntax-highlighter")},function(e,t,n){var r=n(44),a=n(138),o=n(90),i=n(58),s=n(140),c=n(48),u=n(282),l=Object.getOwnPropertyDescriptor;t.f=r?l:function(e,t){if(e=i(e),t=s(t,!0),u)try{return l(e,t)}catch(e){}if(c(e,t))return o(!a.f.call(e,t),e[t])}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(67);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,a){return e.call(t,n,r,a)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r,a=n(46),o=n(183),i=n(186),s=n(123),c=n(287),u=n(178),l=n(144),p=l("IE_PROTO"),f=function(){},d=function(e){return"<script>"+e+"</"+"script>"},h=function(){try{r=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;h=r?function(e){e.write(d("")),e.close();var t=e.parentWindow.Object;return e=null,t}(r):((t=u("iframe")).style.display="none",c.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(d("document.F=Object")),e.close(),e.F);for(var n=i.length;n--;)delete h.prototype[i[n]];return h()};s[p]=!0,e.exports=Object.create||function(e,t){var n;return null!==e?(f.prototype=a(e),n=new f,f.prototype=null,n[p]=e):n=h(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(59);e.exports=function(e,t,n,a){a&&a.enumerable?e[t]=n:r(e,t,n)}},function(e,t){e.exports={}},function(e,t,n){"use strict";var r=n(34);e.exports=function(e,t){var n=[][e];return!!n&&r((function(){n.call(null,t||function(){throw 1},1)}))}},function(e,t,n){var r=n(105),a=n(535),o=n(536),i=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":i&&i in Object(e)?a(e):o(e)}},function(e,t,n){var r=n(553),a=n(556);e.exports=function(e,t){var n=a(e,t);return r(n)?n:void 0}},function(e,t,n){var r=n(335),a=n(336),o=n(99);e.exports=function(e){return o(e)?r(e):a(e)}},function(e,t,n){var r=n(55),a=n(203);e.exports=function(e){return null!=e&&a(e.length)&&!r(e)}},function(e,t,n){var r=n(46),a=n(310),o=n(68),i=n(91),s=n(126),c=n(309),u=function(e,t){this.stopped=e,this.result=t};e.exports=function(e,t,n){var l,p,f,d,h,m,v,g=n&&n.that,y=!(!n||!n.AS_ENTRIES),b=!(!n||!n.IS_ITERATOR),E=!(!n||!n.INTERRUPTED),x=i(t,g,1+y+E),S=function(e){return l&&c(l),new u(!0,e)},w=function(e){return y?(r(e),E?x(e[0],e[1],S):x(e[0],e[1])):E?x(e,S):x(e)};if(b)l=e;else{if("function"!=typeof(p=s(e)))throw TypeError("Target is not iterable");if(a(p)){for(f=0,d=o(e.length);d>f;f++)if((h=w(e[f]))&&h instanceof u)return h;return new u(!1)}l=p.call(e)}for(m=l.next;!(v=m.call(l)).done;){try{h=w(v.value)}catch(e){throw c(l),e}if("object"==typeof h&&h&&h instanceof u)return h}return new u(!1)}},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){e.exports=n(753)},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return l}));var r=n(12),a=n.n(r),o=n(4),i=n.n(o),s=n(384),c=n.n(s),u=[n(215),n(216)];function l(e){var t,n={jsSpec:{}},r=c()(u,(function(e,t){try{var r=t.transform(e,n);return a()(r).call(r,(function(e){return!!e}))}catch(t){return console.error("Transformer error:",t),e}}),e);return i()(t=a()(r).call(r,(function(e){return!!e}))).call(t,(function(e){return!e.get("line")&&e.get("path"),e}))}},function(e,t){e.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(64).Symbol;e.exports=r},function(e,t,n){var r=n(47),a=n(206),o=n(600),i=n(77);e.exports=function(e,t){return r(e)?e:a(e,t)?[e]:o(i(e))}},function(e,t,n){var r=n(146);e.exports=function(e){if("string"==typeof e||r(e))return e;var t=e+"";return"0"==t&&1/e==-Infinity?"-0":t}},function(e,t){e.exports=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e}},function(e,t,n){var r=n(157),a=n(361);e.exports=function(e,t,n,o){var i=!n;n||(n={});for(var s=-1,c=t.length;++s<c;){var u=t[s],l=o?o(n[u],e[u],u,n,e):void 0;void 0===l&&(l=e[u]),i?a(n,u,l):r(n,u,l)}return n}},function(e,t){e.exports=require("serialize-error")},function(e,t,n){"use strict";n.r(t),n.d(t,"sampleFromSchemaGeneric",(function(){return j})),n.d(t,"inferSchema",(function(){return O})),n.d(t,"createXMLExample",(function(){return C})),n.d(t,"sampleFromSchema",(function(){return _})),n.d(t,"memoizedCreateXMLExample",(function(){return A})),n.d(t,"memoizedSampleFromSchema",(function(){return k}));var r=n(19),a=n.n(r),o=n(2),i=n.n(o),s=n(14),c=n.n(s),u=n(13),l=n.n(u),p=n(4),f=n.n(p),d=n(5),h=n(380),m=n.n(h),v=n(270),g=n.n(v),y=n(87),b=n.n(y),E={string:function(){return"string"},string_email:function(){return"[email protected]"},"string_date-time":function(){return(new Date).toISOString()},string_date:function(){return(new Date).toISOString().substring(0,10)},string_uuid:function(){return"3fa85f64-5717-4562-b3fc-2c963f66afa6"},string_hostname:function(){return"example.com"},string_ipv4:function(){return"198.51.100.42"},string_ipv6:function(){return"2001:0db8:5b96:0000:0000:426f:8e17:642a"},number:function(){return 0},number_float:function(){return 0},integer:function(){return 0},boolean:function(e){return"boolean"!=typeof e.default||e.default}},x=function(e){var t,n=e=Object(d.A)(e),r=n.type,a=n.format,o=E[i()(t="".concat(r,"_")).call(t,a)]||E[r];return Object(d.s)(o)?o(e):"Unknown Type: "+e.type},S=function(e){return Object(d.e)(e,"$$ref",(function(e){return"string"==typeof e&&c()(e).call(e,"#")>-1}))},w=function(e,t){return void 0===t.example&&void 0!==e.example&&(t.example=e.example),void 0===t.default&&void 0!==e.default&&(t.default=e.default),void 0===t.enum&&void 0!==e.enum&&(t.enum=e.enum),void 0===t.xml&&void 0!==e.xml&&(t.xml=e.xml),void 0===t.type&&void 0!==e.type&&(t.type=e.type),t},j=function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];t=Object(d.A)(t);var s=void 0!==r||void 0!==t.example||t&&void 0!==t.default,u=!s&&t&&t.oneOf&&t.oneOf.length>0,p=!s&&t&&t.anyOf&&t.anyOf.length>0;if(!s&&(u||p)){var h=Object(d.A)(u?t.oneOf[0]:t.anyOf[0]);if(w(h,t),!t.xml&&h.xml&&(t.xml=h.xml),void 0!==t.example&&void 0!==h.example)s=!0;else if(h.properties){t.properties||(t.properties={});var m=Object(d.A)(h.properties);for(var v in m){var g;if(m.hasOwnProperty(v))if(!m[v]||!m[v].deprecated)if(!m[v]||!m[v].readOnly||n.includeReadOnly)if(!m[v]||!m[v].writeOnly||n.includeWriteOnly)if(!t.properties[v])t.properties[v]=m[v],!h.required&&l()(h.required)&&-1!==c()(g=h.required).call(g,v)&&(t.required?t.required.push(v):t.required=[v])}}}var y,E={},j=t,O=j.xml,C=j.type,_=j.example,A=j.properties,k=j.additionalProperties,I=j.items,P=n.includeReadOnly,T=n.includeWriteOnly,R=O=O||{},N=R.name,M=R.prefix,D=R.namespace,q={};if(o&&(y=(M?M+":":"")+(N=N||"notagname"),D)){var B=M?"xmlns:"+M:"xmlns";E[B]=D}if(o&&(q[y]=[]),t&&!C)if(A||k)C="object";else if(I)C="array";else if(!s&&!t.enum)return;var L,U,V=Object(d.A)(A);if(L=o?function(r){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0;if(t&&V[r]){if(V[r].xml=V[r].xml||{},V[r].xml.attribute){var s=l()(V[r].enum)?V[r].enum[0]:void 0,c=V[r].example,u=V[r].default;return void(E[V[r].xml.name||r]=void 0!==c?c:void 0!==u?u:void 0!==s?s:x(V[r]))}V[r].xml.name=V[r].xml.name||r}else V[r]||!1===k||(V[r]={xml:{name:r}});var p,f=e(t&&V[r]||void 0,n,a,o);l()(f)?q[y]=i()(p=q[y]).call(p,f):q[y].push(f)}:function(t,r){q[t]=e(V[t],n,r,o)},s){var z;if(z=S(void 0!==r?r:void 0!==_?_:t.default),!o){if("number"==typeof z&&"string"===C)return"".concat(z);if("string"!=typeof z||"string"===C)return z;try{return JSON.parse(z)}catch(e){return z}}if(t||(C=l()(z)?"array":a()(z)),"array"===C){if(!l()(z)){if("string"==typeof z)return z;z=[z]}var F=t?t.items:void 0;F&&(F.xml=F.xml||O||{},F.xml.name=F.xml.name||O.name);var J=f()(z).call(z,(function(t){return e(F,n,t,o)}));return O.wrapped?(q[y]=J,b()(E)||q[y].push({_attr:E})):q=J,q}if("object"===C){if("string"==typeof z)return z;for(var W in z)z.hasOwnProperty(W)&&(t&&V[W]&&V[W].readOnly&&!P||t&&V[W]&&V[W].writeOnly&&!T||(!(t&&V[W]&&V[W].xml&&V[W].xml.attribute)||_&&_[W]?t&&V[W]&&V[W].xml&&V[W].xml.attribute?E[V[W].xml.name||W]=_[W]:L(W,z[W]):E[V[W].xml.name||W]=z[W]));return b()(E)||q[y].push({_attr:E}),q}return q[y]=b()(E)?z:[{_attr:E},z],q}if("object"===C){for(var H in V)V.hasOwnProperty(H)&&(V[H]&&V[H].deprecated||V[H]&&V[H].readOnly&&!P||V[H]&&V[H].writeOnly&&!T||L(H));if(!0===k)o?q[y].push({additionalProp:"Anything can be here"}):q.additionalProp1={};else if(k){var $=Object(d.A)(k),Y=e($,n,void 0,o);if(o&&$.xml&&$.xml.name&&"notagname"!==$.xml.name)q[y].push(Y);else for(var K=1;K<4;K++)if(o){var G={};G["additionalProp"+K]=Y.notagname,q[y].push(G)}else q["additionalProp"+K]=Y}return o&&E&&q[y].push({_attr:E}),q}if("array"===C){var Z,X;if(o&&(I.xml=I.xml||t.xml||{},I.xml.name=I.xml.name||O.name),l()(I.anyOf))Z=f()(X=I.anyOf).call(X,(function(t){return e(w(I,t),n,void 0,o)}));else if(l()(I.oneOf)){var Q;Z=f()(Q=I.oneOf).call(Q,(function(t){return e(w(I,t),n,void 0,o)}))}else{if(!(!o||o&&O.wrapped))return e(I,n,void 0,o);Z=[e(I,n,void 0,o)]}return o&&O.wrapped?(q[y]=Z,b()(E)||q[y].push({_attr:E}),q):Z}if(t&&l()(t.enum))U=Object(d.w)(t.enum)[0];else{if(!t)return;U=x(t)}if("file"!==C)return o?(q[y]=b()(E)?U:[{_attr:E},U],q):U},O=function(e){return e.schema&&(e=e.schema),e.properties&&(e.type="object"),e},C=function(e,t,n){var r=j(e,t,n,!0);if(r)return"string"==typeof r?r:m()(r,{declaration:!0,indent:"\t"})},_=function(e,t,n){return j(e,t,n,!1)},A=g()(C),k=g()(_)},function(e,t,n){"use strict";n.r(t),n.d(t,"UPDATE_CONFIGS",(function(){return o})),n.d(t,"TOGGLE_CONFIGS",(function(){return i})),n.d(t,"update",(function(){return s})),n.d(t,"toggle",(function(){return c})),n.d(t,"loaded",(function(){return u}));var r=n(3),a=n.n(r),o="configs_update",i="configs_toggle";function s(e,t){return{type:o,payload:a()({},e,t)}}function c(e){return{type:i,payload:e}}var u=function(){return function(e){var t=e.getConfigs,n=e.authActions;if(t().persistAuthorization){var r=localStorage.getItem("authorized");r&&n.restoreAuthorization({authorized:JSON.parse(r)})}}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return l}));var r=n(12),a=n.n(r),o=n(35),i=n.n(o),s=n(1),c=n.n(s),u=c.a.Set.of("type","format","items","default","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","enum","multipleOf");function l(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.isOAS3;if(!c.a.Map.isMap(e))return{schema:c.a.Map(),parameterContentMediaType:null};if(!n)return"body"===e.get("in")?{schema:e.get("schema",c.a.Map()),parameterContentMediaType:null}:{schema:a()(e).call(e,(function(e,t){return i()(u).call(u,t)})),parameterContentMediaType:null};if(e.get("content")){var r=e.get("content",c.a.Map({})).keySeq(),o=r.first();return{schema:e.getIn(["content",o,"schema"],c.a.Map()),parameterContentMediaType:o}}return{schema:e.get("schema",c.a.Map()),parameterContentMediaType:null}}},function(e,t){e.exports=require("fast-json-patch")},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(115);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){"use strict";var r=n(140),a=n(60),o=n(90);e.exports=function(e,t,n){var i=r(t);i in e?a.f(e,i,o(0,n)):e[i]=n}},function(e,t,n){var r=n(115),a=n(38);e.exports="process"==r(a.process)},function(e,t,n){var r,a,o=n(38),i=n(142),s=o.process,c=s&&s.versions,u=c&&c.v8;u?a=(r=u.split("."))[0]+r[1]:i&&(!(r=i.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=i.match(/Chrome\/(\d+)/))&&(a=r[1]),e.exports=a&&+a},function(e,t,n){var r=n(34),a=n(36),o=n(120),i=a("species");e.exports=function(e){return o>=51||!r((function(){var t=[];return(t.constructor={})[i]=function(){return{foo:1}},1!==t[e](Boolean).foo}))}},function(e,t,n){var r=n(286),a=n(186);e.exports=Object.keys||function(e){return r(e,a)}},function(e,t){e.exports={}},function(e,t,n){var r=n(48),a=n(61),o=n(144),i=n(294),s=o("IE_PROTO"),c=Object.prototype;e.exports=i?Object.getPrototypeOf:function(e){return e=a(e),r(e,s)?e[s]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?c:null}},function(e,t,n){"use strict";var r=n(58),a=n(193),o=n(94),i=n(69),s=n(191),c="Array Iterator",u=i.set,l=i.getterFor(c);e.exports=s(Array,"Array",(function(e,t){u(this,{type:c,target:r(e),index:0,kind:t})}),(function(){var e=l(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values"),o.Arguments=o.Array,a("keys"),a("values"),a("entries")},function(e,t,n){var r=n(74),a=n(94),o=n(36)("iterator");e.exports=function(e){if(null!=e)return e[o]||e["@@iterator"]||a[r(e)]}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var r=n(594),a=n(197),o=n(595),i=n(596),s=n(597),c=n(96),u=n(327),l="[object Map]",p="[object Promise]",f="[object Set]",d="[object WeakMap]",h="[object DataView]",m=u(r),v=u(a),g=u(o),y=u(i),b=u(s),E=c;(r&&E(new r(new ArrayBuffer(1)))!=h||a&&E(new a)!=l||o&&E(o.resolve())!=p||i&&E(new i)!=f||s&&E(new s)!=d)&&(E=function(e){var t=c(e),n="[object Object]"==t?e.constructor:void 0,r=n?u(n):"";if(r)switch(r){case m:return h;case v:return l;case g:return p;case y:return f;case b:return d}return t}),e.exports=E},function(e,t,n){var r=n(93);e.exports=function(e,t,n){for(var a in t)n&&n.unsafe&&e[a]?e[a]=t[a]:r(e,a,t[a],n);return e}},function(e,t,n){"use strict";var r=n(67),a=function(e){var t,n;this.promise=new e((function(e,r){if(void 0!==t||void 0!==n)throw TypeError("Bad Promise constructor");t=e,n=r})),this.resolve=r(t),this.reject=r(n)};e.exports.f=function(e){return new a(e)}},function(e,t,n){"use strict";n.r(t),n.d(t,"parseYamlConfig",(function(){return o}));var r=n(65),a=n.n(r),o=function(e,t){try{return a.a.safeLoad(e)}catch(e){return t&&t.errActions.newThrownErr(new Error(e)),{}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"getDefaultRequestBodyValue",(function(){return b}));var r=n(16),a=n.n(r),o=n(4),i=n.n(o),s=n(14),c=n.n(s),u=n(35),l=n.n(u),p=n(2),f=n.n(p),d=n(13),h=n.n(d),m=n(0),v=n.n(m),g=(n(11),n(27),n(1)),y=n(5),b=function(e,t,n){var r=e.getIn(["content",t]),a=r.get("schema").toJS(),o=void 0!==r.get("examples"),i=r.get("example"),s=o?r.getIn(["examples",n,"value"]):i,c=Object(y.o)(a,t,{includeWriteOnly:!0},s);return Object(y.J)(c)};t.default=function(e){var t=e.userHasEditedBody,n=e.requestBody,r=e.requestBodyValue,o=e.requestBodyInclusionSetting,s=e.requestBodyErrors,u=e.getComponent,p=e.getConfigs,d=e.specSelectors,m=e.fn,E=e.contentType,x=e.isExecute,S=e.specPath,w=e.onChange,j=e.onChangeIncludeEmpty,O=e.activeExamplesKey,C=e.updateActiveExamplesKey,_=e.setRetainRequestBodyValueFlag,A=function(e){var t={key:e,shouldDispatchInit:!1,defaultValue:!0};return"no value"===o.get(e,"no value")&&(t.shouldDispatchInit=!0),t},k=u("Markdown",!0),I=u("modelExample"),P=u("RequestBodyEditor"),T=u("highlightCode"),R=u("ExamplesSelectValueRetainer"),N=u("Example"),M=u("ParameterIncludeEmpty"),D=p().showCommonExtensions,q=n&&n.get("description")||null,B=n&&n.get("content")||new g.OrderedMap;E=E||B.keySeq().first()||"";var L=B.get(E,Object(g.OrderedMap)()),U=L.get("schema",Object(g.OrderedMap)()),V=L.get("examples",null),z=null==V?void 0:i()(V).call(V,(function(e,t){var r,a=null===(r=e)||void 0===r?void 0:r.get("value",null);return a&&(e=e.set("value",b(n,E,t),a)),e}));if(s=g.List.isList(s)?s:Object(g.List)(),!L.size)return null;var F="object"===L.getIn(["schema","type"]);if("application/octet-stream"===E||0===c()(E).call(E,"image/")||0===c()(E).call(E,"audio/")||0===c()(E).call(E,"video/")){var J=u("Input");return x?v.a.createElement(J,{type:"file",onChange:function(e){w(e.target.files[0])}}):v.a.createElement("i",null,"Example values are not available for ",v.a.createElement("code",null,"application/octet-stream")," media types.")}if(F&&("application/x-www-form-urlencoded"===E||0===c()(E).call(E,"multipart/"))&&U.get("properties",Object(g.OrderedMap)()).size>0){var W,H=u("JsonSchemaForm"),$=u("ParameterExt"),Y=U.get("properties",Object(g.OrderedMap)());return r=g.Map.isMap(r)?r:Object(g.OrderedMap)(),v.a.createElement("div",{className:"table-container"},q&&v.a.createElement(k,{source:q}),v.a.createElement("table",null,v.a.createElement("tbody",null,g.Map.isMap(Y)&&i()(W=Y.entrySeq()).call(W,(function(e){var t,n,c=a()(e,2),p=c[0],d=c[1];if(!d.get("readOnly")){var b=D?Object(y.l)(d):null,E=l()(t=U.get("required",Object(g.List)())).call(t,p),S=d.get("type"),O=d.get("format"),C=d.get("description"),_=r.getIn([p,"value"]),I=r.getIn([p,"errors"])||s,P=o.get(p)||!1,T=d.has("default")||d.has("example")||d.hasIn(["items","example"])||d.hasIn(["items","default"]),R=d.has("enum")&&(1===d.get("enum").size||E),N=T||R,q="";"array"!==S||N?N&&(q=Object(y.o)(d,!1,{includeWriteOnly:!0})):q=[],"string"!=typeof q&&"object"===S&&(q=Object(y.J)(q)),"string"==typeof q&&"array"===S&&(q=JSON.parse(q));var B="string"===S&&("binary"===O||"base64"===O);return v.a.createElement("tr",{key:p,className:"parameters","data-property-name":p},v.a.createElement("td",{className:"parameters-col_name"},v.a.createElement("div",{className:E?"parameter__name required":"parameter__name"},p,E?v.a.createElement("span",null," *"):null),v.a.createElement("div",{className:"parameter__type"},S,O&&v.a.createElement("span",{className:"prop-format"},"($",O,")"),D&&b.size?i()(n=b.entrySeq()).call(n,(function(e){var t,n=a()(e,2),r=n[0],o=n[1];return v.a.createElement($,{key:f()(t="".concat(r,"-")).call(t,o),xKey:r,xVal:o})})):null),v.a.createElement("div",{className:"parameter__deprecated"},d.get("deprecated")?"deprecated":null)),v.a.createElement("td",{className:"parameters-col_description"},v.a.createElement(k,{source:C}),x?v.a.createElement("div",null,v.a.createElement(H,{fn:m,dispatchInitialValue:!B,schema:d,description:p,getComponent:u,value:void 0===_?q:_,required:E,errors:I,onChange:function(e){w(e,[p])}}),E?null:v.a.createElement(M,{onChange:function(e){return j(p,e)},isIncluded:P,isIncludedOptions:A(p),isDisabled:h()(_)?0!==_.length:!Object(y.q)(_)})):null))}})))))}var K=b(n,E,O);return v.a.createElement("div",null,q&&v.a.createElement(k,{source:q}),z?v.a.createElement(R,{userHasEditedBody:t,examples:z,currentKey:O,currentUserInputValue:r,onSelect:function(e){C(e)},updateValue:w,defaultToFirstExample:!0,getComponent:u,setRetainRequestBodyValueFlag:_}):null,x?v.a.createElement("div",null,v.a.createElement(P,{value:r,errors:s,defaultValue:K,onChange:w,getComponent:u})):v.a.createElement(I,{getComponent:u,getConfigs:p,specSelectors:d,expandDepth:1,isExecute:x,schema:L.get("schema"),specPath:S.push("content",E),example:v.a.createElement(T,{className:"body-param__example",getConfigs:p,value:Object(y.J)(r)||K}),includeWriteOnly:!0}),z?v.a.createElement(N,{example:z.get(O),getComponent:u,getConfigs:p}):null)}},function(e,t,n){e.exports=n(524)},function(e,t,n){"use strict";n.r(t),n.d(t,"makeMappedContainer",(function(){return A})),n.d(t,"render",(function(){return k})),n.d(t,"getComponent",(function(){return T}));var r=n(19),a=n.n(r),o=n(28),i=n.n(o),s=n(6),c=n.n(s),u=n(7),l=n.n(u),p=n(8),f=n.n(p),d=n(9),h=n.n(d),m=n(22),v=n.n(m),g=n(17),y=n.n(g),b=n(0),E=n.n(b),x=n(386),S=n.n(x),w=n(274),j=n(387),O=n.n(j),C=function(e,t,n){var r=function(e,t){return function(n){f()(a,n);var r=h()(a);function a(){return c()(this,a),r.apply(this,arguments)}return l()(a,[{key:"render",value:function(){return E.a.createElement(t,i()({},e(),this.props,this.context))}}]),a}(b.Component)}(e,t),a=Object(w.connect)((function(n,r){var a=v()({},r,e());return(t.prototype.mapStateToProps||function(e){return{state:e}})(n,a)}))(r);return n?function(e,t){return function(n){f()(a,n);var r=h()(a);function a(){return c()(this,a),r.apply(this,arguments)}return l()(a,[{key:"render",value:function(){return E.a.createElement(w.Provider,{store:e},E.a.createElement(t,i()({},this.props,this.context)))}}]),a}(b.Component)}(n,a):a},_=function(e,t,n,r){for(var a in t){var o=t[a];"function"==typeof o&&o(n[a],r[a],e())}},A=function(e,t,n,r,a,o){return function(t){f()(i,t);var r=h()(i);function i(t,n){var a;return c()(this,i),a=r.call(this,t,n),_(e,o,t,{}),a}return l()(i,[{key:"componentWillReceiveProps",value:function(t){_(e,o,t,this.props)}},{key:"render",value:function(){var e=O()(this.props,o?y()(o):[]),t=n(a,"root");return E.a.createElement(t,e)}}]),i}(b.Component)},k=function(e,t,n,r,a){var o=n(e,t,r,"App","root");S.a.render(E.a.createElement(o,null),a)},I=function(e){var t=e.name;return E.a.createElement("div",{className:"fallback"},"😱 ",E.a.createElement("i",null,"Could not render ","t"===t?"this component":t,", see the console."))},P=function(e){var t=function(e){return!(e.prototype&&e.prototype.isReactComponent)}(e)?function(e){return function(t){f()(r,t);var n=h()(r);function r(){return c()(this,r),n.apply(this,arguments)}return l()(r,[{key:"render",value:function(){return e(this.props)}}]),r}(b.Component)}(e):e,n=t.prototype.render;return t.prototype.render=function(){try{for(var e=arguments.length,r=new Array(e),a=0;a<e;a++)r[a]=arguments[a];return n.apply(this,r)}catch(e){return console.error(e),E.a.createElement(I,{error:e,name:t.name})}},t},T=function(e,t,n,r,o){var i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};if("string"!=typeof r)throw new TypeError("Need a string, to fetch a component. Was given a "+a()(r));var s=n(r);return s?o?"root"===o?C(e,s,t()):C(e,P(s)):P(s):(i.failSilently||e().log.warn("Could not find component:",r),null)}},function(e,t,n){"use strict";n.r(t),n.d(t,"setHash",(function(){return r}));var r=function(e){return e?history.pushState(null,null,"#".concat(e)):window.location.hash=""}},function(e,t){e.exports=require("redux")},function(e,t,n){e.exports=n(413)},function(e,t,n){"use strict";var r={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,o=a&&!r.call({1:2},1);t.f=o?function(e){var t=a(this,e);return!!t&&t.enumerable}:r},function(e,t,n){var r=n(34),a=n(115),o="".split;e.exports=r((function(){return!Object("z").propertyIsEnumerable(0)}))?function(e){return"String"==a(e)?o.call(e,""):Object(e)}:Object},function(e,t,n){var r=n(40);e.exports=function(e,t){if(!r(e))return e;var n,a;if(t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;if("function"==typeof(n=e.valueOf)&&!r(a=n.call(e)))return a;if(!t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;throw TypeError("Can't convert object to primitive value")}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++n+r).toString(36)}},function(e,t,n){var r=n(62);e.exports=r("navigator","userAgent")||""},function(e,t){},function(e,t,n){var r=n(180),a=n(141),o=r("keys");e.exports=function(e){return o[e]||(o[e]=a(e))}},function(e,t,n){var r=n(488),a=n(306),o=n(303);e.exports=function(e,t){var n;if(e){if("string"==typeof e)return o(e,t);var i=r(n=Object.prototype.toString.call(e)).call(n,8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?a(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?o(e,t):void 0}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(96),a=n(76);e.exports=function(e){return"symbol"==typeof e||a(e)&&"[object Symbol]"==r(e)}},function(e,t,n){var r=n(97)(Object,"create");e.exports=r},function(e,t,n){var r=n(561),a=n(562),o=n(563),i=n(564),s=n(565);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=i,c.prototype.set=s,e.exports=c},function(e,t,n){var r=n(101);e.exports=function(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}},function(e,t,n){var r=n(567);e.exports=function(e,t){var n=e.__data__;return r(t)?n["string"==typeof t?"string":"hash"]:n.map}},function(e,t,n){var r=n(572),a=n(599),o=n(207),i=n(47),s=n(604);e.exports=function(e){return"function"==typeof e?e:null==e?o:"object"==typeof e?i(e)?a(e[0],e[1]):r(e):s(e)}},function(e,t,n){var r=n(590),a=n(76),o=Object.prototype,i=o.hasOwnProperty,s=o.propertyIsEnumerable,c=r(function(){return arguments}())?r:function(e){return a(e)&&i.call(e,"callee")&&!s.call(e,"callee")};e.exports=c},function(e,t,n){(function(e){var r=n(64),a=n(591),o=t&&!t.nodeType&&t,i=o&&"object"==typeof e&&e&&!e.nodeType&&e,s=i&&i.exports===o?r.Buffer:void 0,c=(s?s.isBuffer:void 0)||a;e.exports=c}).call(this,n(201)(e))},function(e,t){var n=/^(?:0|[1-9]\d*)$/;e.exports=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&n.test(e))&&e>-1&&e%1==0&&e<t}},function(e,t,n){var r=n(106),a=n(107);e.exports=function(e,t){for(var n=0,o=(t=r(t,e)).length;null!=e&&n<o;)e=e[a(t[n++])];return n&&n==o?e:void 0}},function(e,t){e.exports=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}}},function(e,t,n){var r=n(361),a=n(101),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var i=e[t];o.call(e,t)&&a(i,n)&&(void 0!==n||t in e)||r(e,t,n)}},function(e,t,n){var r=n(123),a=n(40),o=n(48),i=n(60).f,s=n(141),c=n(737),u=s("meta"),l=0,p=Object.isExtensible||function(){return!0},f=function(e){i(e,u,{value:{objectID:"O"+ ++l,weakData:{}}})},d=e.exports={REQUIRED:!1,fastKey:function(e,t){if(!a(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!o(e,u)){if(!p(e))return"F";if(!t)return"E";f(e)}return e[u].objectID},getWeakData:function(e,t){if(!o(e,u)){if(!p(e))return!0;if(!t)return!1;f(e)}return e[u].weakData},onFreeze:function(e){return c&&d.REQUIRED&&p(e)&&!o(e,u)&&f(e),e}};r[u]=!0},function(e,t,n){var r=n(364),a=n(679);function o(t){return e.exports=o=r?a:function(e){return e.__proto__||a(e)},e.exports.default=e.exports,e.exports.__esModule=!0,o(t)}e.exports=o,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(502)},function(e,t,n){var r=n(571)(n(607));e.exports=r},function(e,t,n){e.exports=n(660)},function(e,t,n){var r=n(96),a=n(47),o=n(76);e.exports=function(e){return"string"==typeof e||!a(e)&&o(e)&&"[object String]"==r(e)}},function(e,t,n){e.exports=n(720)},function(e,t,n){var r=n(722),a=n(369)((function(e,t){return null==e?{}:r(e,t)}));e.exports=a},function(e,t){e.exports=require("buffer")},function(e,t,n){var r=n(157),a=n(109),o=n(740),i=n(99),s=n(127),c=n(98),u=Object.prototype.hasOwnProperty,l=o((function(e,t){if(s(t)||i(t))a(t,c(t),e);else for(var n in t)u.call(t,n)&&r(e,n,t[n])}));e.exports=l},function(e,t){e.exports=require("btoa")},function(e,t,n){e.exports=n(747)},function(e,t,n){"use strict";n.d(t,"a",(function(){return _}));var r=n(19),a=n.n(r),o=n(6),i=n.n(o),s=n(7),c=n.n(s),u=n(10),l=n.n(u),p=n(8),f=n.n(p),d=n(9),h=n.n(d),m=n(3),v=n.n(m),g=n(17),y=n.n(g),b=n(2),E=n.n(b),x=n(0),S=n.n(x),w=n(79),j=n.n(w),O=(n(11),n(5)),C=n(26),_=function(e){f()(n,e);var t=h()(n);function n(e,r){var a;i()(this,n),a=t.call(this,e,r),v()(l()(a),"getDefinitionUrl",(function(){var e=a.props.specSelectors;return new j.a(e.url(),C.a.location).toString()}));var o=(0,e.getConfigs)().validatorUrl;return a.state={url:a.getDefinitionUrl(),validatorUrl:void 0===o?"https://validator.swagger.io/validator":o},a}return c()(n,[{key:"componentWillReceiveProps",value:function(e){var t=(0,e.getConfigs)().validatorUrl;this.setState({url:this.getDefinitionUrl(),validatorUrl:void 0===t?"https://validator.swagger.io/validator":t})}},{key:"render",value:function(){var e,t,n=(0,this.props.getConfigs)().spec,r=Object(O.G)(this.state.validatorUrl);return"object"===a()(n)&&y()(n).length?null:this.state.url&&Object(O.F)(this.state.validatorUrl)&&Object(O.F)(this.state.url)?S.a.createElement("span",{className:"float-right"},S.a.createElement("a",{target:"_blank",rel:"noopener noreferrer",href:E()(e="".concat(r,"/debug?url=")).call(e,encodeURIComponent(this.state.url))},S.a.createElement(A,{src:E()(t="".concat(r,"?url=")).call(t,encodeURIComponent(this.state.url)),alt:"Online validator badge"}))):null}}]),n}(S.a.Component),A=function(e){f()(n,e);var t=h()(n);function n(e){var r;return i()(this,n),(r=t.call(this,e)).state={loaded:!1,error:!1},r}return c()(n,[{key:"componentDidMount",value:function(){var e=this,t=new Image;t.onload=function(){e.setState({loaded:!0})},t.onerror=function(){e.setState({error:!0})},t.src=this.props.src}},{key:"componentWillReceiveProps",value:function(e){var t=this;if(e.src!==this.props.src){var n=new Image;n.onload=function(){t.setState({loaded:!0})},n.onerror=function(){t.setState({error:!0})},n.src=e.src}}},{key:"render",value:function(){return this.state.error?S.a.createElement("img",{alt:"Error"}):this.state.loaded?S.a.createElement("img",{src:this.props.src,alt:this.props.alt}):null}}]),n}(S.a.Component)},function(e,t){e.exports=require("react-copy-to-clipboard")},function(e,t,n){"use strict";n.d(t,"a",(function(){return P}));var r=n(28),a=n.n(r),o=n(6),i=n.n(o),s=n(7),c=n.n(s),u=n(10),l=n.n(u),p=n(8),f=n.n(p),d=n(9),h=n.n(d),m=n(3),v=n.n(m),g=n(2),y=n.n(g),b=n(14),E=n.n(b),x=n(4),S=n.n(x),w=n(0),j=n.n(w),O=n(410),C=n.n(O),_=n(27),A=n.n(_),k=n(11),I=n.n(k),P=function(e){f()(r,e);var t=h()(r);function r(){var e,n;i()(this,r);for(var a=arguments.length,o=new Array(a),s=0;s<a;s++)o[s]=arguments[s];return n=t.call.apply(t,y()(e=[this]).call(e,o)),v()(l()(n),"getModelName",(function(e){return-1!==E()(e).call(e,"#/definitions/")?e.replace(/^.*#\/definitions\//,""):-1!==E()(e).call(e,"#/components/schemas/")?e.replace(/^.*#\/components\/schemas\//,""):void 0})),v()(l()(n),"getRefSchema",(function(e){return n.props.specSelectors.findDefinition(e)})),n}return c()(r,[{key:"render",value:function(){var e=this.props,t=e.getComponent,r=e.getConfigs,o=e.specSelectors,i=e.schema,s=e.required,c=e.name,u=e.isRef,l=e.specPath,p=e.displayName,f=e.includeReadOnly,d=e.includeWriteOnly,h=t("ObjectModel"),m=t("ArrayModel"),v=t("PrimitiveModel"),g="object",y=i&&i.get("$$ref");if(!c&&y&&(c=this.getModelName(y)),!i&&y&&(i=this.getRefSchema(c)),!i)return j.a.createElement("span",{className:"model model-title"},j.a.createElement("span",{className:"model-title__text"},p||c),j.a.createElement("img",{src:n(375),height:"20px",width:"20px"}));var b=o.isOAS3()&&i.get("deprecated");switch(u=void 0!==u?u:!!y,g=i&&i.get("type")||g){case"object":return j.a.createElement(h,a()({className:"object"},this.props,{specPath:l,getConfigs:r,schema:i,name:c,deprecated:b,isRef:u,includeReadOnly:f,includeWriteOnly:d}));case"array":return j.a.createElement(m,a()({className:"array"},this.props,{getConfigs:r,schema:i,name:c,deprecated:b,required:s,includeReadOnly:f,includeWriteOnly:d}));case"string":case"number":case"integer":case"boolean":default:return j.a.createElement(v,a()({},this.props,{getComponent:t,getConfigs:r,schema:i,name:c,deprecated:b,required:s}))}}}]),r}(C.a);v()(P,"propTypes",{schema:S()(A.a).isRequired,getComponent:I.a.func.isRequired,getConfigs:I.a.func.isRequired,specSelectors:I.a.object.isRequired,name:I.a.string,displayName:I.a.string,isRef:I.a.bool,required:I.a.bool,expandDepth:I.a.number,depth:I.a.number,specPath:A.a.list.isRequired,includeReadOnly:I.a.bool,includeWriteOnly:I.a.bool})},function(e,t){e.exports=require("remarkable")},function(e,t,n){"use strict";n.d(t,"b",(function(){return y}));var r=n(0),a=n.n(r),o=(n(11),n(173)),i=n(411),s=n.n(i),c=/www|@|\:\/\//;function u(e){return/^<\/a\s*>/i.test(e)}function l(){var e=[],t=new s.a({stripPrefix:!1,url:!0,email:!0,replaceFn:function(t){switch(t.getType()){case"url":e.push({text:t.matchedText,url:t.getUrl()});break;case"email":e.push({text:t.matchedText,url:"mailto:"+t.getEmail().replace(/^mailto:/i,"")})}return!1}});return{links:e,autolinker:t}}function p(e){var t,n,r,a,o,i,s,p,f,d,h,m,v,g,y=e.tokens,b=null;for(n=0,r=y.length;n<r;n++)if("inline"===y[n].type)for(h=0,t=(a=y[n].children).length-1;t>=0;t--)if("link_close"!==(o=a[t]).type){if("htmltag"===o.type&&(g=o.content,/^<a[>\s]/i.test(g)&&h>0&&h--,u(o.content)&&h++),!(h>0)&&"text"===o.type&&c.test(o.content)){if(b||(m=(b=l()).links,v=b.autolinker),i=o.content,m.length=0,v.link(i),!m.length)continue;for(s=[],d=o.level,p=0;p<m.length;p++)e.inline.validateLink(m[p].url)&&((f=i.indexOf(m[p].text))&&s.push({type:"text",content:i.slice(0,f),level:d}),s.push({type:"link_open",href:m[p].url,title:"",level:d++}),s.push({type:"text",content:m[p].text,level:d}),s.push({type:"link_close",level:--d}),i=i.slice(f+m[p].text.length));i.length&&s.push({type:"text",content:i,level:d}),y[n].children=a=[].concat(a.slice(0,t),s,a.slice(t+1))}}else for(t--;a[t].level!==o.level&&"link_open"!==a[t].type;)t--}function f(e){e.core.ruler.push("linkify",p)}var d=n(176),h=n.n(d),m=n(54),v=n.n(m);function g(e){var t=e.source,n=e.className,r=void 0===n?"":n,i=e.getConfigs;if("string"!=typeof t)return null;var s=new o.Remarkable({html:!0,typographer:!0,breaks:!0,linkTarget:"_blank"}).use(f);s.core.ruler.disable(["replacements","smartquotes"]);var c=i().useUnsafeMarkdown,u=s.render(t),l=y(u,{useUnsafeMarkdown:c});return t&&u&&l?a.a.createElement("div",{className:v()(r,"markdown"),dangerouslySetInnerHTML:{__html:l}}):null}h.a.addHook&&h.a.addHook("beforeSanitizeElements",(function(e){return e.href&&e.setAttribute("rel","noopener noreferrer"),e})),g.defaultProps={getConfigs:function(){return{useUnsafeMarkdown:!1}}};t.a=g;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.useUnsafeMarkdown,r=void 0!==n&&n,a=r,o=r?[]:["style","class"];return r&&!y.hasWarnedAboutDeprecation&&(console.warn("useUnsafeMarkdown display configuration parameter is deprecated since >3.26.0 and will be removed in v4.0.0."),y.hasWarnedAboutDeprecation=!0),h.a.sanitize(e,{ADD_ATTR:["target"],FORBID_TAGS:["style"],ALLOW_DATA_ATTR:a,FORBID_ATTR:o})}y.hasWarnedAboutDeprecation=!1},function(e,t){e.exports=require("qs")},function(e,t){e.exports=require("dompurify")},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){var r=n(38),a=n(40),o=r.document,i=a(o)&&a(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(40),a=n(116),o=n(36)("species");e.exports=function(e,t){var n;return a(e)&&("function"!=typeof(n=e.constructor)||n!==Array&&!a(n.prototype)?r(n)&&null===(n=n[o])&&(n=void 0):n=void 0),new(void 0===n?Array:n)(0===t?0:t)}},function(e,t,n){var r=n(81),a=n(181);(e.exports=function(e,t){return a[e]||(a[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.9.1",mode:r?"pure":"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})},function(e,t,n){var r=n(38),a=n(415),o="__core-js_shared__",i=r[o]||a(o,{});e.exports=i},function(e,t,n){var r=n(119),a=n(120),o=n(34);e.exports=!!Object.getOwnPropertySymbols&&!o((function(){return!Symbol.sham&&(r?38===a:a>37&&a<41)}))},function(e,t,n){var r=n(44),a=n(60),o=n(46),i=n(122);e.exports=r?Object.defineProperties:function(e,t){o(e);for(var n,r=i(t),s=r.length,c=0;s>c;)a.f(e,n=r[c++],t[n]);return e}},function(e,t,n){var r=n(58),a=n(68),o=n(185),i=function(e){return function(t,n,i){var s,c=r(t),u=a(c.length),l=o(i,u);if(e&&n!=n){for(;u>l;)if((s=c[l++])!=s)return!0}else for(;u>l;l++)if((e||l in c)&&c[l]===n)return e||l||0;return!e&&-1}};e.exports={includes:i(!0),indexOf:i(!1)}},function(e,t,n){var r=n(117),a=Math.max,o=Math.min;e.exports=function(e,t){var n=r(e);return n<0?a(n+t,0):o(n,t)}},function(e,t){e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(e,t,n){var r=n(286),a=n(186).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,a)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(36);t.f=r},function(e,t,n){var r={};r[n(36)("toStringTag")]="z",e.exports="[object z]"===String(r)},function(e,t,n){"use strict";var r=n(24),a=n(292),o=n(124),i=n(192),s=n(82),c=n(59),u=n(93),l=n(36),p=n(81),f=n(94),d=n(293),h=d.IteratorPrototype,m=d.BUGGY_SAFARI_ITERATORS,v=l("iterator"),g="keys",y="values",b="entries",E=function(){return this};e.exports=function(e,t,n,l,d,x,S){a(n,t,l);var w,j,O,C=function(e){if(e===d&&P)return P;if(!m&&e in k)return k[e];switch(e){case g:case y:case b:return function(){return new n(this,e)}}return function(){return new n(this)}},_=t+" Iterator",A=!1,k=e.prototype,I=k[v]||k["@@iterator"]||d&&k[d],P=!m&&I||C(d),T="Array"==t&&k.entries||I;if(T&&(w=o(T.call(new e)),h!==Object.prototype&&w.next&&(p||o(w)===h||(i?i(w,h):"function"!=typeof w[v]&&c(w,v,E)),s(w,_,!0,!0),p&&(f[_]=E))),d==y&&I&&I.name!==y&&(A=!0,P=function(){return I.call(this)}),p&&!S||k[v]===P||c(k,v,P),f[t]=P,d)if(j={values:C(y),keys:x?P:C(g),entries:C(b)},S)for(O in j)(m||A||!(O in k))&&u(k,O,j[O]);else r({target:t,proto:!0,forced:m||A},j);return j}},function(e,t,n){var r=n(46),a=n(442);e.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(n,[]),t=n instanceof Array}catch(e){}return function(n,o){return r(n),a(o),t?e.call(n,o):n.__proto__=o,n}}():void 0)},function(e,t){e.exports=function(){}},function(e,t,n){e.exports=n(455)},function(e,t,n){e.exports=n(482)},function(e,t,n){var r=n(550),a=n(566),o=n(568),i=n(569),s=n(570);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=i,c.prototype.set=s,e.exports=c},function(e,t,n){var r=n(97)(n(64),"Map");e.exports=r},function(e,t,n){var r=n(148),a=n(574),o=n(575),i=n(576),s=n(577),c=n(578);function u(e){var t=this.__data__=new r(e);this.size=t.size}u.prototype.clear=a,u.prototype.delete=o,u.prototype.get=i,u.prototype.has=s,u.prototype.set=c,e.exports=u},function(e,t){e.exports=function(e,t){for(var n=-1,r=t.length,a=e.length;++n<r;)e[a+n]=t[n];return e}},function(e,t,n){var r=n(588),a=n(334),o=Object.prototype.propertyIsEnumerable,i=Object.getOwnPropertySymbols,s=i?function(e){return null==e?[]:(e=Object(e),r(i(e),(function(t){return o.call(e,t)})))}:a;e.exports=s},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,n){var r=n(592),a=n(204),o=n(205),i=o&&o.isTypedArray,s=i?a(i):r;e.exports=s},function(e,t){e.exports=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991}},function(e,t){e.exports=function(e){return function(t){return e(t)}}},function(e,t,n){(function(e){var r=n(322),a=t&&!t.nodeType&&t,o=a&&"object"==typeof e&&e&&!e.nodeType&&e,i=o&&o.exports===a&&r.process,s=function(){try{var e=o&&o.require&&o.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=s}).call(this,n(201)(e))},function(e,t,n){var r=n(47),a=n(146),o=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=function(e,t){if(r(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!a(e))||(i.test(e)||!o.test(e)||null!=t&&e in Object(t))}},function(e,t){e.exports=function(e){return e}},function(e,t,n){var r=n(335),a=n(688),o=n(99);e.exports=function(e){return o(e)?r(e,!0):a(e)}},function(e,t,n){var r=n(337)(Object.getPrototypeOf,Object);e.exports=r},function(e,t,n){var r=n(331);e.exports=function(e){var t=new e.constructor(e.byteLength);return new r(t).set(new r(e)),t}},function(e,t,n){var r=n(537)("toUpperCase");e.exports=r},function(e,t,n){var r=n(196);function a(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var r=arguments,a=t?t.apply(this,r):r[0],o=n.cache;if(o.has(a))return o.get(a);var i=e.apply(this,r);return n.cache=o.set(a,i)||o,i};return n.cache=new(a.Cache||r),n}a.Cache=r,e.exports=a},function(e,t,n){"use strict";n.r(t);var r=n(214),a=n(53),o=n(217);t.default=function(e){return{statePlugins:{err:{reducers:Object(r.default)(e),actions:a,selectors:o}}}}},function(e,t,n){"use strict";n.r(t);var r=n(3),a=n.n(r),o=n(22),i=n.n(o),s=n(4),c=n.n(s),u=n(2),l=n.n(u),p=n(12),f=n.n(p),d=n(85),h=n.n(d),m=n(53),v=n(1),g=n(103),y={line:0,level:"error",message:"Unknown error"};t.default=function(){var e;return e={},a()(e,m.NEW_THROWN_ERR,(function(e,t){var n=t.payload,r=i()(y,n,{type:"thrown"});return e.update("errors",(function(e){return(e||Object(v.List)()).push(Object(v.fromJS)(r))})).update("errors",(function(e){return Object(g.default)(e)}))})),a()(e,m.NEW_THROWN_ERR_BATCH,(function(e,t){var n=t.payload;return n=c()(n).call(n,(function(e){return Object(v.fromJS)(i()(y,e,{type:"thrown"}))})),e.update("errors",(function(e){var t;return l()(t=e||Object(v.List)()).call(t,Object(v.fromJS)(n))})).update("errors",(function(e){return Object(g.default)(e)}))})),a()(e,m.NEW_SPEC_ERR,(function(e,t){var n=t.payload,r=Object(v.fromJS)(n);return r=r.set("type","spec"),e.update("errors",(function(e){return(e||Object(v.List)()).push(Object(v.fromJS)(r)).sortBy((function(e){return e.get("line")}))})).update("errors",(function(e){return Object(g.default)(e)}))})),a()(e,m.NEW_SPEC_ERR_BATCH,(function(e,t){var n=t.payload;return n=c()(n).call(n,(function(e){return Object(v.fromJS)(i()(y,e,{type:"spec"}))})),e.update("errors",(function(e){var t;return l()(t=e||Object(v.List)()).call(t,Object(v.fromJS)(n))})).update("errors",(function(e){return Object(g.default)(e)}))})),a()(e,m.NEW_AUTH_ERR,(function(e,t){var n=t.payload,r=Object(v.fromJS)(i()({},n));return r=r.set("type","auth"),e.update("errors",(function(e){return(e||Object(v.List)()).push(Object(v.fromJS)(r))})).update("errors",(function(e){return Object(g.default)(e)}))})),a()(e,m.CLEAR,(function(e,t){var n,r=t.payload;if(!r||!e.get("errors"))return e;var a=f()(n=e.get("errors")).call(n,(function(e){var t;return h()(t=e.keySeq()).call(t,(function(t){var n=e.get(t),a=r[t];return!a||n!==a}))}));return e.merge({errors:a})})),a()(e,m.CLEAR_BY,(function(e,t){var n,r=t.payload;if(!r||"function"!=typeof r)return e;var a=f()(n=e.get("errors")).call(n,(function(e){return r(e)}));return e.merge({errors:a})})),e}},function(e,t,n){"use strict";n.r(t),n.d(t,"transform",(function(){return p}));var r=n(4),a=n.n(r),o=n(14),i=n.n(o),s=n(23),c=n.n(s),u=n(21),l=n.n(u);function p(e){return a()(e).call(e,(function(e){var t,n="is not of a type(s)",r=i()(t=e.get("message")).call(t,n);if(r>-1){var a,o,s=c()(a=e.get("message")).call(a,r+n.length).split(",");return e.set("message",c()(o=e.get("message")).call(o,0,r)+function(e){return l()(e).call(e,(function(e,t,n,r){return n===r.length-1&&r.length>1?e+"or "+t:r[n+1]&&r.length>2?e+t+", ":r[n+1]?e+t+" ":e+t}),"should be a")}(s))}return e}))}},function(e,t,n){"use strict";n.r(t),n.d(t,"transform",(function(){return r}));n(4),n(14),n(41),n(1);function r(e,t){t.jsSpec;return e}},function(e,t,n){"use strict";n.r(t),n.d(t,"allErrors",(function(){return o})),n.d(t,"lastError",(function(){return i}));var r=n(1),a=n(20),o=Object(a.createSelector)((function(e){return e}),(function(e){return e.get("errors",Object(r.List)())})),i=Object(a.createSelector)(o,(function(e){return e.last()}))},function(e,t,n){"use strict";n.r(t);var r=n(219),a=n(86),o=n(220);t.default=function(){return{statePlugins:{layout:{reducers:r.default,actions:a,selectors:o}}}}},function(e,t,n){"use strict";n.r(t);var r,a=n(3),o=n.n(a),i=n(2),s=n.n(i),c=n(1),u=n(86);t.default=(r={},o()(r,u.UPDATE_LAYOUT,(function(e,t){return e.set("layout",t.payload)})),o()(r,u.UPDATE_FILTER,(function(e,t){return e.set("filter",t.payload)})),o()(r,u.SHOW,(function(e,t){var n=t.payload.shown,r=Object(c.fromJS)(t.payload.thing);return e.update("shown",Object(c.fromJS)({}),(function(e){return e.set(r,n)}))})),o()(r,u.UPDATE_MODE,(function(e,t){var n,r=t.payload.thing,a=t.payload.mode;return e.setIn(s()(n=["modes"]).call(n,r),(a||"")+"")})),r)},function(e,t,n){"use strict";n.r(t),n.d(t,"current",(function(){return l})),n.d(t,"currentFilter",(function(){return p})),n.d(t,"isShown",(function(){return f})),n.d(t,"whatMode",(function(){return d})),n.d(t,"showSummary",(function(){return h}));var r=n(15),a=n.n(r),o=n(2),i=n.n(o),s=n(20),c=n(5),u=n(1),l=function(e){return e.get("layout")},p=function(e){return e.get("filter")},f=function(e,t,n){return t=Object(c.w)(t),e.get("shown",Object(u.fromJS)({})).get(Object(u.fromJS)(t),n)},d=function(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return t=Object(c.w)(t),e.getIn(i()(n=["modes"]).call(n,a()(t)),r)},h=Object(s.createSelector)((function(e){return e}),(function(e){return!f(e,"editor")}))},function(e,t,n){"use strict";n.r(t);var r=n(222),a=n(42),o=n(78),i=n(223);t.default=function(){return{statePlugins:{spec:{wrapActions:i,reducers:r.default,actions:a,selectors:o}}}}},function(e,t,n){"use strict";n.r(t);var r,a=n(3),o=n.n(a),i=n(15),s=n.n(i),c=n(2),u=n.n(c),l=n(21),p=n.n(l),f=n(4),d=n.n(f),h=n(22),m=n.n(h),v=n(1),g=n(5),y=n(26),b=n(78),E=n(42);t.default=(r={},o()(r,E.UPDATE_SPEC,(function(e,t){return"string"==typeof t.payload?e.set("spec",t.payload):e})),o()(r,E.UPDATE_URL,(function(e,t){return e.set("url",t.payload+"")})),o()(r,E.UPDATE_JSON,(function(e,t){return e.set("json",Object(g.i)(t.payload))})),o()(r,E.UPDATE_RESOLVED,(function(e,t){return e.setIn(["resolved"],Object(g.i)(t.payload))})),o()(r,E.UPDATE_RESOLVED_SUBTREE,(function(e,t){var n,r=t.payload,a=r.value,o=r.path;return e.setIn(u()(n=["resolvedSubtrees"]).call(n,s()(o)),Object(g.i)(a))})),o()(r,E.UPDATE_PARAM,(function(e,t){var n,r,a=t.payload,o=a.path,i=a.paramName,c=a.paramIn,l=a.param,p=a.value,f=a.isXml,d=l?Object(g.B)(l):u()(n="".concat(c,".")).call(n,i),h=f?"value_xml":"value";return e.setIn(u()(r=["meta","paths"]).call(r,s()(o),["parameters",d,h]),p)})),o()(r,E.UPDATE_EMPTY_PARAM_INCLUSION,(function(e,t){var n,r,a=t.payload,o=a.pathMethod,i=a.paramName,c=a.paramIn,l=a.includeEmptyValue;if(!i||!c)return console.warn("Warning: UPDATE_EMPTY_PARAM_INCLUSION could not generate a paramKey."),e;var p=u()(n="".concat(c,".")).call(n,i);return e.setIn(u()(r=["meta","paths"]).call(r,s()(o),["parameter_inclusions",p]),l)})),o()(r,E.VALIDATE_PARAMS,(function(e,t){var n,r,a=t.payload,o=a.pathMethod,i=a.isOAS3,c=Object(b.specJsonWithResolvedSubtrees)(e).getIn(u()(n=["paths"]).call(n,s()(o))),l=Object(b.parameterValues)(e,o).toJS();return e.updateIn(u()(r=["meta","paths"]).call(r,s()(o),["parameters"]),Object(v.fromJS)({}),(function(t){var n;return p()(n=c.get("parameters",Object(v.List)())).call(n,(function(t,n){var r=Object(g.C)(n,l),a=Object(b.parameterInclusionSettingFor)(e,o,n.get("name"),n.get("in")),s=Object(g.L)(n,r,{bypassRequiredCheck:a,isOAS3:i});return t.setIn([Object(g.B)(n),"errors"],Object(v.fromJS)(s))}),t)}))})),o()(r,E.CLEAR_VALIDATE_PARAMS,(function(e,t){var n,r=t.payload.pathMethod;return e.updateIn(u()(n=["meta","paths"]).call(n,s()(r),["parameters"]),Object(v.fromJS)([]),(function(e){return d()(e).call(e,(function(e){return e.set("errors",Object(v.fromJS)([]))}))}))})),o()(r,E.SET_RESPONSE,(function(e,t){var n,r=t.payload,a=r.res,o=r.path,i=r.method;(n=a.error?m()({error:!0,name:a.err.name,message:a.err.message,statusCode:a.err.statusCode},a.err.response):a).headers=n.headers||{};var s=e.setIn(["responses",o,i],Object(g.i)(n));return y.a.Blob&&a.data instanceof y.a.Blob&&(s=s.setIn(["responses",o,i,"text"],a.data)),s})),o()(r,E.SET_REQUEST,(function(e,t){var n=t.payload,r=n.req,a=n.path,o=n.method;return e.setIn(["requests",a,o],Object(g.i)(r))})),o()(r,E.SET_MUTATED_REQUEST,(function(e,t){var n=t.payload,r=n.req,a=n.path,o=n.method;return e.setIn(["mutatedRequests",a,o],Object(g.i)(r))})),o()(r,E.UPDATE_OPERATION_META_VALUE,(function(e,t){var n,r,a,o,i,c,l=t.payload,p=l.path,f=l.value,d=l.key,h=u()(n=["paths"]).call(n,s()(p)),m=u()(r=["meta","paths"]).call(r,s()(p));return e.getIn(u()(a=["json"]).call(a,s()(h)))||e.getIn(u()(o=["resolved"]).call(o,s()(h)))||e.getIn(u()(i=["resolvedSubtrees"]).call(i,s()(h)))?e.setIn(u()(c=[]).call(c,s()(m),[d]),Object(v.fromJS)(f)):e})),o()(r,E.CLEAR_RESPONSE,(function(e,t){var n=t.payload,r=n.path,a=n.method;return e.deleteIn(["responses",r,a])})),o()(r,E.CLEAR_REQUEST,(function(e,t){var n=t.payload,r=n.path,a=n.method;return e.deleteIn(["requests",r,a])})),o()(r,E.SET_SCHEME,(function(e,t){var n=t.payload,r=n.scheme,a=n.path,o=n.method;return a&&o?e.setIn(["scheme",a,o],r):a||o?void 0:e.setIn(["scheme","_defaultScheme"],r)})),r)},function(e,t,n){"use strict";n.r(t),n.d(t,"updateSpec",(function(){return u})),n.d(t,"updateJsonSpec",(function(){return l})),n.d(t,"executeRequest",(function(){return p})),n.d(t,"validateParams",(function(){return f}));var r=n(17),a=n.n(r),o=n(18),i=n.n(o),s=n(41),c=n.n(s),u=function(e,t){var n=t.specActions;return function(){e.apply(void 0,arguments),n.parseToJson.apply(n,arguments)}},l=function(e,t){var n=t.specActions;return function(){for(var t=arguments.length,r=new Array(t),o=0;o<t;o++)r[o]=arguments[o];e.apply(void 0,r),n.invalidateResolvedSubtreeCache();var s=r[0],u=c()(s,["paths"])||{},l=a()(u);i()(l).call(l,(function(e){c()(u,[e]).$ref&&n.requestResolvedSubtree(["paths",e])})),n.requestResolvedSubtree(["components","securitySchemes"])}},p=function(e,t){var n=t.specActions;return function(t){return n.logRequest(t),e(t)}},f=function(e,t){var n=t.specSelectors;return function(t){return e(t,n.isOAS3())}}},function(e,t,n){"use strict";n.r(t);var r=n(29),a=n.n(r),o=n(134),i=n(5);t.default=function(e){var t=e.getComponents,n=e.getStore,r=e.getSystem,s=o.getComponent,c=o.render,u=o.makeMappedContainer,l=Object(i.v)(a()(s).call(s,null,r,n,t));return{rootInjects:{getComponent:l,makeMappedContainer:Object(i.v)(a()(u).call(u,null,r,n,l,t)),render:a()(c).call(c,null,r,n,s,t)}}}},function(e,t,n){var r=n(96),a=n(209),o=n(76),i=Function.prototype,s=Object.prototype,c=i.toString,u=s.hasOwnProperty,l=c.call(Object);e.exports=function(e){if(!o(e)||"[object Object]"!=r(e))return!1;var t=a(e);if(null===t)return!0;var n=u.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==l}},function(e,t,n){"use strict";n.r(t);var r=n(111);t.default=function(){return{fn:r}}},function(e,t,n){"use strict";n.r(t);var r=n(29),a=n.n(r);t.default=function(e){var t=e.configs,n={debug:0,info:1,log:2,warn:3,error:4},r=function(e){return n[e]||-1},o=t.logLevel,i=r(o);function s(e){for(var t,n=arguments.length,a=new Array(n>1?n-1:0),o=1;o<n;o++)a[o-1]=arguments[o];r(e)>=i&&(t=console)[e].apply(t,a)}return s.warn=a()(s).call(s,null,"warn"),s.error=a()(s).call(s,null,"error"),s.info=a()(s).call(s,null,"info"),s.debug=a()(s).call(s,null,"debug"),{rootInjects:{log:s}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"loaded",(function(){return r}));var r=function(e,t){return function(){e.apply(void 0,arguments);var n=t.getConfigs().withCredentials;void 0!==n&&(t.fn.fetch.withCredentials="string"==typeof n?"true"===n:!!n)}}},function(e,t,n){"use strict";n.r(t),n.d(t,"preauthorizeBasic",(function(){return d})),n.d(t,"preauthorizeApiKey",(function(){return h}));var r=n(3),a=n.n(r),o=n(29),i=n.n(o),s=n(2),c=n.n(s),u=n(230),l=n(73),p=n(231),f=n(232);function d(e,t,n,r){var o,i=e.authActions.authorize,s=e.specSelectors,u=s.specJson,l=(0,s.isOAS3)()?["components","securitySchemes"]:["securityDefinitions"],p=u().getIn(c()(o=[]).call(o,l,[t]));return p?i(a()({},t,{value:{username:n,password:r},schema:p.toJS()})):null}function h(e,t,n){var r,o=e.authActions.authorize,i=e.specSelectors,s=i.specJson,u=(0,i.isOAS3)()?["components","securitySchemes"]:["securityDefinitions"],l=s().getIn(c()(r=[]).call(r,u,[t]));return l?o(a()({},t,{value:n,schema:l.toJS()})):null}t.default=function(){return{afterLoad:function(e){this.rootInjects=this.rootInjects||{},this.rootInjects.initOAuth=e.authActions.configureAuth,this.rootInjects.preauthorizeApiKey=i()(h).call(h,null,e),this.rootInjects.preauthorizeBasic=i()(d).call(d,null,e)},statePlugins:{auth:{reducers:u.default,actions:l,selectors:p},spec:{wrapActions:f}}}}},function(e,t,n){"use strict";n.r(t);var r,a=n(3),o=n.n(a),i=n(16),s=n.n(i),c=n(18),u=n.n(c),l=n(22),p=n.n(l),f=n(1),d=n(5),h=n(73);t.default=(r={},o()(r,h.SHOW_AUTH_POPUP,(function(e,t){var n=t.payload;return e.set("showDefinitions",n)})),o()(r,h.AUTHORIZE,(function(e,t){var n,r=t.payload,a=Object(f.fromJS)(r),o=e.get("authorized")||Object(f.Map)();return u()(n=a.entrySeq()).call(n,(function(t){var n=s()(t,2),r=n[0],a=n[1];if(!Object(d.s)(a.getIn))return e.set("authorized",o);var i=a.getIn(["schema","type"]);if("apiKey"===i||"http"===i)o=o.set(r,a);else if("basic"===i){var c=a.getIn(["value","username"]),u=a.getIn(["value","password"]);o=(o=o.setIn([r,"value"],{username:c,header:"Basic "+Object(d.a)(c+":"+u)})).setIn([r,"schema"],a.get("schema"))}})),e.set("authorized",o)})),o()(r,h.AUTHORIZE_OAUTH2,(function(e,t){var n,r=t.payload,a=r.auth,o=r.token;a.token=p()({},o),n=Object(f.fromJS)(a);var i=e.get("authorized")||Object(f.Map)();return i=i.set(n.get("name"),n),e.set("authorized",i)})),o()(r,h.LOGOUT,(function(e,t){var n=t.payload,r=e.get("authorized").withMutations((function(e){u()(n).call(n,(function(t){e.delete(t)}))}));return e.set("authorized",r)})),o()(r,h.CONFIGURE_AUTH,(function(e,t){var n=t.payload;return e.set("configs",n)})),o()(r,h.RESTORE_AUTHORIZATION,(function(e,t){var n=t.payload;return e.set("authorized",Object(f.fromJS)(n.authorized))})),r)},function(e,t,n){"use strict";n.r(t),n.d(t,"shownDefinitions",(function(){return E})),n.d(t,"definitionsToAuthorize",(function(){return x})),n.d(t,"getDefinitionsByNames",(function(){return S})),n.d(t,"definitionsForRequirements",(function(){return w})),n.d(t,"authorized",(function(){return j})),n.d(t,"isAuthorized",(function(){return O})),n.d(t,"getConfigs",(function(){return C}));var r=n(16),a=n.n(r),o=n(18),i=n.n(o),s=n(12),c=n.n(s),u=n(33),l=n.n(u),p=n(14),f=n.n(p),d=n(4),h=n.n(d),m=n(17),v=n.n(m),g=n(20),y=n(1),b=function(e){return e},E=Object(g.createSelector)(b,(function(e){return e.get("showDefinitions")})),x=Object(g.createSelector)(b,(function(){return function(e){var t,n=e.specSelectors.securityDefinitions()||Object(y.Map)({}),r=Object(y.List)();return i()(t=n.entrySeq()).call(t,(function(e){var t=a()(e,2),n=t[0],o=t[1],i=Object(y.Map)();i=i.set(n,o),r=r.push(i)})),r}})),S=function(e,t){return function(e){var n,r=e.specSelectors;console.warn("WARNING: getDefinitionsByNames is deprecated and will be removed in the next major version.");var o=r.securityDefinitions(),s=Object(y.List)();return i()(n=t.valueSeq()).call(n,(function(e){var t,n=Object(y.Map)();i()(t=e.entrySeq()).call(t,(function(e){var t,r,s=a()(e,2),c=s[0],u=s[1],l=o.get(c);"oauth2"===l.get("type")&&u.size&&(t=l.get("scopes"),i()(r=t.keySeq()).call(r,(function(e){u.contains(e)||(t=t.delete(e))})),l=l.set("allowedScopes",t));n=n.set(c,l)})),s=s.push(n)})),s}},w=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Object(y.List)();return function(e){var n=e.authSelectors.definitionsToAuthorize()||Object(y.List)();return c()(n).call(n,(function(e){return l()(t).call(t,(function(t){return t.get(e.keySeq().first())}))}))}},j=Object(g.createSelector)(b,(function(e){return e.get("authorized")||Object(y.Map)()})),O=function(e,t){return function(e){var n,r=e.authSelectors.authorized();return y.List.isList(t)?!!c()(n=t.toJS()).call(n,(function(e){var t,n;return-1===f()(t=h()(n=v()(e)).call(n,(function(e){return!!r.get(e)}))).call(t,!1)})).length:null}},C=Object(g.createSelector)(b,(function(e){return e.get("configs")}))},function(e,t,n){"use strict";n.r(t),n.d(t,"execute",(function(){return o}));var r=n(25),a=n.n(r),o=function(e,t){var n=t.authSelectors,r=t.specSelectors;return function(t){var o=t.path,i=t.method,s=t.operation,c=t.extras,u={authorized:n.authorized()&&n.authorized().toJS(),definitions:r.securityDefinitions()&&r.securityDefinitions().toJS(),specSecurity:r.security()&&r.security().toJS()};return e(a()({path:o,method:i,operation:s,securities:u},c))}}},function(e,t,n){"use strict";n.r(t);var r=n(5);t.default=function(){return{fn:{shallowEqualKeys:r.H}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return v}));var r=n(22),a=n.n(r),o=n(80),i=n.n(o),s=n(2),c=n.n(s),u=n(14),l=n.n(u),p=n(30),f=n.n(p),d=n(20),h=n(1),m=n(26);function v(e){var t=e.fn;return{statePlugins:{spec:{actions:{download:function(e){return function(n){var r=n.errActions,o=n.specSelectors,s=n.specActions,u=n.getConfigs,l=t.fetch,p=u();function f(t){if(t instanceof Error||t.status>=400)return s.updateLoadingStatus("failed"),r.newThrownErr(a()(new Error((t.message||t.statusText)+" "+e),{source:"fetch"})),void(!t.status&&t instanceof Error&&function(){try{var t;if("URL"in m.a?t=new i.a(e):(t=document.createElement("a")).href=e,"https:"!==t.protocol&&"https:"===m.a.location.protocol){var n=a()(new Error("Possible mixed-content issue? The page was loaded over https:// but a ".concat(t.protocol,"// URL was specified. Check that you are not attempting to load mixed content.")),{source:"fetch"});return void r.newThrownErr(n)}if(t.origin!==m.a.location.origin){var o,s=a()(new Error(c()(o="Possible cross-origin (CORS) issue? The URL origin (".concat(t.origin,") does not match the page (")).call(o,m.a.location.origin,"). Check the server returns the correct 'Access-Control-Allow-*' headers.")),{source:"fetch"});r.newThrownErr(s)}}catch(e){return}}());s.updateLoadingStatus("success"),s.updateSpec(t.text),o.url()!==e&&s.updateUrl(e)}e=e||o.url(),s.updateLoadingStatus("loading"),r.clear({source:"fetch"}),l({url:e,loadSpec:!0,requestInterceptor:p.requestInterceptor||function(e){return e},responseInterceptor:p.responseInterceptor||function(e){return e},credentials:"same-origin",headers:{Accept:"application/json,*/*"}}).then(f,f)}},updateLoadingStatus:function(e){var t,n=[null,"loading","failed","success","failedConfig"];-1===l()(n).call(n,e)&&console.error(c()(t="Error: ".concat(e," is not one of ")).call(t,f()(n)));return{type:"spec_update_loading_status",payload:e}}},reducers:{spec_update_loading_status:function(e,t){return"string"==typeof t.payload?e.set("loadingStatus",t.payload):e}},selectors:{loadingStatus:Object(d.createSelector)((function(e){return e||Object(h.Map)()}),(function(e){return e.get("loadingStatus")||null}))}}}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"downloadConfig",(function(){return a})),n.d(t,"getConfigByUrl",(function(){return o}));var r=n(131),a=function(e){return function(t){return(0,t.fn.fetch)(e)}},o=function(e,t){return function(n){var a=n.specActions;if(e)return a.downloadConfig(e).then(o,o);function o(n){n instanceof Error||n.status>=400?(a.updateLoadingStatus("failedConfig"),a.updateLoadingStatus("failedConfig"),a.updateUrl(""),console.error(n.statusText+" "+e.url),t(null)):t(Object(r.parseYamlConfig)(n.text))}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"get",(function(){return o}));var r=n(13),a=n.n(r),o=function(e,t){return e.getIn(a()(t)?t:[t])}},function(e,t,n){"use strict";n.r(t);var r,a=n(3),o=n.n(a),i=n(1),s=n(112);t.default=(r={},o()(r,s.UPDATE_CONFIGS,(function(e,t){return e.merge(Object(i.fromJS)(t.payload))})),o()(r,s.TOGGLE_CONFIGS,(function(e,t){var n=t.payload,r=e.get(n);return e.set(n,!r)})),r)},function(e,t,n){"use strict";n.r(t);var r=n(239),a=n(240),o=n(241);t.default=function(){return[r.default,{statePlugins:{configs:{wrapActions:{loaded:function(e,t){return function(){e.apply(void 0,arguments);var n=decodeURIComponent(window.location.hash);t.layoutActions.parseDeepLinkHash(n)}}}}},wrapComponents:{operation:a.default,OperationTag:o.default}}]}},function(e,t,n){"use strict";n.r(t),n.d(t,"show",(function(){return C})),n.d(t,"scrollTo",(function(){return _})),n.d(t,"parseDeepLinkHash",(function(){return A})),n.d(t,"readyToScroll",(function(){return k})),n.d(t,"scrollToElement",(function(){return I})),n.d(t,"clearScrollTo",(function(){return P}));var r,a=n(3),o=n.n(a),i=n(16),s=n.n(i),c=n(13),u=n.n(c),l=n(2),p=n.n(l),f=n(23),d=n.n(f),h=n(4),m=n.n(h),v=n(14),g=n.n(v),y=n(135),b=n(397),E=n.n(b),x=n(5),S=n(1),w=n.n(S),j="layout_scroll_to",O="layout_clear_scroll",C=function(e,t){var n=t.getConfigs,r=t.layoutSelectors;return function(){for(var t=arguments.length,a=new Array(t),o=0;o<t;o++)a[o]=arguments[o];if(e.apply(void 0,a),n().deepLinking)try{var i=a[0],c=a[1];i=u()(i)?i:[i];var l=r.urlHashArrayFromIsShownKey(i);if(!l.length)return;var f,d=s()(l,2),h=d[0],m=d[1];if(!c)return Object(y.setHash)("/");if(2===l.length)Object(y.setHash)(Object(x.d)(p()(f="/".concat(encodeURIComponent(h),"/")).call(f,encodeURIComponent(m))));else 1===l.length&&Object(y.setHash)(Object(x.d)("/".concat(encodeURIComponent(h))))}catch(e){console.error(e)}}},_=function(e){return{type:j,payload:u()(e)?e:[e]}},A=function(e){return function(t){var n=t.layoutActions,r=t.layoutSelectors;if((0,t.getConfigs)().deepLinking&&e){var a,o=d()(e).call(e,1);"!"===o[0]&&(o=d()(o).call(o,1)),"/"===o[0]&&(o=d()(o).call(o,1));var i=m()(a=o.split("/")).call(a,(function(e){return e||""})),c=r.isShownKeyFromUrlHashArray(i),u=s()(c,3),l=u[0],p=u[1],f=void 0===p?"":p,h=u[2],v=void 0===h?"":h;if("operations"===l){var y=r.isShownKeyFromUrlHashArray([f]);g()(f).call(f,"_")>-1&&(console.warn("Warning: escaping deep link whitespace with `_` will be unsupported in v4.0, use `%20` instead."),n.show(m()(y).call(y,(function(e){return e.replace(/_/g," ")})),!0)),n.show(y,!0)}(g()(f).call(f,"_")>-1||g()(v).call(v,"_")>-1)&&(console.warn("Warning: escaping deep link whitespace with `_` will be unsupported in v4.0, use `%20` instead."),n.show(m()(c).call(c,(function(e){return e.replace(/_/g," ")})),!0)),n.show(c,!0),n.scrollTo(c)}}},k=function(e,t){return function(n){var r=n.layoutSelectors.getScrollToKey();w.a.is(r,Object(S.fromJS)(e))&&(n.layoutActions.scrollToElement(t),n.layoutActions.clearScrollTo())}},I=function(e,t){return function(n){try{t=t||n.fn.getScrollParent(e),E.a.createScroller(t).to(e)}catch(e){console.error(e)}}},P=function(){return{type:O}};t.default={fn:{getScrollParent:function(e,t){var n=document.documentElement,r=getComputedStyle(e),a="absolute"===r.position,o=t?/(auto|scroll|hidden)/:/(auto|scroll)/;if("fixed"===r.position)return n;for(var i=e;i=i.parentElement;)if(r=getComputedStyle(i),(!a||"static"!==r.position)&&o.test(r.overflow+r.overflowY+r.overflowX))return i;return n}},statePlugins:{layout:{actions:{scrollToElement:I,scrollTo:_,clearScrollTo:P,readyToScroll:k,parseDeepLinkHash:A},selectors:{getScrollToKey:function(e){return e.get("scrollToKey")},isShownKeyFromUrlHashArray:function(e,t){var n=s()(t,2),r=n[0],a=n[1];return a?["operations",r,a]:r?["operations-tag",r]:[]},urlHashArrayFromIsShownKey:function(e,t){var n=s()(t,3),r=n[0],a=n[1],o=n[2];return"operations"==r?[a,o]:"operations-tag"==r?[a]:[]}},reducers:(r={},o()(r,j,(function(e,t){return e.set("scrollToKey",w.a.fromJS(t.payload))})),o()(r,O,(function(e){return e.delete("scrollToKey")})),r),wrapActions:{show:C}}}}},function(e,t,n){"use strict";n.r(t);var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(10),c=n.n(s),u=n(8),l=n.n(u),p=n(9),f=n.n(p),d=n(3),h=n.n(d),m=n(2),v=n.n(m),g=n(0),y=n.n(g);n(27);t.default=function(e,t){return function(n){l()(o,n);var r=f()(o);function o(){var e,n;a()(this,o);for(var i=arguments.length,s=new Array(i),u=0;u<i;u++)s[u]=arguments[u];return n=r.call.apply(r,v()(e=[this]).call(e,s)),h()(c()(n),"onLoad",(function(e){var r=n.props.operation,a=r.toObject(),o=a.tag,i=a.operationId,s=r.toObject().isShownKey;s=s||["operations",o,i],t.layoutActions.readyToScroll(s,e)})),n}return i()(o,[{key:"render",value:function(){return y.a.createElement("span",{ref:this.onLoad},y.a.createElement(e,this.props))}}]),o}(y.a.Component)}},function(e,t,n){"use strict";n.r(t);var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(10),c=n.n(s),u=n(8),l=n.n(u),p=n(9),f=n.n(p),d=n(3),h=n.n(d),m=n(2),v=n.n(m),g=n(0),y=n.n(g);n(11);t.default=function(e,t){return function(n){l()(o,n);var r=f()(o);function o(){var e,n;a()(this,o);for(var i=arguments.length,s=new Array(i),u=0;u<i;u++)s[u]=arguments[u];return n=r.call.apply(r,v()(e=[this]).call(e,s)),h()(c()(n),"onLoad",(function(e){var r=["operations-tag",n.props.tag];t.layoutActions.readyToScroll(r,e)})),n}return i()(o,[{key:"render",value:function(){return y.a.createElement("span",{ref:this.onLoad},y.a.createElement(e,this.props))}}]),o}(y.a.Component)}},function(e,t,n){"use strict";n.r(t);var r=n(243);t.default=function(){return{fn:{opsFilter:r.default}}}},function(e,t,n){"use strict";n.r(t);var r=n(12),a=n.n(r),o=n(14),i=n.n(o);t.default=function(e,t){return a()(e).call(e,(function(e,n){return-1!==i()(n).call(n,t)}))}},function(e,t,n){"use strict";n.r(t);var r=n(169),a=n.n(r),o=!1;t.default=function(){return{statePlugins:{spec:{wrapActions:{updateSpec:function(e){return function(){return o=!0,e.apply(void 0,arguments)}},updateJsonSpec:function(e,t){return function(){var n=t.getConfigs().onComplete;return o&&"function"==typeof n&&(a()(n,0),o=!1),e.apply(void 0,arguments)}}}}}}}},function(e,t,n){"use strict";n.r(t);var r=n(246),a=n(247),o=n(248),i=n(249),s=n(257),c=n(50),u=n(264),l=n(265);t.default=function(){return{components:i.default,wrapComponents:s.default,statePlugins:{spec:{wrapSelectors:r,selectors:o},auth:{wrapSelectors:a},oas3:{actions:c,reducers:l.default,selectors:u}}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"definitions",(function(){return d})),n.d(t,"hasHost",(function(){return h})),n.d(t,"securityDefinitions",(function(){return m})),n.d(t,"host",(function(){return v})),n.d(t,"basePath",(function(){return g})),n.d(t,"consumes",(function(){return y})),n.d(t,"produces",(function(){return b})),n.d(t,"schemes",(function(){return E})),n.d(t,"servers",(function(){return x})),n.d(t,"isOAS3",(function(){return S})),n.d(t,"isSwagger2",(function(){return w}));var r=n(20),a=n(78),o=n(1),i=n(32);function s(e){return function(t,n){return function(){var r=n.getSystem().specSelectors.specJson();return Object(i.isOAS3)(r)?e.apply(void 0,arguments):t.apply(void 0,arguments)}}}var c=function(e){return e||Object(o.Map)()},u=s(Object(r.createSelector)((function(){return null}))),l=Object(r.createSelector)(c,(function(e){return e.get("json",Object(o.Map)())})),p=Object(r.createSelector)(c,(function(e){return e.get("resolved",Object(o.Map)())})),f=function(e){var t=p(e);return t.count()<1&&(t=l(e)),t},d=s(Object(r.createSelector)(f,(function(e){var t=e.getIn(["components","schemas"]);return o.Map.isMap(t)?t:Object(o.Map)()}))),h=s((function(e){return f(e).hasIn(["servers",0])})),m=s(Object(r.createSelector)(a.specJsonWithResolvedSubtrees,(function(e){return e.getIn(["components","securitySchemes"])||null}))),v=u,g=u,y=u,b=u,E=u,x=s(Object(r.createSelector)(f,(function(e){return e.getIn(["servers"])||Object(o.Map)()}))),S=function(e,t){return function(){var e=t.getSystem().specSelectors.specJson();return Object(i.isOAS3)(o.Map.isMap(e)?e:Object(o.Map)())}},w=function(e,t){return function(){var e=t.getSystem().specSelectors.specJson();return Object(i.isSwagger2)(o.Map.isMap(e)?e:Object(o.Map)())}}},function(e,t,n){"use strict";n.r(t),n.d(t,"definitionsToAuthorize",(function(){return b}));var r=n(3),a=n.n(r),o=n(16),i=n.n(o),s=n(2),c=n.n(s),u=n(18),l=n.n(u),p=n(12),f=n.n(p),d=n(21),h=n.n(d),m=n(20),v=n(1),g=n(32);var y,b=(y=Object(m.createSelector)((function(e){return e}),(function(e){return e.specSelectors.securityDefinitions()}),(function(e,t){var n,r=Object(v.List)();return t?(l()(n=t.entrySeq()).call(n,(function(e){var t,n=i()(e,2),o=n[0],s=n[1],c=s.get("type");if("oauth2"===c&&l()(t=s.get("flows").entrySeq()).call(t,(function(e){var t=i()(e,2),n=t[0],c=t[1],u=Object(v.fromJS)({flow:n,authorizationUrl:c.get("authorizationUrl"),tokenUrl:c.get("tokenUrl"),scopes:c.get("scopes"),type:s.get("type")});r=r.push(new v.Map(a()({},o,f()(u).call(u,(function(e){return void 0!==e})))))})),"http"!==c&&"apiKey"!==c||(r=r.push(new v.Map(a()({},o,s)))),"openIdConnect"===c&&s.get("openIdConnectData")){var u=s.get("openIdConnectData"),p=u.get("grant_types_supported")||["authorization_code","implicit"];l()(p).call(p,(function(e){var t,n=u.get("scopes_supported")&&h()(t=u.get("scopes_supported")).call(t,(function(e,t){return e.set(t,"")}),new v.Map),i=Object(v.fromJS)({flow:e,authorizationUrl:u.get("authorization_endpoint"),tokenUrl:u.get("token_endpoint"),scopes:n,type:"oauth2",openIdConnectUrl:s.get("openIdConnectUrl")});r=r.push(new v.Map(a()({},o,f()(i).call(i,(function(e){return void 0!==e})))))}))}})),r):r})),function(e,t){return function(){for(var n=t.getSystem().specSelectors.specJson(),r=arguments.length,a=new Array(r),o=0;o<r;o++)a[o]=arguments[o];if(Object(g.isOAS3)(n)){var i,s=t.getState().getIn(["spec","resolvedSubtrees","components","securitySchemes"]);return y.apply(void 0,c()(i=[t,s]).call(i,a))}return e.apply(void 0,a)}})},function(e,t,n){"use strict";n.r(t),n.d(t,"servers",(function(){return l})),n.d(t,"isSwagger2",(function(){return p}));var r=n(20),a=n(1),o=n(32);var i,s=function(e){return e||Object(a.Map)()},c=Object(r.createSelector)(s,(function(e){return e.get("json",Object(a.Map)())})),u=Object(r.createSelector)(s,(function(e){return e.get("resolved",Object(a.Map)())})),l=(i=Object(r.createSelector)((function(e){var t=u(e);return t.count()<1&&(t=c(e)),t}),(function(e){return e.getIn(["servers"])||Object(a.Map)()})),function(){return function(e){var t=e.getSystem().specSelectors.specJson();if(Object(o.isOAS3)(t)){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return i.apply(void 0,r)}return null}}),p=function(e,t){return function(){var e=t.getSystem().specSelectors.specJson();return Object(o.isSwagger2)(e)}}},function(e,t,n){"use strict";n.r(t);var r=n(250),a=n(132),o=n(251),i=n(252),s=n(253),c=n(254),u=n(255),l=n(256);t.default={Callbacks:r.default,HttpAuth:u.default,RequestBody:a.default,Servers:i.default,ServersContainer:s.default,RequestBodyEditor:c.default,OperationServers:l.default,operationLink:o.default}},function(e,t,n){"use strict";n.r(t);var r=n(28),a=n.n(r),o=n(16),i=n.n(o),s=n(4),c=n.n(s),u=n(0),l=n.n(u),p=(n(11),n(27),n(1));t.default=function(e){var t,n=e.callbacks,r=e.getComponent,o=e.specPath,s=r("OperationContainer",!0);if(!n)return l.a.createElement("span",null,"No callbacks");var u=c()(t=n.entrySeq()).call(t,(function(t){var n,r=i()(t,2),u=r[0],f=r[1];return l.a.createElement("div",{key:u},l.a.createElement("h2",null,u),c()(n=f.entrySeq()).call(n,(function(t){var n,r=i()(t,2),f=r[0],d=r[1];return"$$ref"===f?null:l.a.createElement("div",{key:f},c()(n=d.entrySeq()).call(n,(function(t){var n=i()(t,2),r=n[0],c=n[1];if("$$ref"===r)return null;var d=Object(p.fromJS)({operation:c});return l.a.createElement(s,a()({},e,{op:d,key:r,tag:"",method:r,path:f,specPath:o.push(u,f,r),allowTryItOut:!1}))})))})))}));return l.a.createElement("div",null,u)}},function(e,t,n){"use strict";n.r(t);var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(8),c=n.n(s),u=n(9),l=n.n(u),p=n(30),f=n.n(p),d=n(4),h=n.n(d),m=n(0),v=n.n(m),g=(n(11),n(27),function(e){c()(n,e);var t=l()(n);function n(){return a()(this,n),t.apply(this,arguments)}return i()(n,[{key:"render",value:function(){var e=this.props,t=e.link,n=e.name,r=(0,e.getComponent)("Markdown",!0),a=t.get("operationId")||t.get("operationRef"),o=t.get("parameters")&&t.get("parameters").toJS(),i=t.get("description");return v.a.createElement("div",{className:"operation-link"},v.a.createElement("div",{className:"description"},v.a.createElement("b",null,v.a.createElement("code",null,n)),i?v.a.createElement(r,{source:i}):null),v.a.createElement("pre",null,"Operation `",a,"`",v.a.createElement("br",null),v.a.createElement("br",null),"Parameters ",function(e,t){var n;if("string"!=typeof t)return"";return h()(n=t.split("\n")).call(n,(function(t,n){return n>0?Array(e+1).join(" ")+t:t})).join("\n")}(0,f()(o,null,2))||"{}",v.a.createElement("br",null)))}}]),n}(m.Component));t.default=g},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return C}));var r=n(16),a=n.n(r),o=n(6),i=n.n(o),s=n(7),c=n.n(s),u=n(10),l=n.n(u),p=n(8),f=n.n(p),d=n(9),h=n.n(d),m=n(3),v=n.n(m),g=n(2),y=n.n(g),b=n(56),E=n.n(b),x=n(4),S=n.n(x),w=n(0),j=n.n(w),O=n(1),C=(n(11),n(27),function(e){f()(n,e);var t=h()(n);function n(){var e,r;i()(this,n);for(var a=arguments.length,o=new Array(a),s=0;s<a;s++)o[s]=arguments[s];return r=t.call.apply(t,y()(e=[this]).call(e,o)),v()(l()(r),"onServerChange",(function(e){r.setServer(e.target.value)})),v()(l()(r),"onServerVariableValueChange",(function(e){var t=r.props,n=t.setServerVariableValue,a=t.currentServer,o=e.target.getAttribute("data-variable"),i=e.target.value;"function"==typeof n&&n({server:a,key:o,val:i})})),v()(l()(r),"setServer",(function(e){(0,r.props.setSelectedServer)(e)})),r}return c()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.servers;e.currentServer||this.setServer(t.first().get("url"))}},{key:"componentWillReceiveProps",value:function(e){var t=e.servers,n=e.setServerVariableValue,r=e.getServerVariable;if(this.props.currentServer!==e.currentServer||this.props.servers!==e.servers){var a=E()(t).call(t,(function(t){return t.get("url")===e.currentServer}));if(!a)return this.setServer(t.first().get("url"));var o=a.get("variables")||Object(O.OrderedMap)();S()(o).call(o,(function(t,a){r(e.currentServer,a)||n({server:e.currentServer,key:a,val:t.get("default")||""})}))}}},{key:"render",value:function(){var e,t,n=this,r=this.props,o=r.servers,i=r.currentServer,s=r.getServerVariable,c=r.getEffectiveServerValue,u=(E()(o).call(o,(function(e){return e.get("url")===i}))||Object(O.OrderedMap)()).get("variables")||Object(O.OrderedMap)(),l=0!==u.size;return j.a.createElement("div",{className:"servers"},j.a.createElement("label",{htmlFor:"servers"},j.a.createElement("select",{onChange:this.onServerChange,value:i},S()(e=o.valueSeq()).call(e,(function(e){return j.a.createElement("option",{value:e.get("url"),key:e.get("url")},e.get("url"),e.get("description")&&" - ".concat(e.get("description")))})).toArray())),l?j.a.createElement("div",null,j.a.createElement("div",{className:"computed-url"},"Computed URL:",j.a.createElement("code",null,c(i))),j.a.createElement("h4",null,"Server variables"),j.a.createElement("table",null,j.a.createElement("tbody",null,S()(t=u.entrySeq()).call(t,(function(e){var t,r=a()(e,2),o=r[0],c=r[1];return j.a.createElement("tr",{key:o},j.a.createElement("td",null,o),j.a.createElement("td",null,c.get("enum")?j.a.createElement("select",{"data-variable":o,onChange:n.onServerVariableValueChange},S()(t=c.get("enum")).call(t,(function(e){return j.a.createElement("option",{selected:e===s(i,o),key:e,value:e},e)}))):j.a.createElement("input",{type:"text",value:s(i,o)||"",onChange:n.onServerVariableValueChange,"data-variable":o})))}))))):null)}}]),n}(j.a.Component))},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return d}));var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(8),c=n.n(s),u=n(9),l=n.n(u),p=n(0),f=n.n(p),d=(n(11),function(e){c()(n,e);var t=l()(n);function n(){return a()(this,n),t.apply(this,arguments)}return i()(n,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,n=e.oas3Selectors,r=e.oas3Actions,a=e.getComponent,o=t.servers(),i=a("Servers");return o&&o.size?f.a.createElement("div",null,f.a.createElement("span",{className:"servers-title"},"Servers"),f.a.createElement(i,{servers:o,currentServer:n.selectedServer(),setSelectedServer:r.setSelectedServer,setServerVariableValue:r.setServerVariableValue,getServerVariable:n.serverVariableValue,getEffectiveServerValue:n.serverEffectiveValue})):null}}]),n}(f.a.Component))},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return x}));var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(10),c=n.n(s),u=n(8),l=n.n(u),p=n(9),f=n.n(p),d=n(3),h=n.n(d),m=n(0),v=n.n(m),g=(n(11),n(54)),y=n.n(g),b=n(5),E=Function.prototype,x=function(e){l()(n,e);var t=f()(n);function n(e,r){var o;return a()(this,n),o=t.call(this,e,r),h()(c()(o),"applyDefaultValue",(function(e){var t=e||o.props,n=t.onChange,r=t.defaultValue;return o.setState({value:r}),n(r)})),h()(c()(o),"onChange",(function(e){o.props.onChange(Object(b.J)(e))})),h()(c()(o),"onDomChange",(function(e){var t=e.target.value;o.setState({value:t},(function(){return o.onChange(t)}))})),o.state={value:Object(b.J)(e.value)||e.defaultValue},e.onChange(e.value),o}return i()(n,[{key:"componentWillReceiveProps",value:function(e){this.props.value!==e.value&&e.value!==this.state.value&&this.setState({value:Object(b.J)(e.value)}),!e.value&&e.defaultValue&&this.state.value&&this.applyDefaultValue(e)}},{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.errors,r=this.state.value,a=n.size>0,o=t("TextArea");return v.a.createElement("div",{className:"body-param"},v.a.createElement(o,{className:y()("body-param__text",{invalid:a}),title:n.size?n.join(", "):"",value:r,onChange:this.onDomChange}))}}]),n}(m.PureComponent);h()(x,"defaultProps",{onChange:E,userHasEditedBody:!1})},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return w}));var r=n(6),a=n.n(r),o=n(7),i=n.n(o),s=n(10),c=n.n(s),u=n(8),l=n.n(u),p=n(9),f=n.n(p),d=n(3),h=n.n(d),m=n(22),v=n.n(m),g=n(12),y=n.n(g),b=n(4),E=n.n(b),x=n(0),S=n.n(x),w=(n(11),function(e){l()(n,e);var t=f()(n);function n(e,r){var o;a()(this,n),o=t.call(this,e,r),h()(c()(o),"onChange",(function(e){var t=o.props.onChange,n=e.target,r=n.value,a=n.name,i=v()({},o.state.value);a?i[a]=r:i=r,o.setState({value:i},(function(){return t(o.state)}))}));var i=o.props,s=i.name,u=i.schema,l=o.getValue();return o.state={name:s,schema:u,value:l},o}return i()(n,[{key:"getValue",value:function(){var e=this.props,t=e.name,n=e.authorized;return n&&n.getIn([t,"value"])}},{key:"render",value:function(){var e,t,n=this.props,r=n.schema,a=n.getComponent,o=n.errSelectors,i=n.name,s=a("Input"),c=a("Row"),u=a("Col"),l=a("authError"),p=a("Markdown",!0),f=a("JumpToPath",!0),d=(r.get("scheme")||"").toLowerCase(),h=this.getValue(),m=y()(e=o.allErrors()).call(e,(function(e){return e.get("authId")===i}));if("basic"===d){var v,g=h?h.get("username"):null;return S.a.createElement("div",null,S.a.createElement("h4",null,S.a.createElement("code",null,i||r.get("name"))," (http, Basic)",S.a.createElement(f,{path:["securityDefinitions",i]})),g&&S.a.createElement("h6",null,"Authorized"),S.a.createElement(c,null,S.a.createElement(p,{source:r.get("description")})),S.a.createElement(c,null,S.a.createElement("label",null,"Username:"),g?S.a.createElement("code",null," ",g," "):S.a.createElement(u,null,S.a.createElement(s,{type:"text",required:"required",name:"username",onChange:this.onChange,autoFocus:!0}))),S.a.createElement(c,null,S.a.createElement("label",null,"Password:"),g?S.a.createElement("code",null," ****** "):S.a.createElement(u,null,S.a.createElement(s,{autoComplete:"new-password",name:"password",type:"password",onChange:this.onChange}))),E()(v=m.valueSeq()).call(v,(function(e,t){return S.a.createElement(l,{error:e,key:t})})))}return"bearer"===d?S.a.createElement("div",null,S.a.createElement("h4",null,S.a.createElement("code",null,i||r.get("name"))," (http, Bearer)",S.a.createElement(f,{path:["securityDefinitions",i]})),h&&S.a.createElement("h6",null,"Authorized"),S.a.createElement(c,null,S.a.createElement(p,{source:r.get("description")})),S.a.createElement(c,null,S.a.createElement("label",null,"Value:"),h?S.a.createElement("code",null," ****** "):S.a.createElement(u,null,S.a.createElement(s,{type:"text",onChange:this.onChange,autoFocus:!0}))),E()(t=m.valueSeq()).call(t,(function(e,t){return S.a.createElement(l,{error:e,key:t})}))):S.a.createElement("div",null,S.a.createElement("em",null,S.a.createElement("b",null,i)," HTTP authentication: unsupported scheme ","'".concat(d,"'")))}}]),n}(S.a.Component))},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return x}));var r=n(25),a=n.n(r),o=n(6),i=n.n(o),s=n(7),c=n.n(s),u=n(10),l=n.n(u),p=n(8),f=n.n(p),d=n(9),h=n.n(d),m=n(3),v=n.n(m),g=n(2),y=n.n(g),b=n(0),E=n.n(b),x=(n(11),n(27),function(e){f()(n,e);var t=h()(n);function n(){var e,r;i()(this,n);for(var o=arguments.length,s=new Array(o),c=0;c<o;c++)s[c]=arguments[c];return r=t.call.apply(t,y()(e=[this]).call(e,s)),v()(l()(r),"setSelectedServer",(function(e){var t,n=r.props,a=n.path,o=n.method;return r.forceUpdate(),r.props.setSelectedServer(e,y()(t="".concat(a,":")).call(t,o))})),v()(l()(r),"setServerVariableValue",(function(e){var t,n=r.props,o=n.path,i=n.method;return r.forceUpdate(),r.props.setServerVariableValue(a()(a()({},e),{},{namespace:y()(t="".concat(o,":")).call(t,i)}))})),v()(l()(r),"getSelectedServer",(function(){var e,t=r.props,n=t.path,a=t.method;return r.props.getSelectedServer(y()(e="".concat(n,":")).call(e,a))})),v()(l()(r),"getServerVariable",(function(e,t){var n,a=r.props,o=a.path,i=a.method;return r.props.getServerVariable({namespace:y()(n="".concat(o,":")).call(n,i),server:e},t)})),v()(l()(r),"getEffectiveServerValue",(function(e){var t,n=r.props,a=n.path,o=n.method;return r.props.getEffectiveServerValue({server:e,namespace:y()(t="".concat(a,":")).call(t,o)})})),r}return c()(n,[{key:"render",value:function(){var e=this.props,t=e.operationServers,n=e.pathServers,r=e.getComponent;if(!t&&!n)return null;var a=r("Servers"),o=t||n,i=t?"operation":"path";return E.a.createElement("div",{className:"opblock-section operation-servers"},E.a.createElement("div",{className:"opblock-section-header"},E.a.createElement("div",{className:"tab-header"},E.a.createElement("h4",{className:"opblock-title"},"Servers"))),E.a.createElement("div",{className:"opblock-description-wrapper"},E.a.createElement("h4",{className:"message"},"These ",i,"-level options override the global server options."),E.a.createElement(a,{servers:o,currentServer:this.getSelectedServer(),setSelectedServer:this.setSelectedServer,setServerVariableValue:this.setServerVariableValue,getServerVariable:this.getServerVariable,getEffectiveServerValue:this.getEffectiveServerValue})))}}]),n}(E.a.Component))},function(e,t,n){"use strict";n.r(t);var r=n(258),a=n(259),o=n(260),i=n(261),s=n(262),c=n(263);t.default={Markdown:r.default,AuthItem:a.default,JsonSchema_string:c.default,VersionStamp:o.default,model:s.default,onlineValidatorBadge:i.default}},function(e,t,n){"use strict";n.r(t),n.d(t,"Markdown",(function(){return d}));var r=n(84),a=n.n(r),o=n(0),i=n.n(o),s=(n(11),n(54)),c=n.n(s),u=n(173),l=n(32),p=n(174),f=new u.Remarkable("commonmark");f.block.ruler.enable(["table"]),f.set({linkTarget:"_blank"});var d=function(e){var t=e.source,n=e.className,r=void 0===n?"":n,o=e.getConfigs;if("string"!=typeof t)return null;if(t){var s,u=o().useUnsafeMarkdown,l=f.render(t),d=Object(p.b)(l,{useUnsafeMarkdown:u});return"string"==typeof d&&(s=a()(d).call(d)),i.a.createElement("div",{dangerouslySetInnerHTML:{__html:s},className:c()(r,"renderedMarkdown")})}return null};d.defaultProps={getConfigs:function(){return{useUnsafeMarkdown:!1}}},t.default=Object(l.OAS3ComponentWrapFactory)(d)},function(e,t,n){"use strict";n.r(t);var r=n(49),a=n.n(r),o=n(0),i=n.n(o),s=n(32);t.default=Object(s.OAS3ComponentWrapFactory)((function(e){var t=e.Ori,n=a()(e,["Ori"]),r=n.schema,o=n.getComponent,s=n.errSelectors,c=n.authorized,u=n.onAuthChange,l=n.name,p=o("HttpAuth");return"http"===r.get("type")?i.a.createElement(p,{key:l,schema:r,name:l,errSelectors:s,authorized:c,getComponent:o,onChange:u}):i.a.createElement(t,n)}))},function(e,t,n){"use strict";n.r(t);var r=n(0),a=n.n(r),o=n(32);t.default=Object(o.OAS3ComponentWrapFactory)((function(e){var t=e.Ori;return a.a.createElement("span",null,a.a.createElement(t,e),a.a.createElement("small",{className:"version-stamp"},a.a.createElement("pre",{className:"version"},"OAS3")))}))},function(e,t,n){"use strict";n.r(t);var r=n(32),a=n(170);t.default=Object(r.OAS3ComponentWrapFactory)(a.a)},function(e,t,n){"use strict";n.r(t);var r=n(28),a=n.n(r),o=n(6),i=n.n(o),s=n(7),c=n.n(s),u=n(8),l=n.n(u),p=n(9),f=n.n(p),d=n(0),h=n.n(d),m=(n(11),n(32)),v=n(172),g=function(e){l()(n,e);var t=f()(n);function n(){return i()(this,n),t.apply(this,arguments)}return c()(n,[{key:"render",value:function(){var e=this.props,t=e.getConfigs,n=["model-box"],r=null;return!0===e.schema.get("deprecated")&&(n.push("deprecated"),r=h.a.createElement("span",{className:"model-deprecated-warning"},"Deprecated:")),h.a.createElement("div",{className:n.join(" ")},r,h.a.createElement(v.a,a()({},this.props,{getConfigs:t,depth:1,expandDepth:this.props.expandDepth||0})))}}]),n}(d.Component);t.default=Object(m.OAS3ComponentWrapFactory)(g)},function(e,t,n){"use strict";n.r(t);var r=n(49),a=n.n(r),o=n(0),i=n.n(o),s=n(32);t.default=Object(s.OAS3ComponentWrapFactory)((function(e){var t=e.Ori,n=a()(e,["Ori"]),r=n.schema,o=n.getComponent,s=n.errors,c=n.onChange,u=r&&r.get?r.get("format"):null,l=r&&r.get?r.get("type"):null,p=o("Input");return l&&"string"===l&&u&&("binary"===u||"base64"===u)?i.a.createElement(p,{type:"file",className:s.length?"invalid":"",title:s.length?s:"",onChange:function(e){c(e.target.files[0])},disabled:t.isDisabled}):i.a.createElement(t,n)}))},function(e,t,n){"use strict";n.r(t),n.d(t,"selectedServer",(function(){return x})),n.d(t,"requestBodyValue",(function(){return S})),n.d(t,"shouldRetainRequestBodyValue",(function(){return w})),n.d(t,"hasUserEditedBody",(function(){return j})),n.d(t,"requestBodyInclusionSetting",(function(){return O})),n.d(t,"requestBodyErrors",(function(){return C})),n.d(t,"activeExamplesMember",(function(){return _})),n.d(t,"requestContentType",(function(){return A})),n.d(t,"responseContentType",(function(){return k})),n.d(t,"serverVariableValue",(function(){return I})),n.d(t,"serverVariables",(function(){return P})),n.d(t,"serverEffectiveValue",(function(){return T})),n.d(t,"validateBeforeExecute",(function(){return R})),n.d(t,"validateShallowRequired",(function(){return N}));var r=n(15),a=n.n(r),o=n(2),i=n.n(o),s=n(4),c=n.n(s),u=n(18),l=n.n(u),p=n(17),f=n.n(p),d=n(14),h=n.n(d),m=n(1),v=n(32),g=n(132),y=n(5);function b(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(t){var r=t.getSystem().specSelectors.specJson();return Object(v.isOAS3)(r)?e.apply(void 0,n):null}}}var E,x=b((function(e,t){var n=t?[t,"selectedServer"]:["selectedServer"];return e.getIn(n)||""})),S=b((function(e,t,n){return e.getIn(["requestData",t,n,"bodyValue"])||null})),w=b((function(e,t,n){return e.getIn(["requestData",t,n,"retainBodyValue"])||!1})),j=function(e,t,n){return function(e){var r=e.getSystem(),a=r.oas3Selectors,o=r.specSelectors,i=o.specJson();if(Object(v.isOAS3)(i)){var s=!1,c=a.requestContentType(t,n),u=a.requestBodyValue(t,n);if(m.Map.isMap(u)&&(u=Object(y.J)(u.mapEntries((function(e){return m.Map.isMap(e[1])?[e[0],e[1].get("value")]:e})).toJS())),m.List.isList(u)&&(u=Object(y.J)(u)),c){var l=Object(g.getDefaultRequestBodyValue)(o.specResolvedSubtree(["paths",t,n,"requestBody"]),c,a.activeExamplesMember(t,n,"requestBody","requestBody"));s=!!u&&u!==l}return s}return null}},O=b((function(e,t,n){return e.getIn(["requestData",t,n,"bodyInclusion"])||Object(m.Map)()})),C=b((function(e,t,n){return e.getIn(["requestData",t,n,"errors"])||null})),_=b((function(e,t,n,r,a){return e.getIn(["examples",t,n,r,a,"activeExample"])||null})),A=b((function(e,t,n){return e.getIn(["requestData",t,n,"requestContentType"])||null})),k=b((function(e,t,n){return e.getIn(["requestData",t,n,"responseContentType"])||null})),I=b((function(e,t,n){var r;if("string"!=typeof t){var a=t.server,o=t.namespace;r=o?[o,"serverVariableValues",a,n]:["serverVariableValues",a,n]}else{r=["serverVariableValues",t,n]}return e.getIn(r)||null})),P=b((function(e,t){var n;if("string"!=typeof t){var r=t.server,a=t.namespace;n=a?[a,"serverVariableValues",r]:["serverVariableValues",r]}else{n=["serverVariableValues",t]}return e.getIn(n)||Object(m.OrderedMap)()})),T=b((function(e,t){var n,r;if("string"!=typeof t){var a=t.server,o=t.namespace;r=a,n=o?e.getIn([o,"serverVariableValues",r]):e.getIn(["serverVariableValues",r])}else r=t,n=e.getIn(["serverVariableValues",r]);n=n||Object(m.OrderedMap)();var i=r;return c()(n).call(n,(function(e,t){i=i.replace(new RegExp("{".concat(t,"}"),"g"),e)})),i})),R=(E=function(e,t){return function(e,t){var n;return t=t||[],!!e.getIn(i()(n=["requestData"]).call(n,a()(t),["bodyValue"]))}(e,t)},function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){var n,r,o=e.getSystem().specSelectors.specJson(),s=i()(n=[]).call(n,t)[1]||[];return!o.getIn(i()(r=["paths"]).call(r,a()(s),["requestBody","required"]))||E.apply(void 0,t)}}),N=function(e,t){var n,r=t.oas3RequiredRequestBodyContentType,a=t.oas3RequestContentType,o=t.oas3RequestBodyValue,i=[];if(!m.Map.isMap(o))return i;var s=[];return l()(n=f()(r.requestContentType)).call(n,(function(e){if(e===a){var t=r.requestContentType[e];l()(t).call(t,(function(e){h()(s).call(s,e)<0&&s.push(e)}))}})),l()(s).call(s,(function(e){o.getIn([e,"value"])||i.push(e)})),i}},function(e,t,n){"use strict";n.r(t);var r,a=n(3),o=n.n(a),i=n(280),s=n.n(i),c=n(16),u=n.n(c),l=n(102),p=n.n(l),f=n(23),d=n.n(f),h=n(18),m=n.n(h),v=n(21),g=n.n(v),y=n(1),b=n(50);t.default=(r={},o()(r,b.UPDATE_SELECTED_SERVER,(function(e,t){var n=t.payload,r=n.selectedServerUrl,a=n.namespace,o=a?[a,"selectedServer"]:["selectedServer"];return e.setIn(o,r)})),o()(r,b.UPDATE_REQUEST_BODY_VALUE,(function(e,t){var n=t.payload,r=n.value,a=n.pathMethod,o=u()(a,2),i=o[0],c=o[1];if(!y.Map.isMap(r))return e.setIn(["requestData",i,c,"bodyValue"],r);var l,f=e.getIn(["requestData",i,c,"bodyValue"])||Object(y.Map)();y.Map.isMap(f)||(f=Object(y.Map)());var h=p()(r).call(r),v=s()(h),g=d()(v).call(v,0);return m()(g).call(g,(function(e){var t=r.getIn([e]);f.has(e)&&y.Map.isMap(t)||(l=f.setIn([e,"value"],t))})),e.setIn(["requestData",i,c,"bodyValue"],l)})),o()(r,b.UPDATE_REQUEST_BODY_VALUE_RETAIN_FLAG,(function(e,t){var n=t.payload,r=n.value,a=n.pathMethod,o=u()(a,2),i=o[0],s=o[1];return e.setIn(["requestData",i,s,"retainBodyValue"],r)})),o()(r,b.UPDATE_REQUEST_BODY_INCLUSION,(function(e,t){var n=t.payload,r=n.value,a=n.pathMethod,o=n.name,i=u()(a,2),s=i[0],c=i[1];return e.setIn(["requestData",s,c,"bodyInclusion",o],r)})),o()(r,b.UPDATE_ACTIVE_EXAMPLES_MEMBER,(function(e,t){var n=t.payload,r=n.name,a=n.pathMethod,o=n.contextType,i=n.contextName,s=u()(a,2),c=s[0],l=s[1];return e.setIn(["examples",c,l,o,i,"activeExample"],r)})),o()(r,b.UPDATE_REQUEST_CONTENT_TYPE,(function(e,t){var n=t.payload,r=n.value,a=n.pathMethod,o=u()(a,2),i=o[0],s=o[1];return e.setIn(["requestData",i,s,"requestContentType"],r)})),o()(r,b.UPDATE_RESPONSE_CONTENT_TYPE,(function(e,t){var n=t.payload,r=n.value,a=n.path,o=n.method;return e.setIn(["requestData",a,o,"responseContentType"],r)})),o()(r,b.UPDATE_SERVER_VARIABLE_VALUE,(function(e,t){var n=t.payload,r=n.server,a=n.namespace,o=n.key,i=n.val,s=a?[a,"serverVariableValues",r,o]:["serverVariableValues",r,o];return e.setIn(s,i)})),o()(r,b.SET_REQUEST_BODY_VALIDATE_ERROR,(function(e,t){var n=t.payload,r=n.path,a=n.method,o=n.validationErrors,i=[];if(i.push("Required field is not provided"),o.missingBodyValue)return e.setIn(["requestData",r,a,"errors"],Object(y.fromJS)(i));if(o.missingRequiredKeys&&o.missingRequiredKeys.length>0){var s=o.missingRequiredKeys;return e.updateIn(["requestData",r,a,"bodyValue"],Object(y.fromJS)({}),(function(e){return g()(s).call(s,(function(e,t){return e.setIn([t,"errors"],Object(y.fromJS)(i))}),e)}))}return console.warn("unexpected result: SET_REQUEST_BODY_VALIDATE_ERROR"),e})),o()(r,b.CLEAR_REQUEST_BODY_VALIDATE_ERROR,(function(e,t){var n=t.payload,r=n.path,a=n.method,o=e.getIn(["requestData",r,a,"bodyValue"]);if(!y.Map.isMap(o))return e.setIn(["requestData",r,a,"errors"],Object(y.fromJS)([]));var i=p()(o).call(o),c=s()(i),u=d()(c).call(c,0);return u?e.updateIn(["requestData",r,a,"bodyValue"],Object(y.fromJS)({}),(function(e){return g()(u).call(u,(function(e,t){return e.setIn([t,"errors"],Object(y.fromJS)([]))}),e)})):e})),o()(r,b.CLEAR_REQUEST_BODY_VALUE,(function(e,t){var n=t.payload.pathMethod,r=u()(n,2),a=r[0],o=r[1],i=e.getIn(["requestData",a,o,"bodyValue"]);return i?y.Map.isMap(i)?e.setIn(["requestData",a,o,"bodyValue"],Object(y.Map)()):e.setIn(["requestData",a,o,"bodyValue"],""):e})),r)},function(e,t,n){"use strict";n.r(t);var r,a=n(18),o=n.n(a),i=n(102),s=n.n(i),c=n(5),u=n(764),l={};o()(r=s()(u).call(u)).call(r,(function(e){if("./index.js"!==e){var t=u(e);l[Object(c.E)(e)]=t.default?t.default:t}})),t.default=l},function(e,t,n){"use strict";n.r(t);var r={};n.r(r),n.d(r,"path",(function(){return Mn})),n.d(r,"query",(function(){return Dn})),n.d(r,"header",(function(){return Bn})),n.d(r,"cookie",(function(){return Ln}));var a=n(2),o=n.n(a),i=n(37),s=n.n(i),c=n(66),u=n.n(c),l=n(18),p=n.n(l),f=n(12),d=n.n(f),h=n(45),m=n.n(h),v=n(388),g=n.n(v),y=n(17),b=n.n(y),E=n(4),x=n.n(E),S=n(85),w=n.n(S),j=n(30),O=n.n(j),C=n(33),_=n.n(C),A=n(13),k=n.n(A),I=n(19),P=n.n(I),T=n(16),R=n.n(T),N=n(164),M=n.n(N),D=n(21),q=n.n(D),B=n(71),L=n.n(B),U=n(35),V=n.n(U),z=n(14),F=n.n(z),J=(n(721),n(175)),W=n.n(J),H=n(65),$=n.n(H),Y=n(165),K=n.n(Y),G=n(55),Z=n.n(G),X=n(166),Q=n(56),ee=n.n(Q),te=n(6),ne=n.n(te),re=n(7),ae=n.n(re),oe=n(389),ie=n.n(oe),se=n(159),ce=n.n(se),ue=n(8),le=n.n(ue),pe=n(9),fe=n.n(pe),de=n(390),he=function(e){var t=function(e,t){return{name:e,value:t}};return Z()(e.prototype.set)||Z()(e.prototype.get)||Z()(e.prototype.getAll)||Z()(e.prototype.has)?e:function(e){le()(r,e);var n=fe()(r);function r(e){var t;return ne()(this,r),(t=n.call(this,e)).entryList=[],t}return ae()(r,[{key:"append",value:function(e,n,a){return this.entryList.push(t(e,n)),ie()(ce()(r.prototype),"append",this).call(this,e,n,a)}},{key:"set",value:function(e,n){var r,a=t(e,n);this.entryList=d()(r=this.entryList).call(r,(function(t){return t.name!==e})),this.entryList.push(a)}},{key:"get",value:function(e){var t,n=ee()(t=this.entryList).call(t,(function(t){return t.name===e}));return void 0===n?null:n}},{key:"getAll",value:function(e){var t,n;return x()(t=d()(n=this.entryList).call(n,(function(t){return t.name===e}))).call(t,(function(e){return e.value}))}},{key:"has",value:function(e){var t;return _()(t=this.entryList).call(t,(function(t){return t.name===e}))}}]),r}(e)}(n.n(de).a),me=n(23),ve=n.n(me),ge=n(15),ye=n.n(ge),be=n(166).Buffer,Ee=function(e){return F()(":/?#[]@!$&'()*+,;=").call(":/?#[]@!$&'()*+,;=",e)>-1},xe=function(e){return/^[a-z0-9\-._~]+$/i.test(e)};function Se(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.escape,a=arguments.length>2?arguments[2]:void 0;return"number"==typeof e&&(e=e.toString()),"string"==typeof e&&e.length&&r?a?JSON.parse(e):x()(t=ye()(e)).call(t,(function(e){var t,n;return xe(e)||Ee(e)&&"unsafe"===r?e:x()(t=x()(n=be.from(e).toJSON().data||[]).call(n,(function(e){var t;return ve()(t="0".concat(e.toString(16).toUpperCase())).call(t,-2)}))).call(t,(function(e){return"%".concat(e)})).join("")})).join(""):e}function we(e){var t=e.value;return k()(t)?function(e){var t,n=e.key,r=e.value,a=e.style,i=e.explode,s=e.escape,c=function(e){return Se(e,{escape:s})};if("simple"===a)return x()(r).call(r,(function(e){return c(e)})).join(",");if("label"===a)return".".concat(x()(r).call(r,(function(e){return c(e)})).join("."));if("matrix"===a)return q()(t=x()(r).call(r,(function(e){return c(e)}))).call(t,(function(e,t){var r,a,s;return!e||i?o()(a=o()(s="".concat(e||"",";")).call(s,n,"=")).call(a,t):o()(r="".concat(e,",")).call(r,t)}),"");if("form"===a){var u=i?"&".concat(n,"="):",";return x()(r).call(r,(function(e){return c(e)})).join(u)}if("spaceDelimited"===a){var l=i?"".concat(n,"="):"";return x()(r).call(r,(function(e){return c(e)})).join(" ".concat(l))}if("pipeDelimited"===a){var p=i?"".concat(n,"="):"";return x()(r).call(r,(function(e){return c(e)})).join("|".concat(p))}return}(e):"object"===P()(t)?function(e){var t=e.key,n=e.value,r=e.style,a=e.explode,i=e.escape,s=function(e){return Se(e,{escape:i})},c=b()(n);if("simple"===r)return q()(c).call(c,(function(e,t){var r,i,c,u=s(n[t]),l=a?"=":",",p=e?"".concat(e,","):"";return o()(r=o()(i=o()(c="".concat(p)).call(c,t)).call(i,l)).call(r,u)}),"");if("label"===r)return q()(c).call(c,(function(e,t){var r,i,c,u=s(n[t]),l=a?"=":".",p=e?"".concat(e,"."):".";return o()(r=o()(i=o()(c="".concat(p)).call(c,t)).call(i,l)).call(r,u)}),"");if("matrix"===r&&a)return q()(c).call(c,(function(e,t){var r,a,i=s(n[t]),c=e?"".concat(e,";"):";";return o()(r=o()(a="".concat(c)).call(a,t,"=")).call(r,i)}),"");if("matrix"===r)return q()(c).call(c,(function(e,r){var a,i,c=s(n[r]),u=e?"".concat(e,","):";".concat(t,"=");return o()(a=o()(i="".concat(u)).call(i,r,",")).call(a,c)}),"");if("form"===r)return q()(c).call(c,(function(e,t){var r,i,c,u,l=s(n[t]),p=e?o()(r="".concat(e)).call(r,a?"&":","):"",f=a?"=":",";return o()(i=o()(c=o()(u="".concat(p)).call(u,t)).call(c,f)).call(i,l)}),"");return}(e):function(e){var t,n=e.key,r=e.value,a=e.style,i=e.escape,s=function(e){return Se(e,{escape:i})};if("simple"===a)return s(r);if("label"===a)return".".concat(s(r));if("matrix"===a)return o()(t=";".concat(n,"=")).call(t,s(r));if("form"===a)return s(r);if("deepObject"===a)return s(r,{},!0);return}(e)}var je={serializeRes:ke,mergeInQueryOrForm:Ue};function Oe(e){return Ce.apply(this,arguments)}function Ce(){return(Ce=u()(s.a.mark((function e(t){var n,r,a,o,i,c,u=arguments;return s.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=u.length>1&&void 0!==u[1]?u[1]:{},"object"===P()(t)&&(t=(n=t).url),n.headers=n.headers||{},je.mergeInQueryOrForm(n),n.headers&&p()(r=b()(n.headers)).call(r,(function(e){var t=n.headers[e];"string"==typeof t&&(n.headers[e]=t.replace(/\n+/g," "))})),!n.requestInterceptor){e.next=12;break}return e.next=8,n.requestInterceptor(n);case 8:if(e.t0=e.sent,e.t0){e.next=11;break}e.t0=n;case 11:n=e.t0;case 12:return a=n.headers["content-type"]||n.headers["Content-Type"],/multipart\/form-data/i.test(a)&&(delete n.headers["content-type"],delete n.headers["Content-Type"]),e.prev=14,e.next=17,(n.userFetch||fetch)(n.url,n);case 17:return o=e.sent,e.next=20,je.serializeRes(o,t,n);case 20:if(o=e.sent,!n.responseInterceptor){e.next=28;break}return e.next=24,n.responseInterceptor(o);case 24:if(e.t1=e.sent,e.t1){e.next=27;break}e.t1=o;case 27:o=e.t1;case 28:e.next=39;break;case 30:if(e.prev=30,e.t2=e.catch(14),o){e.next=34;break}throw e.t2;case 34:throw(i=new Error(o.statusText)).status=o.status,i.statusCode=o.status,i.responseError=e.t2,i;case 39:if(o.ok){e.next=45;break}throw(c=new Error(o.statusText)).status=o.status,c.statusCode=o.status,c.response=o,c;case 45:return e.abrupt("return",o);case 46:case"end":return e.stop()}}),e,null,[[14,30]])})))).apply(this,arguments)}var _e=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return/(json|xml|yaml|text)\b/.test(e)};function Ae(e,t){return t&&(0===F()(t).call(t,"application/json")||F()(t).call(t,"+json")>0)?JSON.parse(e):$.a.safeLoad(e)}function ke(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.loadSpec,a=void 0!==r&&r,o={ok:e.ok,url:e.url||t,status:e.status,statusText:e.statusText,headers:Pe(e.headers)},i=o.headers["content-type"],s=a||_e(i),c=s?e.text:e.blob||e.buffer;return c.call(e).then((function(e){if(o.text=e,o.data=e,s)try{var t=Ae(e,i);o.body=t,o.obj=t}catch(e){o.parseError=e}return o}))}function Ie(e){return V()(e).call(e,", ")?e.split(", "):e}function Pe(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Z()(L()(t))?q()(e=M()(L()(t).call(t))).call(e,(function(e,t){var n=R()(t,2),r=n[0],a=n[1];return e[r]=Ie(a),e}),{}):{}}function Te(e,t){return t||"undefined"==typeof navigator||(t=navigator),t&&"ReactNative"===t.product?!(!e||"object"!==P()(e)||"string"!=typeof e.uri):"undefined"!=typeof File&&e instanceof File||("undefined"!=typeof Blob&&e instanceof Blob||(void 0!==X.Buffer&&e instanceof X.Buffer||null!==e&&"object"===P()(e)&&"function"==typeof e.pipe))}function Re(e,t){return k()(e)&&_()(e).call(e,(function(e){return Te(e,t)}))}var Ne={form:",",spaceDelimited:"%20",pipeDelimited:"|"},Me={csv:",",ssv:"%20",tsv:"%09",pipes:"|"};function De(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t.collectionFormat,a=t.allowEmptyValue,o=t.serializationOption,i=t.encoding,s="object"!==P()(t)||k()(t)?t:t.value,c=n?function(e){return e.toString()}:function(e){return encodeURIComponent(e)},u=c(e);if(void 0===s&&a)return[[u,""]];if(Te(s)||Re(s))return[[u,s]];if(o)return qe(e,s,n,o);if(i){var l;if(_()(l=[P()(i.style),P()(i.explode),P()(i.allowReserved)]).call(l,(function(e){return"undefined"!==e})))return qe(e,s,n,K()(i,["style","explode","allowReserved"]));if(i.contentType){if("application/json"===i.contentType){var p="string"==typeof s?s:O()(s);return[[u,c(p)]]}return[[u,c(s.toString())]]}return"object"!==P()(s)?[[u,c(s)]]:k()(s)&&w()(s).call(s,(function(e){return"object"!==P()(e)}))?[[u,x()(s).call(s,c).join(",")]]:[[u,c(O()(s))]]}return"object"!==P()(s)?[[u,c(s)]]:k()(s)?"multi"===r?[[u,x()(s).call(s,c)]]:[[u,x()(s).call(s,c).join(Me[r||"csv"])]]:[[u,""]]}function qe(e,t,n,r){var a,i,s,c=r.style||"form",u=void 0===r.explode?"form"===c:r.explode,l=!n&&(r&&r.allowReserved?"unsafe":"reserved"),p=function(e){return Se(e,{escape:l})},f=n?function(e){return e}:function(e){return Se(e,{escape:l})};return"object"!==P()(t)?[[f(e),p(t)]]:k()(t)?u?[[f(e),x()(t).call(t,p)]]:[[f(e),x()(t).call(t,p).join(Ne[c])]]:"deepObject"===c?x()(i=b()(t)).call(i,(function(n){var r;return[f(o()(r="".concat(e,"[")).call(r,n,"]")),p(t[n])]})):u?x()(s=b()(t)).call(s,(function(e){return[f(e),p(t[e])]})):[[f(e),x()(a=b()(t)).call(a,(function(e){var n;return[o()(n="".concat(f(e),",")).call(n,p(t[e]))]})).join(",")]]}function Be(e){var t;return q()(t=g()(e)).call(t,(function(e,t){var n,r=R()(t,2),a=r[0],o=r[1],i=m()(De(a,o,!0));try{for(i.s();!(n=i.n()).done;){var s=R()(n.value,2),c=s[0],u=s[1];if(k()(u)){var l,p=m()(u);try{for(p.s();!(l=p.n()).done;){var f=l.value;e.append(c,f)}}catch(e){p.e(e)}finally{p.f()}}else e.append(c,u)}}catch(e){i.e(e)}finally{i.f()}return e}),new he)}function Le(e){var t,n=q()(t=b()(e)).call(t,(function(t,n){var r,a=m()(De(n,e[n]));try{for(a.s();!(r=a.n()).done;){var o=R()(r.value,2),i=o[0],s=o[1];t[i]=s}}catch(e){a.e(e)}finally{a.f()}return t}),{});return W.a.stringify(n,{encode:!1,indices:!1})||""}function Ue(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.url,n=void 0===t?"":t,r=e.query,a=e.form,o=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=d()(t).call(t,(function(e){return e})).join("&");return r?"?".concat(r):""};if(a){var i,s=_()(i=b()(a)).call(i,(function(e){var t=a[e].value;return Te(t)||Re(t)})),c=e.headers["content-type"]||e.headers["Content-Type"];s||/multipart\/form-data/i.test(c)?e.body=Be(e.form):e.body=Le(a),delete e.form}if(r){var u=n.split("?"),l=R()(u,2),f=l[0],h=l[1],m="";if(h){var v=W.a.parse(h),g=b()(r);p()(g).call(g,(function(e){return delete v[e]})),m=W.a.stringify(v,{encode:!0})}var y=o(m,Le(r));e.url=f+y,delete e.query}return e}var Ve=n(391),ze=n.n(Ve),Fe=n(25),Je=n.n(Fe),We=n(57),He=n.n(We),$e=n(29),Ye=n.n($e),Ke=n(275),Ge=n.n(Ke),Ze=n(22),Xe=n.n(Ze),Qe=n(161),et=n.n(Qe),tt=n(276),nt=n.n(tt),rt=n(3),at=n.n(rt),ot=n(114),it=n(70),st=n.n(it),ct=n(392),ut=n.n(ct),lt={add:function(e,t){return{op:"add",path:e,value:t}},replace:ft,remove:function(e){return{op:"remove",path:e}},merge:function(e,t){return{type:"mutation",op:"merge",path:e,value:t}},mergeDeep:function(e,t){return{type:"mutation",op:"mergeDeep",path:e,value:t}},context:function(e,t){return{type:"context",path:e,value:t}},getIn:function(e,t){return q()(t).call(t,(function(e,t){return void 0!==t&&e?e[t]:e}),e)},applyPatch:function(e,t,n){if(n=n||{},"merge"===(t=Je()(Je()({},t),{},{path:t.path&&pt(t.path)})).op){var r=Ot(e,t.path);Xe()(r,t.value),ot.applyPatch(e,[ft(t.path,r)])}else if("mergeDeep"===t.op){var a=Ot(e,t.path);for(var i in t.value){var s=t.value[i],c=k()(s);if(c){var u=a[i]||[];a[i]=o()(u).call(u,s)}else if(bt(s)&&!c){var l=Je()({},a[i]);for(var p in s){if(Object.prototype.hasOwnProperty.call(l,p)){l=st()(ut()(l),s);break}Xe()(l,at()({},p,s[p]))}a[i]=l}else a[i]=s}}else if("add"===t.op&&""===t.path&&bt(t.value)){var f,d=q()(f=b()(t.value)).call(f,(function(e,n){return e.push({op:"add",path:"/".concat(pt(n)),value:t.value[n]}),e}),[]);ot.applyPatch(e,d)}else if("replace"===t.op&&""===t.path){var h=t.value;n.allowMetaPatches&&t.meta&&wt(t)&&(k()(t.value)||bt(t.value))&&(h=Je()(Je()({},h),t.meta)),e=h}else if(ot.applyPatch(e,[t]),n.allowMetaPatches&&t.meta&&wt(t)&&(k()(t.value)||bt(t.value))){var m=Ot(e,t.path),v=Je()(Je()({},m),t.meta);ot.applyPatch(e,[ft(t.path,v)])}return e},parentPathMatch:function(e,t){if(!k()(t))return!1;for(var n=0,r=t.length;n<r;n+=1)if(t[n]!==e[n])return!1;return!0},flatten:gt,fullyNormalizeArray:function(e){return yt(gt(vt(e)))},normalizeArray:vt,isPromise:function(e){return bt(e)&&Et(e.then)},forEachNew:function(e,t){try{return dt(e,mt,t)}catch(e){return e}},forEachNewPrimitive:function(e,t){try{return dt(e,ht,t)}catch(e){return e}},isJsonPatch:xt,isContextPatch:function(e){return jt(e)&&"context"===e.type},isPatch:jt,isMutation:St,isAdditiveMutation:wt,isGenerator:function(e){return"[object GeneratorFunction]"===Object.prototype.toString.call(e)},isFunction:Et,isObject:bt,isError:function(e){return e instanceof Error}};function pt(e){return k()(e)?e.length<1?"":"/".concat(x()(e).call(e,(function(e){return(e+"").replace(/~/g,"~0").replace(/\//g,"~1")})).join("/")):e}function ft(e,t,n){return{op:"replace",path:e,value:t,meta:n}}function dt(e,t,n){var r;return yt(gt(x()(r=d()(e).call(e,wt)).call(r,(function(e){return t(e.value,n,e.path)}))||[]))}function ht(e,t,n){return n=n||[],k()(e)?x()(e).call(e,(function(e,r){return ht(e,t,o()(n).call(n,r))})):bt(e)?x()(r=b()(e)).call(r,(function(r){return ht(e[r],t,o()(n).call(n,r))})):t(e,n[n.length-1],n);var r}function mt(e,t,n){var r=[];if((n=n||[]).length>0){var a=t(e,n[n.length-1],n);a&&(r=o()(r).call(r,a))}if(k()(e)){var i=x()(e).call(e,(function(e,r){return mt(e,t,o()(n).call(n,r))}));i&&(r=o()(r).call(r,i))}else if(bt(e)){var s,c=x()(s=b()(e)).call(s,(function(r){return mt(e[r],t,o()(n).call(n,r))}));c&&(r=o()(r).call(r,c))}return r=gt(r)}function vt(e){return k()(e)?e:[e]}function gt(e){var t,n,r;return(n=o()(t=[])).call.apply(n,o()(r=[t]).call(r,ye()(x()(e).call(e,(function(e){return k()(e)?gt(e):e})))))}function yt(e){return d()(e).call(e,(function(e){return void 0!==e}))}function bt(e){return e&&"object"===P()(e)}function Et(e){return e&&"function"==typeof e}function xt(e){if(jt(e)){var t=e.op;return"add"===t||"remove"===t||"replace"===t}return!1}function St(e){return xt(e)||jt(e)&&"mutation"===e.type}function wt(e){return St(e)&&("add"===e.op||"replace"===e.op||"merge"===e.op||"mergeDeep"===e.op)}function jt(e){return e&&"object"===P()(e)}function Ot(e,t){try{return ot.getValueByPointer(e,t)}catch(e){return console.error(e),{}}}var Ct=n(393),_t=n.n(Ct),At=n(394),kt=n(277),It=n.n(kt),Pt=n(72),Tt=n.n(Pt);function Rt(e,t){function n(){Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack;for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];this.message=n[0],t&&t.apply(this,n)}return n.prototype=new Error,n.prototype.name=e,n.prototype.constructor=n,n}var Nt=n(395),Mt=n.n(Nt),Dt=n(163),qt=n.n(Dt),Bt=["properties"],Lt=["properties"],Ut=["definitions","parameters","responses","securityDefinitions","components/schemas","components/responses","components/parameters","components/securitySchemes"],Vt=["schema/example","items/example"];function zt(e){var t=e[e.length-1],n=e[e.length-2],r=e.join("/");return F()(Bt).call(Bt,t)>-1&&-1===F()(Lt).call(Lt,n)||F()(Ut).call(Ut,r)>-1||_()(Vt).call(Vt,(function(e){return F()(r).call(r,e)>-1}))}function Ft(e,t){var n,r=e.split("#"),a=R()(r,2),i=a[0],s=a[1],c=Tt.a.resolve(i||"",t||"");return s?o()(n="".concat(c,"#")).call(n,s):c}var Jt="application/json, application/yaml",Wt=new RegExp("^([a-z]+://|//)","i"),Ht=Rt("JSONRefError",(function(e,t,n){this.originalError=n,Xe()(this,t||{})})),$t={},Yt=new _t.a,Kt=[function(e){return"paths"===e[0]&&"responses"===e[3]&&"examples"===e[5]},function(e){return"paths"===e[0]&&"responses"===e[3]&&"content"===e[5]&&"example"===e[7]},function(e){return"paths"===e[0]&&"responses"===e[3]&&"content"===e[5]&&"examples"===e[7]&&"value"===e[9]},function(e){return"paths"===e[0]&&"requestBody"===e[3]&&"content"===e[4]&&"example"===e[6]},function(e){return"paths"===e[0]&&"requestBody"===e[3]&&"content"===e[4]&&"examples"===e[6]&&"value"===e[8]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"example"===e[4]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"example"===e[5]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"examples"===e[4]&&"value"===e[6]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"examples"===e[5]&&"value"===e[7]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"content"===e[4]&&"example"===e[6]},function(e){return"paths"===e[0]&&"parameters"===e[2]&&"content"===e[4]&&"examples"===e[6]&&"value"===e[8]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"content"===e[4]&&"example"===e[7]},function(e){return"paths"===e[0]&&"parameters"===e[3]&&"content"===e[5]&&"examples"===e[7]&&"value"===e[9]}],Gt={key:"$ref",plugin:function(e,t,n,r){var a=r.getInstance(),i=ve()(n).call(n,0,-1);if(!zt(i)&&(s=i,!_()(Kt).call(Kt,(function(e){return e(s)})))){var s,c=r.getContext(n).baseDoc;if("string"!=typeof e)return new Ht("$ref: must be a string (JSON-Ref)",{$ref:e,baseDoc:c,fullPath:n});var u,l,p,f=tn(e),d=f[0],h=f[1]||"";try{u=c||d?Qt(d,c):null}catch(t){return en(t,{pointer:h,$ref:e,basePath:u,fullPath:n})}if(function(e,t,n,r){var a,i,s=Yt.get(r);s||(s={},Yt.set(r,s));var c=function(e){if(0===e.length)return"";return"/".concat(x()(e).call(e,cn).join("/"))}(n),u=o()(a="".concat(t||"<specmap-base>","#")).call(a,e),l=c.replace(/allOf\/\d+\/?/g,""),p=r.contextTree.get([]).baseDoc;if(t==p&&un(l,e))return!0;var f="";if(_()(n).call(n,(function(e){var t,n;return f=o()(t="".concat(f,"/")).call(t,cn(e)),s[f]&&_()(n=s[f]).call(n,(function(e){return un(e,u)||un(u,e)}))})))return!0;return void(s[l]=o()(i=s[l]||[]).call(i,u))}(h,u,i,r)&&!a.useCircularStructures){var m=Ft(e,u);return e===m?null:lt.replace(n,m)}if(null==u?(p=on(h),void 0===(l=r.get(p))&&(l=new Ht("Could not resolve reference: ".concat(e),{pointer:h,$ref:e,baseDoc:c,fullPath:n}))):l=null!=(l=nn(u,h)).__value?l.__value:l.catch((function(t){throw en(t,{pointer:h,$ref:e,baseDoc:c,fullPath:n})})),l instanceof Error)return[lt.remove(n),l];var v=Ft(e,u),g=lt.replace(i,l,{$$ref:v});if(u&&u!==c)return[g,lt.context(i,{baseDoc:u})];try{if(!function(e,t){var n,r=[e];return q()(n=t.path).call(n,(function(e,t){return r.push(e[t]),e[t]}),e),a(t.value);function a(e){var t;return lt.isObject(e)&&(F()(r).call(r,e)>=0||_()(t=b()(e)).call(t,(function(t){return a(e[t])})))}}(r.state,g)||a.useCircularStructures)return g}catch(e){return null}}}},Zt=Xe()(Gt,{docCache:$t,absoluteify:Qt,clearCache:function(e){var t;void 0!==e?delete $t[e]:p()(t=b()($t)).call(t,(function(e){delete $t[e]}))},JSONRefError:Ht,wrapError:en,getDoc:rn,split:tn,extractFromDoc:nn,fetchJSON:function(e){return Object(At.fetch)(e,{headers:{Accept:Jt},loadSpec:!0}).then((function(e){return e.text()})).then((function(e){return $.a.safeLoad(e)}))},extract:an,jsonPointerToArray:on,unescapeJsonPointerToken:sn}),Xt=Zt;function Qt(e,t){if(!Wt.test(e)){var n;if(!t)throw new Ht(o()(n="Tried to resolve a relative URL, without having a basePath. path: '".concat(e,"' basePath: '")).call(n,t,"'"));return Tt.a.resolve(t,e)}return e}function en(e,t){var n,r;e&&e.response&&e.response.body?n=o()(r="".concat(e.response.body.code," ")).call(r,e.response.body.message):n=e.message;return new Ht("Could not resolve reference: ".concat(n),t,e)}function tn(e){return(e+"").split("#")}function nn(e,t){var n=$t[e];if(n&&!lt.isPromise(n))try{var r=an(t,n);return Xe()(He.a.resolve(r),{__value:r})}catch(e){return He.a.reject(e)}return rn(e).then((function(e){return an(t,e)}))}function rn(e){var t=$t[e];return t?lt.isPromise(t)?t:He.a.resolve(t):($t[e]=Zt.fetchJSON(e).then((function(t){return $t[e]=t,t})),$t[e])}function an(e,t){var n=on(e);if(n.length<1)return t;var r=lt.getIn(t,n);if(void 0===r)throw new Ht("Could not resolve pointer: ".concat(e," does not exist in document"),{pointer:e});return r}function on(e){var t;if("string"!=typeof e)throw new TypeError("Expected a string, got a ".concat(P()(e)));return"/"===e[0]&&(e=e.substr(1)),""===e?[]:x()(t=e.split("/")).call(t,sn)}function sn(e){return"string"!=typeof e?e:It.a.unescape(e.replace(/~1/g,"/").replace(/~0/g,"~"))}function cn(e){return It.a.escape(e.replace(/~/g,"~0").replace(/\//g,"~1"))}function un(e,t){if(!(n=t)||"/"===n||"#"===n)return!0;var n,r=e.charAt(t.length),a=ve()(t).call(t,-1);return 0===F()(e).call(e,t)&&(!r||"/"===r||"#"===r)&&"#"!==a}var ln=n(87),pn=n.n(ln),fn={key:"allOf",plugin:function(e,t,n,r,a){if(!a.meta||!a.meta.$$ref){var i=ve()(n).call(n,0,-1);if(!zt(i)){if(!k()(e)){var s=new TypeError("allOf must be an array");return s.fullPath=n,s}var c=!1,u=a.value;if(p()(i).call(i,(function(e){u&&(u=u[e])})),u=Je()({},u),!pn()(u)){delete u.allOf;var l,f=[];if(f.push(r.replace(i,{})),p()(e).call(e,(function(e,t){if(!r.isObject(e)){if(c)return null;c=!0;var a=new TypeError("Elements in allOf must be objects");return a.fullPath=n,f.push(a)}f.push(r.mergeDeep(i,e));var s=function(e,t){var n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=r.specmap,i=r.getBaseUrlForNodePath,s=void 0===i?function(e){var n;return a.getContext(o()(n=[]).call(n,ye()(t),ye()(e))).baseDoc}:i,c=r.targetKeys,u=void 0===c?["$ref","$$ref"]:c,l=[];return p()(n=Mt()(e)).call(n,(function(){if(V()(u).call(u,this.key)&&qt()(this.node)){var e=this.path,n=o()(t).call(t,this.path),r=Ft(this.node,s(e));l.push(a.replace(n,r))}})),l}(e,ve()(n).call(n,0,-1),{getBaseUrlForNodePath:function(e){var a;return r.getContext(o()(a=[]).call(a,ye()(n),[t],ye()(e))).baseDoc},specmap:r});f.push.apply(f,ye()(s))})),f.push(r.mergeDeep(i,u)),!u.$$ref)f.push(r.remove(o()(l=[]).call(l,i,"$$ref")));return f}}}}},dn={key:"parameters",plugin:function(e,t,n,r){if(k()(e)&&e.length){var a=Xe()([],e),o=ve()(n).call(n,0,-1),i=Je()({},lt.getIn(r.spec,o));return p()(e).call(e,(function(e,t){try{a[t].default=r.parameterMacro(i,e)}catch(e){var o=new Error(e);return o.fullPath=n,o}})),lt.replace(n,a)}return lt.replace(n,e)}},hn={key:"properties",plugin:function(e,t,n,r){var a=Je()({},e);for(var o in e)try{a[o].default=r.modelPropertyMacro(a[o])}catch(e){var i=new Error(e);return i.fullPath=n,i}return lt.replace(n,a)}},mn=function(){function e(t){ne()(this,e),this.root=vn(t||{})}return ae()(e,[{key:"set",value:function(e,t){var n=this.getParent(e,!0);if(n){var r=e[e.length-1],a=n.children;a[r]?gn(a[r],t,n):a[r]=vn(t,n)}else gn(this.root,t,null)}},{key:"get",value:function(e){if((e=e||[]).length<1)return this.root.value;for(var t,n,r=this.root,a=0;a<e.length&&(n=e[a],(t=r.children)[n]);a+=1)r=t[n];return r&&r.protoValue}},{key:"getParent",value:function(e,t){var n;return!e||e.length<1?null:e.length<2?this.root:q()(n=ve()(e).call(e,0,-1)).call(n,(function(e,n){if(!e)return e;var r=e.children;return!r[n]&&t&&(r[n]=vn(null,e)),r[n]}),this.root)}}]),e}();function vn(e,t){return gn({children:{}},e,t)}function gn(e,t,n){var r;return e.value=t||{},e.protoValue=n?Je()(Je()({},n.protoValue),e.value):e.value,p()(r=b()(e.children)).call(r,(function(t){var n=e.children[t];e.children[t]=gn(n,n.value,e)})),e}var yn=function(){function e(t){var n,r,a,o,i,s,c=this;ne()(this,e),Xe()(this,{spec:"",debugLevel:"info",plugins:[],pluginHistory:{},errors:[],mutations:[],promisedPatches:[],state:{},patches:[],context:{},contextTree:new mn,showDebug:!1,allPatches:[],pluginProp:"specMap",libMethods:Xe()(Ge()(this),lt,{getInstance:function(){return c}}),allowMetaPatches:!1},t),this.get=Ye()(n=this._get).call(n,this),this.getContext=Ye()(r=this._getContext).call(r,this),this.hasRun=Ye()(a=this._hasRun).call(a,this),this.wrappedPlugins=d()(o=x()(i=this.plugins).call(i,Ye()(s=this.wrapPlugin).call(s,this))).call(o,lt.isFunction),this.patches.push(lt.add([],this.spec)),this.patches.push(lt.context([],this.context)),this.updatePatches(this.patches)}return ae()(e,[{key:"debug",value:function(e){if(this.debugLevel===e){for(var t,n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];(t=console).log.apply(t,r)}}},{key:"verbose",value:function(e){if("verbose"===this.debugLevel){for(var t,n,r=arguments.length,a=new Array(r>1?r-1:0),i=1;i<r;i++)a[i-1]=arguments[i];(t=console).log.apply(t,o()(n=["[".concat(e,"] ")]).call(n,a))}}},{key:"wrapPlugin",value:function(e,t){var n,r,a,i=this.pathDiscriminator,c=null;return e[this.pluginProp]?(c=e,n=e[this.pluginProp]):lt.isFunction(e)?n=e:lt.isObject(e)&&(r=e,a=function(e,t){return!k()(e)||w()(e).call(e,(function(e,n){return e===t[n]}))},n=s.a.mark((function e(t,n){var c,u,l,p,f,h;return s.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:h=function(e,t,l){var p,f,d,m,v,g,y,E,x,S,w,j,O;return s.a.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:if(lt.isObject(e)){s.next=6;break}if(r.key!==t[t.length-1]){s.next=4;break}return s.next=4,r.plugin(e,r.key,t,n);case 4:s.next=30;break;case 6:p=t.length-1,f=t[p],d=F()(t).call(t,"properties"),m="properties"===f&&p===d,v=n.allowMetaPatches&&u[e.$$ref],g=0,y=b()(e);case 12:if(!(g<y.length)){s.next=30;break}if(E=y[g],x=e[E],S=o()(t).call(t,E),w=lt.isObject(x),j=e.$$ref,v){s.next=22;break}if(!w){s.next=22;break}return n.allowMetaPatches&&j&&(u[j]=!0),s.delegateYield(h(x,S,l),"t0",22);case 22:if(m||E!==r.key){s.next=27;break}if(O=a(i,t),i&&!O){s.next=27;break}return s.next=27,r.plugin(x,E,S,n,l);case 27:g++,s.next=12;break;case 30:case"end":return s.stop()}}),c)},c=s.a.mark(h),u={},l=m()(d()(t).call(t,lt.isAdditiveMutation)),e.prev=4,l.s();case 6:if((p=l.n()).done){e.next=11;break}return f=p.value,e.delegateYield(h(f.value,f.path,f),"t0",9);case 9:e.next=6;break;case 11:e.next=16;break;case 13:e.prev=13,e.t1=e.catch(4),l.e(e.t1);case 16:return e.prev=16,l.f(),e.finish(16);case 19:case"end":return e.stop()}}),e,null,[[4,13,16,19]])}))),Xe()(Ye()(n).call(n,c),{pluginName:e.name||t,isGenerator:lt.isGenerator(n)})}},{key:"nextPlugin",value:function(){var e=this;return et()(this.wrappedPlugins,(function(t){return e.getMutationsForPlugin(t).length>0}))}},{key:"nextPromisedPatch",value:function(){var e;if(this.promisedPatches.length>0)return He.a.race(x()(e=this.promisedPatches).call(e,(function(e){return e.value})))}},{key:"getPluginHistory",value:function(e){var t=this.constructor.getPluginName(e);return this.pluginHistory[t]||[]}},{key:"getPluginRunCount",value:function(e){return this.getPluginHistory(e).length}},{key:"getPluginHistoryTip",value:function(e){var t=this.getPluginHistory(e);return t&&t[t.length-1]||{}}},{key:"getPluginMutationIndex",value:function(e){var t=this.getPluginHistoryTip(e).mutationIndex;return"number"!=typeof t?-1:t}},{key:"updatePluginHistory",value:function(e,t){var n=this.constructor.getPluginName(e);this.pluginHistory[n]=this.pluginHistory[n]||[],this.pluginHistory[n].push(t)}},{key:"updatePatches",value:function(e){var t,n=this;p()(t=lt.normalizeArray(e)).call(t,(function(e){if(e instanceof Error)n.errors.push(e);else try{if(!lt.isObject(e))return void n.debug("updatePatches","Got a non-object patch",e);if(n.showDebug&&n.allPatches.push(e),lt.isPromise(e.value))return n.promisedPatches.push(e),void n.promisedPatchThen(e);if(lt.isContextPatch(e))return void n.setContext(e.path,e.value);if(lt.isMutation(e))return void n.updateMutations(e)}catch(e){console.error(e),n.errors.push(e)}}))}},{key:"updateMutations",value:function(e){"object"===P()(e.value)&&!k()(e.value)&&this.allowMetaPatches&&(e.value=Je()({},e.value));var t=lt.applyPatch(this.state,e,{allowMetaPatches:this.allowMetaPatches});t&&(this.mutations.push(e),this.state=t)}},{key:"removePromisedPatch",value:function(e){var t,n,r=F()(t=this.promisedPatches).call(t,e);r<0?this.debug("Tried to remove a promisedPatch that isn't there!"):ze()(n=this.promisedPatches).call(n,r,1)}},{key:"promisedPatchThen",value:function(e){var t=this;return e.value=e.value.then((function(n){var r=Je()(Je()({},e),{},{value:n});t.removePromisedPatch(e),t.updatePatches(r)})).catch((function(n){t.removePromisedPatch(e),t.updatePatches(n)})),e.value}},{key:"getMutations",value:function(e,t){var n;return e=e||0,"number"!=typeof t&&(t=this.mutations.length),ve()(n=this.mutations).call(n,e,t)}},{key:"getCurrentMutations",value:function(){return this.getMutationsForPlugin(this.getCurrentPlugin())}},{key:"getMutationsForPlugin",value:function(e){var t=this.getPluginMutationIndex(e);return this.getMutations(t+1)}},{key:"getCurrentPlugin",value:function(){return this.currentPlugin}},{key:"getLib",value:function(){return this.libMethods}},{key:"_get",value:function(e){return lt.getIn(this.state,e)}},{key:"_getContext",value:function(e){return this.contextTree.get(e)}},{key:"setContext",value:function(e,t){return this.contextTree.set(e,t)}},{key:"_hasRun",value:function(e){return this.getPluginRunCount(this.getCurrentPlugin())>(e||0)}},{key:"dispatch",value:function(){var e,t=this,n=this,r=this.nextPlugin();if(!r){var a=this.nextPromisedPatch();if(a)return a.then((function(){return t.dispatch()})).catch((function(){return t.dispatch()}));var i={spec:this.state,errors:this.errors};return this.showDebug&&(i.patches=this.allPatches),He.a.resolve(i)}if(n.pluginCount=n.pluginCount||{},n.pluginCount[r]=(n.pluginCount[r]||0)+1,n.pluginCount[r]>100)return He.a.resolve({spec:n.state,errors:o()(e=n.errors).call(e,new Error("We've reached a hard limit of ".concat(100," plugin runs")))});if(r!==this.currentPlugin&&this.promisedPatches.length){var s,c=x()(s=this.promisedPatches).call(s,(function(e){return e.value}));return He.a.all(x()(c).call(c,(function(e){return e.then(nt.a,nt.a)}))).then((function(){return t.dispatch()}))}return function(){n.currentPlugin=r;var e=n.getCurrentMutations(),t=n.mutations.length-1;try{if(r.isGenerator){var a,o=m()(r(e,n.getLib()));try{for(o.s();!(a=o.n()).done;){u(a.value)}}catch(e){o.e(e)}finally{o.f()}}else{u(r(e,n.getLib()))}}catch(e){console.error(e),u([Xe()(Ge()(e),{plugin:r})])}finally{n.updatePluginHistory(r,{mutationIndex:t})}return n.dispatch()}();function u(e){e&&(e=lt.fullyNormalizeArray(e),n.updatePatches(e,r))}}}],[{key:"getPluginName",value:function(e){return e.pluginName}},{key:"getPatchesOfType",value:function(e,t){return d()(e).call(e,t)}}]),e}();var bn={refs:Xt,allOf:fn,parameters:dn,properties:hn},En=n(52);function xn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.requestInterceptor,r=t.responseInterceptor,a=e.withCredentials?"include":"same-origin";return function(t){return e({url:t,loadSpec:!0,requestInterceptor:n,responseInterceptor:r,headers:{Accept:Jt},credentials:a}).then((function(e){return e.body}))}}function Sn(e){var t=e.fetch,n=e.spec,r=e.url,a=e.mode,o=e.allowMetaPatches,i=void 0===o||o,c=e.pathDiscriminator,l=e.modelPropertyMacro,p=e.parameterMacro,f=e.requestInterceptor,d=e.responseInterceptor,h=e.skipNormalization,m=e.useCircularStructures,v=e.http,g=e.baseDoc;return g=g||r,v=t||v||Oe,n?y(n):xn(v,{requestInterceptor:f,responseInterceptor:d})(g).then(y);function y(e){g&&(bn.refs.docCache[g]=e),bn.refs.fetchJSON=xn(v,{requestInterceptor:f,responseInterceptor:d});var t,n=[bn.refs];return"function"==typeof p&&n.push(bn.parameters),"function"==typeof l&&n.push(bn.properties),"strict"!==a&&n.push(bn.allOf),(t={spec:e,context:{baseDoc:g},plugins:n,allowMetaPatches:i,pathDiscriminator:c,parameterMacro:p,modelPropertyMacro:l,useCircularStructures:m},new yn(t).dispatch()).then(h?function(){var e=u()(s.a.mark((function e(t){return s.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",t);case 1:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}():En.d)}}var wn=n(49),jn=n.n(wn),On=n(41),Cn=n.n(On),_n=n(225),An=n.n(_n),kn=n(47),In=n.n(kn),Pn=n(396),Tn=n.n(Pn),Rn={body:function(e){var t=e.req,n=e.value;t.body=n},header:function(e){var t=e.req,n=e.parameter,r=e.value;t.headers=t.headers||{},void 0!==r&&(t.headers[n.name]=r)},query:function(e){var t,n=e.req,r=e.value,a=e.parameter;n.query=n.query||{},!1===r&&"boolean"===a.type&&(r="false");0===r&&F()(t=["number","integer"]).call(t,a.type)>-1&&(r="0");if(r)n.query[a.name]={collectionFormat:a.collectionFormat,value:r};else if(a.allowEmptyValue&&void 0!==r){var o=a.name;n.query[o]=n.query[o]||{},n.query[o].allowEmptyValue=!0}},path:function(e){var t=e.req,n=e.value,r=e.parameter;t.url=t.url.split("{".concat(r.name,"}")).join(encodeURIComponent(n))},formData:function(e){var t=e.req,n=e.value,r=e.parameter;(n||r.allowEmptyValue)&&(t.form=t.form||{},t.form[r.name]={value:n,allowEmptyValue:r.allowEmptyValue,collectionFormat:r.collectionFormat})}};function Nn(e,t){return V()(t).call(t,"application/json")?"string"==typeof e?e:O()(e):e.toString()}function Mn(e){var t=e.req,n=e.value,r=e.parameter,a=r.name,o=r.style,i=r.explode,s=r.content;if(s){var c=b()(s)[0];t.url=t.url.split("{".concat(a,"}")).join(Se(Nn(n,c),{escape:!0}))}else{var u=we({key:r.name,value:n,style:o||"simple",explode:i||!1,escape:!0});t.url=t.url.split("{".concat(a,"}")).join(u)}}function Dn(e){var t=e.req,n=e.value,r=e.parameter;if(t.query=t.query||{},r.content){var a=b()(r.content)[0];t.query[r.name]=Nn(n,a)}else if(!1===n&&(n="false"),0===n&&(n="0"),n)t.query[r.name]={value:n,serializationOption:K()(r,["style","explode","allowReserved"])};else if(r.allowEmptyValue&&void 0!==n){var o=r.name;t.query[o]=t.query[o]||{},t.query[o].allowEmptyValue=!0}}var qn=["accept","authorization","content-type"];function Bn(e){var t=e.req,n=e.parameter,r=e.value;if(t.headers=t.headers||{},!(F()(qn).call(qn,n.name.toLowerCase())>-1))if(n.content){var a=b()(n.content)[0];t.headers[n.name]=Nn(r,a)}else void 0!==r&&(t.headers[n.name]=we({key:n.name,value:r,style:n.style||"simple",explode:void 0!==n.explode&&n.explode,escape:!1}))}function Ln(e){var t=e.req,n=e.parameter,r=e.value;t.headers=t.headers||{};var a=P()(r);if(n.content){var i,s=b()(n.content)[0];t.headers.Cookie=o()(i="".concat(n.name,"=")).call(i,Nn(r,s))}else if("undefined"!==a){var c="object"===a&&!k()(r)&&n.explode?"":"".concat(n.name,"=");t.headers.Cookie=c+we({key:n.name,value:r,escape:!1,style:n.style||"form",explode:void 0!==n.explode&&n.explode})}}var Un=n(167),Vn=n.n(Un),zn=n(168),Fn=n.n(zn);function Jn(e,t){var n=e.operation,r=e.requestBody,a=e.securities,i=e.spec,s=e.attachContentTypeForEmptyPayload,c=e.requestContentType;t=function(e){var t=e.request,n=e.securities,r=void 0===n?{}:n,a=e.operation,i=void 0===a?{}:a,s=e.spec,c=Vn()({},t),u=r.authorized,l=void 0===u?{}:u,f=i.security||s.security||[],d=l&&!!b()(l).length,h=Cn()(s,["components","securitySchemes"])||{};if(c.headers=c.headers||{},c.query=c.query||{},!b()(r).length||!d||!f||k()(i.security)&&!i.security.length)return t;return p()(f).call(f,(function(e){var t;p()(t=b()(e)).call(t,(function(e){var t=l[e],n=h[e];if(t){var r=t.value||t,a=n.type;if(t)if("apiKey"===a)"query"===n.in&&(c.query[n.name]=r),"header"===n.in&&(c.headers[n.name]=r),"cookie"===n.in&&(c.cookies[n.name]=r);else if("http"===a){if(/^basic$/i.test(n.scheme)){var i,s=r.username||"",u=r.password||"",p=Fn()(o()(i="".concat(s,":")).call(i,u));c.headers.Authorization="Basic ".concat(p)}/^bearer$/i.test(n.scheme)&&(c.headers.Authorization="Bearer ".concat(r))}else if("oauth2"===a||"openIdConnect"===a){var f,d=t.token||{},m=d[n["x-tokenName"]||"access_token"],v=d.token_type;v&&"bearer"!==v.toLowerCase()||(v="Bearer"),c.headers.Authorization=o()(f="".concat(v," ")).call(f,m)}}}))})),c}({request:t,securities:a,operation:n,spec:i});var u=n.requestBody||{},l=b()(u.content||{}),f=c&&F()(l).call(l,c)>-1;if(r||s){if(c&&f)t.headers["Content-Type"]=c;else if(!c){var d=l[0];d&&(t.headers["Content-Type"]=d,c=d)}}else c&&f&&(t.headers["Content-Type"]=c);if(r)if(c){if(F()(l).call(l,c)>-1)if("application/x-www-form-urlencoded"===c||"multipart/form-data"===c)if("object"===P()(r)){var h,m=(u.content[c]||{}).encoding||{};t.form={},p()(h=b()(r)).call(h,(function(e){t.form[e]={value:r[e],encoding:m[e]||{}}}))}else t.form=r;else t.body=r}else t.body=r;return t}function Wn(e,t){var n,r,a=e.spec,i=e.operation,s=e.securities,c=e.requestContentType,u=e.attachContentTypeForEmptyPayload;if((t=function(e){var t=e.request,n=e.securities,r=void 0===n?{}:n,a=e.operation,i=void 0===a?{}:a,s=e.spec,c=Vn()({},t),u=r.authorized,l=void 0===u?{}:u,f=r.specSecurity,d=void 0===f?[]:f,h=i.security||d,m=l&&!!b()(l).length,v=s.securityDefinitions;if(c.headers=c.headers||{},c.query=c.query||{},!b()(r).length||!m||!h||k()(i.security)&&!i.security.length)return t;return p()(h).call(h,(function(e){var t;p()(t=b()(e)).call(t,(function(e){var t=l[e];if(t){var n=t.token,r=t.value||t,a=v[e],i=a.type,s=a["x-tokenName"]||"access_token",u=n&&n[s],p=n&&n.token_type;if(t)if("apiKey"===i){var f="query"===a.in?"query":"headers";c[f]=c[f]||{},c[f][a.name]=r}else if("basic"===i)if(r.header)c.headers.authorization=r.header;else{var d,h=r.username||"",m=r.password||"";r.base64=Fn()(o()(d="".concat(h,":")).call(d,m)),c.headers.authorization="Basic ".concat(r.base64)}else if("oauth2"===i&&u){var g;p=p&&"bearer"!==p.toLowerCase()?p:"Bearer",c.headers.authorization=o()(g="".concat(p," ")).call(g,u)}}}))})),c}({request:t,securities:s,operation:i,spec:a})).body||t.form||u)if(c)t.headers["Content-Type"]=c;else if(k()(i.consumes)){var l=R()(i.consumes,1);t.headers["Content-Type"]=l[0]}else if(k()(a.consumes)){var f=R()(a.consumes,1);t.headers["Content-Type"]=f[0]}else i.parameters&&d()(n=i.parameters).call(n,(function(e){return"file"===e.type})).length?t.headers["Content-Type"]="multipart/form-data":i.parameters&&d()(r=i.parameters).call(r,(function(e){return"formData"===e.in})).length&&(t.headers["Content-Type"]="application/x-www-form-urlencoded");else if(c){var h,m,v=i.parameters&&d()(h=i.parameters).call(h,(function(e){return"body"===e.in})).length>0,g=i.parameters&&d()(m=i.parameters).call(m,(function(e){return"formData"===e.in})).length>0;(v||g)&&(t.headers["Content-Type"]=c)}return t}var Hn=function(e){return k()(e)?e:[]},$n=Rt("OperationNotFoundError",(function(e,t,n){this.originalError=n,Xe()(this,t||{})})),Yn={buildRequest:Gn};function Kn(e){var t=e.http,n=e.fetch,r=e.spec,a=e.operationId,o=e.pathName,i=e.method,s=e.parameters,c=e.securities,u=jn()(e,["http","fetch","spec","operationId","pathName","method","parameters","securities"]),l=t||n||Oe;o&&i&&!a&&(a=Object(En.c)(o,i));var p=Yn.buildRequest(Je()({spec:r,operationId:a,parameters:s,securities:c,http:l},u));return p.body&&(An()(p.body)||In()(p.body))&&(p.body=O()(p.body)),l(p)}function Gn(e){var t,n,a=e.spec,i=e.operationId,s=e.responseContentType,c=e.scheme,u=e.requestInterceptor,l=e.responseInterceptor,f=e.contextUrl,h=e.userFetch,m=e.server,v=e.serverVariables,g=e.http,y=e.parameters,E=e.parameterBuilders,S=Object(En.b)(a);E||(E=S?r:Rn);var w={url:"",credentials:g&&g.withCredentials?"include":"same-origin",headers:{},cookies:{}};u&&(w.requestInterceptor=u),l&&(w.responseInterceptor=l),h&&(w.userFetch=h);var j=Object(En.a)(a,i);if(!j)throw new $n("Operation ".concat(i," not found"));var O,C=j.operation,_=void 0===C?{}:C,A=j.method,I=j.pathName;if(w.url+=(O={spec:a,scheme:c,contextUrl:f,server:m,serverVariables:v,pathName:I,method:A},Object(En.b)(O.spec)?function(e){var t=e.spec,n=e.pathName,r=e.method,a=e.server,i=e.contextUrl,s=e.serverVariables,c=void 0===s?{}:s,u=Cn()(t,["paths",n,(r||"").toLowerCase(),"servers"])||Cn()(t,["paths",n,"servers"])||Cn()(t,["servers"]),l="",f=null;if(a&&u&&u.length){var d=x()(u).call(u,(function(e){return e.url}));F()(d).call(d,a)>-1&&(l=a,f=u[F()(d).call(d,a)])}if(!l&&u&&u.length){l=u[0].url;var h=R()(u,1);f=h[0]}if(F()(l).call(l,"{")>-1){var m=function(e){for(var t,n=[],r=/{([^}]+)}/g;t=r.exec(e);)n.push(t[1]);return n}(l);p()(m).call(m,(function(e){if(f.variables&&f.variables[e]){var t=f.variables[e],n=c[e]||t.default,r=new RegExp("{".concat(e,"}"),"g");l=l.replace(r,n)}}))}return function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",a=n&&r?Tt.a.parse(Tt.a.resolve(r,n)):Tt.a.parse(n),i=Tt.a.parse(r),s=Zn(a.protocol)||Zn(i.protocol)||"",c=a.host||i.host,u=a.pathname||"";return"/"===(e=s&&c?o()(t="".concat(s,"://")).call(t,c+u):u)[e.length-1]?ve()(e).call(e,0,-1):e}(l,i)}(O):function(e){var t,n,r=e.spec,a=e.scheme,i=e.contextUrl,s=void 0===i?"":i,c=Tt.a.parse(s),u=k()(r.schemes)?r.schemes[0]:null,l=a||u||Zn(c.protocol)||"http",p=r.host||c.host||"",f=r.basePath||"";return"/"===(t=l&&p?o()(n="".concat(l,"://")).call(n,p+f):f)[t.length-1]?ve()(t).call(t,0,-1):t}(O)),!i)return delete w.cookies,w;w.url+=I,w.method="".concat(A).toUpperCase(),y=y||{};var P=a.paths[I]||{};s&&(w.headers.accept=s);var T=function(e){var t,n={};p()(e).call(e,(function(e){n[e.in]||(n[e.in]={}),n[e.in][e.name]=e}));var r=[];return p()(t=b()(n)).call(t,(function(e){var t;p()(t=b()(n[e])).call(t,(function(t){r.push(n[e][t])}))})),r}(o()(t=o()(n=[]).call(n,Hn(_.parameters))).call(t,Hn(P.parameters)));p()(T).call(T,(function(e){var t,n,r=E[e.in];if("body"===e.in&&e.schema&&e.schema.properties&&(t=y),void 0===(t=e&&e.name&&y[e.name]))t=e&&e.name&&y[o()(n="".concat(e.in,".")).call(n,e.name)];else if(function(e,t){return d()(t).call(t,(function(t){return t.name===e}))}(e.name,T).length>1){var i;console.warn(o()(i="Parameter '".concat(e.name,"' is ambiguous because the defined spec has more than one parameter with the name: '")).call(i,e.name,"' and the passed-in parameter values did not define an 'in' value."))}if(null!==t){if(void 0!==e.default&&void 0===t&&(t=e.default),void 0===t&&e.required&&!e.allowEmptyValue)throw new Error("Required parameter ".concat(e.name," is not provided"));if(S&&e.schema&&"object"===e.schema.type&&"string"==typeof t)try{t=JSON.parse(t)}catch(e){throw new Error("Could not parse object parameter value string as JSON")}r&&r({req:w,parameter:e,value:t,operation:_,spec:a})}}));var N=Je()(Je()({},e),{},{operation:_});if((w=S?Jn(N,w):Wn(N,w)).cookies&&b()(w.cookies).length){var M,D=q()(M=b()(w.cookies)).call(M,(function(e,t){var n=w.cookies[t];return e+(e?"&":"")+Tn.a.serialize(t,n)}),"");w.headers.Cookie=D}return w.cookies&&delete w.cookies,Ue(w),w}var Zn=function(e){return e?e.replace(/\W/g,""):null};function Xn(e,t){return Qn.apply(this,arguments)}function Qn(){return(Qn=u()(s.a.mark((function e(t,n){var r,a,o,i,c,u,l,p,f,d,h,m,v=arguments;return s.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=v.length>2&&void 0!==v[2]?v[2]:{},a=r.returnEntireTree,o=r.baseDoc,i=r.requestInterceptor,c=r.responseInterceptor,u=r.parameterMacro,l=r.modelPropertyMacro,p=r.useCircularStructures,f={pathDiscriminator:n,baseDoc:o,requestInterceptor:i,responseInterceptor:c,parameterMacro:u,modelPropertyMacro:l,useCircularStructures:p},d=Object(En.d)({spec:t}),h=d.spec,e.next=6,Sn(Je()(Je()({},f),{},{spec:h,allowMetaPatches:!0,skipNormalization:!0}));case 6:return m=e.sent,!a&&k()(n)&&n.length&&(m.spec=Cn()(m.spec,n)||null),e.abrupt("return",m);case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var er=n(228);t.default=function(e){var t,n,r,a=e.configs,i=e.getConfigs;return{fn:{fetch:(t=Oe,n=a.preFetch,r=a.postFetch,r=r||function(e){return e},n=n||function(e){return e},function(e){return"string"==typeof e&&(e={url:e}),je.mergeInQueryOrForm(e),e=n(e),r(t(e))}),buildRequest:Gn,execute:Kn,resolve:Sn,resolveSubtree:function(e,t,n){var r;if(void 0===n){var a=i();n={modelPropertyMacro:a.modelPropertyMacro,parameterMacro:a.parameterMacro,requestInterceptor:a.requestInterceptor,responseInterceptor:a.responseInterceptor}}for(var s=arguments.length,c=new Array(s>3?s-3:0),u=3;u<s;u++)c[u-3]=arguments[u];return Xn.apply(void 0,o()(r=[e,t,n]).call(r,c))},serializeRes:ke,opId:En.e},statePlugins:{configs:{wrapActions:er}}}}},function(e,t,n){"use strict";n.r(t),n.d(t,"default",(function(){return u}));var r=n(131),a=n(112),o=n(235),i=n(236),s=n(237),c={getLocalConfig:function(){return Object(r.parseYamlConfig)('---\nurl: "https://petstore.swagger.io/v2/swagger.json"\ndom_id: "#swagger-ui"\nvalidatorUrl: "https://validator.swagger.io/validator"\n')}};function u(){return{statePlugins:{spec:{actions:o,selectors:c},configs:{reducers:s.default,actions:a,selectors:i}}}}},function(e,t,n){var r=n(330),a=n(151),o=n(612),i=n(47),s=n(344);e.exports=function(e,t,n){var c=i(e)?r:o;return n&&s(e,t,n)&&(t=void 0),c(e,a(t,3))}},function(e,t){e.exports=require("memoizee")},function(e,t,n){e.exports=n(658)},function(e,t,n){e.exports=n(663)},function(e,t,n){var r=n(360);e.exports=function(e,t,n){return null==e?e:r(e,t,n)}},function(e,t){e.exports=require("react-redux")},function(e,t,n){e.exports=n(733)},function(e,t){e.exports=function(){}},function(e,t){e.exports=require("querystring-browser")},function(e,t,n){var r=n(739),a=n(321),o=n(341),i=n(77);e.exports=function(e,t,n){return e=i(e),n=null==n?0:r(o(n),0,e.length),t=a(t),e.slice(n,n+t.length)==t}},function(e,t){e.exports=require("react-debounce-input")},function(e,t,n){var r=n(312),a=n(304),o=n(145),i=n(315);e.exports=function(e){return r(e)||a(e)||o(e)||i()},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){"use strict";var r=n(24),a=n(34),o=n(116),i=n(40),s=n(61),c=n(68),u=n(118),l=n(179),p=n(121),f=n(36),d=n(120),h=f("isConcatSpreadable"),m=9007199254740991,v="Maximum allowed index exceeded",g=d>=51||!a((function(){var e=[];return e[h]=!1,e.concat()[0]!==e})),y=p("concat"),b=function(e){if(!i(e))return!1;var t=e[h];return void 0!==t?!!t:o(e)};r({target:"Array",proto:!0,forced:!g||!y},{concat:function(e){var t,n,r,a,o,i=s(this),p=l(i,0),f=0;for(t=-1,r=arguments.length;t<r;t++)if(b(o=-1===t?i:arguments[t])){if(f+(a=c(o.length))>m)throw TypeError(v);for(n=0;n<a;n++,f++)n in o&&u(p,f,o[n])}else{if(f>=m)throw TypeError(v);u(p,f++,o)}return p.length=f,p}})},function(e,t,n){var r=n(44),a=n(34),o=n(178);e.exports=!r&&!a((function(){return 7!=Object.defineProperty(o("div"),"a",{get:function(){return 7}}).a}))},function(e,t,n){var r=n(34),a=/#|\.prototype\./,o=function(e,t){var n=s[i(e)];return n==u||n!=c&&("function"==typeof t?r(t):!!t)},i=o.normalize=function(e){return String(e).replace(a,".").toLowerCase()},s=o.data={},c=o.NATIVE="N",u=o.POLYFILL="P";e.exports=o},function(e,t,n){var r=n(182);e.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(e,t,n){"use strict";var r=n(24),a=n(38),o=n(62),i=n(81),s=n(44),c=n(182),u=n(284),l=n(34),p=n(48),f=n(116),d=n(40),h=n(46),m=n(61),v=n(58),g=n(140),y=n(90),b=n(92),E=n(122),x=n(187),S=n(416),w=n(188),j=n(89),O=n(60),C=n(138),_=n(59),A=n(93),k=n(180),I=n(144),P=n(123),T=n(141),R=n(36),N=n(189),M=n(43),D=n(82),q=n(69),B=n(75).forEach,L=I("hidden"),U="Symbol",V=R("toPrimitive"),z=q.set,F=q.getterFor(U),J=Object.prototype,W=a.Symbol,H=o("JSON","stringify"),$=j.f,Y=O.f,K=S.f,G=C.f,Z=k("symbols"),X=k("op-symbols"),Q=k("string-to-symbol-registry"),ee=k("symbol-to-string-registry"),te=k("wks"),ne=a.QObject,re=!ne||!ne.prototype||!ne.prototype.findChild,ae=s&&l((function(){return 7!=b(Y({},"a",{get:function(){return Y(this,"a",{value:7}).a}})).a}))?function(e,t,n){var r=$(J,t);r&&delete J[t],Y(e,t,n),r&&e!==J&&Y(J,t,r)}:Y,oe=function(e,t){var n=Z[e]=b(W.prototype);return z(n,{type:U,tag:e,description:t}),s||(n.description=t),n},ie=u?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof W},se=function(e,t,n){e===J&&se(X,t,n),h(e);var r=g(t,!0);return h(n),p(Z,r)?(n.enumerable?(p(e,L)&&e[L][r]&&(e[L][r]=!1),n=b(n,{enumerable:y(0,!1)})):(p(e,L)||Y(e,L,y(1,{})),e[L][r]=!0),ae(e,r,n)):Y(e,r,n)},ce=function(e,t){h(e);var n=v(t),r=E(n).concat(fe(n));return B(r,(function(t){s&&!ue.call(n,t)||se(e,t,n[t])})),e},ue=function(e){var t=g(e,!0),n=G.call(this,t);return!(this===J&&p(Z,t)&&!p(X,t))&&(!(n||!p(this,t)||!p(Z,t)||p(this,L)&&this[L][t])||n)},le=function(e,t){var n=v(e),r=g(t,!0);if(n!==J||!p(Z,r)||p(X,r)){var a=$(n,r);return!a||!p(Z,r)||p(n,L)&&n[L][r]||(a.enumerable=!0),a}},pe=function(e){var t=K(v(e)),n=[];return B(t,(function(e){p(Z,e)||p(P,e)||n.push(e)})),n},fe=function(e){var t=e===J,n=K(t?X:v(e)),r=[];return B(n,(function(e){!p(Z,e)||t&&!p(J,e)||r.push(Z[e])})),r};(c||(A((W=function(){if(this instanceof W)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=T(e),n=function(e){this===J&&n.call(X,e),p(this,L)&&p(this[L],t)&&(this[L][t]=!1),ae(this,t,y(1,e))};return s&&re&&ae(J,t,{configurable:!0,set:n}),oe(t,e)}).prototype,"toString",(function(){return F(this).tag})),A(W,"withoutSetter",(function(e){return oe(T(e),e)})),C.f=ue,O.f=se,j.f=le,x.f=S.f=pe,w.f=fe,N.f=function(e){return oe(R(e),e)},s&&(Y(W.prototype,"description",{configurable:!0,get:function(){return F(this).description}}),i||A(J,"propertyIsEnumerable",ue,{unsafe:!0}))),r({global:!0,wrap:!0,forced:!c,sham:!c},{Symbol:W}),B(E(te),(function(e){M(e)})),r({target:U,stat:!0,forced:!c},{for:function(e){var t=String(e);if(p(Q,t))return Q[t];var n=W(t);return Q[t]=n,ee[n]=t,n},keyFor:function(e){if(!ie(e))throw TypeError(e+" is not a symbol");if(p(ee,e))return ee[e]},useSetter:function(){re=!0},useSimple:function(){re=!1}}),r({target:"Object",stat:!0,forced:!c,sham:!s},{create:function(e,t){return void 0===t?b(e):ce(b(e),t)},defineProperty:se,defineProperties:ce,getOwnPropertyDescriptor:le}),r({target:"Object",stat:!0,forced:!c},{getOwnPropertyNames:pe,getOwnPropertySymbols:fe}),r({target:"Object",stat:!0,forced:l((function(){w.f(1)}))},{getOwnPropertySymbols:function(e){return w.f(m(e))}}),H)&&r({target:"JSON",stat:!0,forced:!c||l((function(){var e=W();return"[null]"!=H([e])||"{}"!=H({a:e})||"{}"!=H(Object(e))}))},{stringify:function(e,t,n){for(var r,a=[e],o=1;arguments.length>o;)a.push(arguments[o++]);if(r=t,(d(t)||void 0!==e)&&!ie(e))return f(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!ie(t))return t}),a[1]=t,H.apply(null,a)}});W.prototype[V]||_(W.prototype,V,W.prototype.valueOf),D(W,U),P[L]=!0},function(e,t,n){var r=n(48),a=n(58),o=n(184).indexOf,i=n(123);e.exports=function(e,t){var n,s=a(e),c=0,u=[];for(n in s)!r(i,n)&&r(s,n)&&u.push(n);for(;t.length>c;)r(s,n=t[c++])&&(~o(u,n)||u.push(n));return u}},function(e,t,n){var r=n(62);e.exports=r("document","documentElement")},function(e,t,n){var r=n(38),a=n(289),o=r.WeakMap;e.exports="function"==typeof o&&/native code/.test(a(o))},function(e,t,n){var r=n(181),a=Function.toString;"function"!=typeof r.inspectSource&&(r.inspectSource=function(e){return a.call(e)}),e.exports=r.inspectSource},function(e,t,n){n(43)("iterator")},function(e,t,n){var r=n(117),a=n(104),o=function(e){return function(t,n){var o,i,s=String(a(t)),c=r(n),u=s.length;return c<0||c>=u?e?"":void 0:(o=s.charCodeAt(c))<55296||o>56319||c+1===u||(i=s.charCodeAt(c+1))<56320||i>57343?e?s.charAt(c):o:e?s.slice(c,c+2):i-56320+(o-55296<<10)+65536}};e.exports={codeAt:o(!1),charAt:o(!0)}},function(e,t,n){"use strict";var r=n(293).IteratorPrototype,a=n(92),o=n(90),i=n(82),s=n(94),c=function(){return this};e.exports=function(e,t,n){var u=t+" Iterator";return e.prototype=a(r,{next:o(1,n)}),i(e,u,!1,!0),s[u]=c,e}},function(e,t,n){"use strict";var r,a,o,i=n(34),s=n(124),c=n(59),u=n(48),l=n(36),p=n(81),f=l("iterator"),d=!1;[].keys&&("next"in(o=[].keys())?(a=s(s(o)))!==Object.prototype&&(r=a):d=!0);var h=null==r||i((function(){var e={};return r[f].call(e)!==e}));h&&(r={}),p&&!h||u(r,f)||c(r,f,(function(){return this})),e.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:d}},function(e,t,n){var r=n(34);e.exports=!r((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}))},function(e,t,n){var r=n(448),a=Array.prototype;e.exports=function(e){var t=e.filter;return e===a||e instanceof Array&&t===a.filter?r:t}},function(e,t,n){n(451);var r=n(31);e.exports=r.Object.keys},function(e,t,n){n(456);var r=n(31).Object,a=e.exports=function(e,t,n){return r.defineProperty(e,t,n)};r.defineProperty.sham&&(a.sham=!0)},function(e,t,n){"use strict";var r=n(67),a=n(40),o=[].slice,i={},s=function(e,t,n){if(!(t in i)){for(var r=[],a=0;a<t;a++)r[a]="a["+a+"]";i[t]=Function("C,a","return new C("+r.join(",")+")")}return i[t](e,n)};e.exports=Function.bind||function(e){var t=r(this),n=o.call(arguments,1),i=function(){var r=n.concat(o.call(arguments));return this instanceof i?s(t,r.length,r):t.apply(e,r)};return a(t.prototype)&&(i.prototype=t.prototype),i}},function(e,t,n){n(462);var r=n(31);e.exports=r.Object.assign},function(e,t,n){"use strict";var r=n(44),a=n(34),o=n(122),i=n(188),s=n(138),c=n(61),u=n(139),l=Object.assign,p=Object.defineProperty;e.exports=!l||a((function(){if(r&&1!==l({b:1},l(p({},"a",{enumerable:!0,get:function(){p(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),a="abcdefghijklmnopqrst";return e[n]=7,a.split("").forEach((function(e){t[e]=e})),7!=l({},e)[n]||o(l({},t)).join("")!=a}))?function(e,t){for(var n=c(e),a=arguments.length,l=1,p=i.f,f=s.f;a>l;)for(var d,h=u(arguments[l++]),m=p?o(h).concat(p(h)):o(h),v=m.length,g=0;v>g;)d=m[g++],r&&!f.call(h,d)||(n[d]=h[d]);return n}:l},function(e,t,n){var r=n(464),a=Array.prototype;e.exports=function(e){var t=e.slice;return e===a||e instanceof Array&&t===a.slice?r:t}},function(e,t,n){n(467);var r=n(31);e.exports=r.Array.isArray},function(e,t){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(137),a=n(305),o=n(306);e.exports=function(e){if(void 0!==r&&a(Object(e)))return o(e)},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(483)},function(e,t,n){e.exports=n(485)},function(e,t,n){n(83),n(486);var r=n(31);e.exports=r.Array.from},function(e,t,n){"use strict";var r=n(91),a=n(61),o=n(487),i=n(310),s=n(68),c=n(118),u=n(126);e.exports=function(e){var t,n,l,p,f,d,h=a(e),m="function"==typeof this?this:Array,v=arguments.length,g=v>1?arguments[1]:void 0,y=void 0!==g,b=u(h),E=0;if(y&&(g=r(g,v>2?arguments[2]:void 0,2)),null==b||m==Array&&i(b))for(n=new m(t=s(h.length));t>E;E++)d=y?g(h[E],E):h[E],c(n,E,d);else for(f=(p=b.call(h)).next,n=new m;!(l=f.call(p)).done;E++)d=y?o(p,g,[l.value,E],!0):l.value,c(n,E,d);return n.length=E,n}},function(e,t,n){var r=n(46);e.exports=function(e){var t=e.return;if(void 0!==t)return r(t.call(e)).value}},function(e,t,n){var r=n(36),a=n(94),o=r("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(a.Array===e||i[o]===e)}},function(e,t,n){var r=n(36)("iterator"),a=!1;try{var o=0,i={next:function(){return{done:!!o++}},return:function(){a=!0}};i[r]=function(){return this},Array.from(i,(function(){throw 2}))}catch(e){}e.exports=function(e,t){if(!t&&!a)return!1;var n=!1;try{var o={};o[r]=function(){return{next:function(){return{done:n=!0}}}},e(o)}catch(e){}return n}},function(e,t,n){var r=n(195);e.exports=function(e){if(r(e))return e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(492)},function(e,t,n){var r=n(46),a=n(126);e.exports=function(e){var t=a(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return r(t.call(e))}},function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){n(63);var r=n(498),a=n(74),o=Array.prototype,i={DOMTokenList:!0,NodeList:!0};e.exports=function(e){var t=e.forEach;return e===o||e instanceof Array&&t===o.forEach||i.hasOwnProperty(a(e))?r:t}},function(e,t,n){var r=n(516);e.exports=function(e){if(r(e))throw TypeError("The method doesn't accept regular expressions");return e}},function(e,t,n){var r=n(36)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[r]=!1,"/./"[e](t)}catch(e){}}return!1}},function(e,t,n){var r=n(518),a=Array.prototype;e.exports=function(e){var t=e.indexOf;return e===a||e instanceof Array&&t===a.indexOf?r:t}},function(e,t){e.exports="\t\n\v\f\r \u2028\u2029\ufeff"},function(e,t,n){var r=n(105),a=n(323),o=n(47),i=n(146),s=r?r.prototype:void 0,c=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(o(t))return a(t,e)+"";if(i(t))return c?c.call(t):"";var n=t+"";return"0"==n&&1/t==-Infinity?"-0":n}},function(e,t,n){(function(t){var n="object"==typeof t&&t&&t.Object===Object&&t;e.exports=n}).call(this,n(177))},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,a=Array(r);++n<r;)a[n]=t(e[n],n,e);return a}},function(e,t){e.exports=function(e,t,n){var r=-1,a=e.length;t<0&&(t=-t>a?0:a+t),(n=n>a?a:n)<0&&(n+=a),a=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(a);++r<a;)o[r]=e[r+t];return o}},function(e,t){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");e.exports=function(e){return n.test(e)}},function(e,t){e.exports=function(e,t,n,r){var a=-1,o=null==e?0:e.length;for(r&&o&&(n=e[++a]);++a<o;)n=t(n,e[a],a,e);return n}},function(e,t){var n=Function.prototype.toString;e.exports=function(e){if(null!=e){try{return n.call(e)}catch(e){}try{return e+""}catch(e){}}return""}},function(e,t,n){var r=n(579),a=n(76);e.exports=function e(t,n,o,i,s){return t===n||(null==t||null==n||!a(t)&&!a(n)?t!=t&&n!=n:r(t,n,o,i,e,s))}},function(e,t,n){var r=n(580),a=n(330),o=n(583);e.exports=function(e,t,n,i,s,c){var u=1&n,l=e.length,p=t.length;if(l!=p&&!(u&&p>l))return!1;var f=c.get(e),d=c.get(t);if(f&&d)return f==t&&d==e;var h=-1,m=!0,v=2&n?new r:void 0;for(c.set(e,t),c.set(t,e);++h<l;){var g=e[h],y=t[h];if(i)var b=u?i(y,g,h,t,e,c):i(g,y,h,e,t,c);if(void 0!==b){if(b)continue;m=!1;break}if(v){if(!a(t,(function(e,t){if(!o(v,t)&&(g===e||s(g,e,n,i,c)))return v.push(t)}))){m=!1;break}}else if(g!==y&&!s(g,y,n,i,c)){m=!1;break}}return c.delete(e),c.delete(t),m}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}},function(e,t,n){var r=n(64).Uint8Array;e.exports=r},function(e,t,n){var r=n(333),a=n(200),o=n(98);e.exports=function(e){return r(e,o,a)}},function(e,t,n){var r=n(199),a=n(47);e.exports=function(e,t,n){var o=t(e);return a(e)?o:r(o,n(e))}},function(e,t){e.exports=function(){return[]}},function(e,t,n){var r=n(589),a=n(152),o=n(47),i=n(153),s=n(154),c=n(202),u=Object.prototype.hasOwnProperty;e.exports=function(e,t){var n=o(e),l=!n&&a(e),p=!n&&!l&&i(e),f=!n&&!l&&!p&&c(e),d=n||l||p||f,h=d?r(e.length,String):[],m=h.length;for(var v in e)!t&&!u.call(e,v)||d&&("length"==v||p&&("offset"==v||"parent"==v)||f&&("buffer"==v||"byteLength"==v||"byteOffset"==v)||s(v,m))||h.push(v);return h}},function(e,t,n){var r=n(127),a=n(593),o=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return a(e);var t=[];for(var n in Object(e))o.call(e,n)&&"constructor"!=n&&t.push(n);return t}},function(e,t){e.exports=function(e,t){return function(n){return e(t(n))}}},function(e,t,n){var r=n(51);e.exports=function(e){return e==e&&!r(e)}},function(e,t){e.exports=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}},function(e,t,n){var r=n(602),a=n(603);e.exports=function(e,t){return null!=e&&a(e,t,r)}},function(e,t,n){var r=n(609);e.exports=function(e){var t=r(e),n=t%1;return t==t?n?t-n:t:0}},function(e,t,n){var r=n(610),a=n(51),o=n(146),i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,u=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(o(e))return NaN;if(a(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=a(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var n=s.test(e);return n||c.test(e)?u(e.slice(2),n?2:8):i.test(e)?NaN:+e}},function(e,t,n){var r=n(613),a=n(616)(r);e.exports=a},function(e,t,n){var r=n(101),a=n(99),o=n(154),i=n(51);e.exports=function(e,t,n){if(!i(n))return!1;var s=typeof t;return!!("number"==s?a(n)&&o(t,n.length):"string"==s&&t in n)&&r(n[t],e)}},function(e,t,n){e.exports=n(625)},function(e,t,n){e.exports=n(626)},function(e,t,n){e.exports=n(630)},function(e,t,n){e.exports=n(644)},function(e,t,n){n(350),n(143),n(648),n(357),n(358),n(652),n(83),n(63);var r=n(31);e.exports=r.Promise},function(e,t,n){"use strict";var r=n(24),a=n(124),o=n(192),i=n(92),s=n(59),c=n(90),u=n(100),l=function(e,t){var n=this;if(!(n instanceof l))return new l(e,t);o&&(n=o(new Error(void 0),a(n))),void 0!==t&&s(n,"message",String(t));var r=[];return u(e,r.push,{that:r}),s(n,"errors",r),n};l.prototype=i(Error.prototype,{constructor:c(5,l),message:c(5,""),name:c(5,"AggregateError")}),r({global:!0},{AggregateError:l})},function(e,t,n){var r=n(38);e.exports=r.Promise},function(e,t,n){"use strict";var r=n(62),a=n(60),o=n(36),i=n(44),s=o("species");e.exports=function(e){var t=r(e),n=a.f;i&&t&&!t[s]&&n(t,s,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(46),a=n(67),o=n(36)("species");e.exports=function(e,t){var n,i=r(e).constructor;return void 0===i||null==(n=r(i)[o])?t:a(n)}},function(e,t,n){var r,a,o,i=n(38),s=n(34),c=n(91),u=n(287),l=n(178),p=n(355),f=n(119),d=i.location,h=i.setImmediate,m=i.clearImmediate,v=i.process,g=i.MessageChannel,y=i.Dispatch,b=0,E={},x="onreadystatechange",S=function(e){if(E.hasOwnProperty(e)){var t=E[e];delete E[e],t()}},w=function(e){return function(){S(e)}},j=function(e){S(e.data)},O=function(e){i.postMessage(e+"",d.protocol+"//"+d.host)};h&&m||(h=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return E[++b]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},r(b),b},m=function(e){delete E[e]},f?r=function(e){v.nextTick(w(e))}:y&&y.now?r=function(e){y.now(w(e))}:g&&!p?(o=(a=new g).port2,a.port1.onmessage=j,r=c(o.postMessage,o,1)):i.addEventListener&&"function"==typeof postMessage&&!i.importScripts&&d&&"file:"!==d.protocol&&!s(O)?(r=O,i.addEventListener("message",j,!1)):r=x in l("script")?function(e){u.appendChild(l("script")).onreadystatechange=function(){u.removeChild(this),S(e)}}:function(e){setTimeout(w(e),0)}),e.exports={set:h,clear:m}},function(e,t,n){var r=n(142);e.exports=/(iphone|ipod|ipad).*applewebkit/i.test(r)},function(e,t,n){var r=n(46),a=n(40),o=n(130);e.exports=function(e,t){if(r(e),a(t)&&t.constructor===e)return t;var n=o.f(e);return(0,n.resolve)(t),n.promise}},function(e,t,n){"use strict";var r=n(24),a=n(67),o=n(130),i=n(156),s=n(100);r({target:"Promise",stat:!0},{allSettled:function(e){var t=this,n=o.f(t),r=n.resolve,c=n.reject,u=i((function(){var n=a(t.resolve),o=[],i=0,c=1;s(e,(function(e){var a=i++,s=!1;o.push(void 0),c++,n.call(t,e).then((function(e){s||(s=!0,o[a]={status:"fulfilled",value:e},--c||r(o))}),(function(e){s||(s=!0,o[a]={status:"rejected",reason:e},--c||r(o))}))})),--c||r(o)}));return u.error&&c(u.value),n.promise}})},function(e,t,n){"use strict";var r=n(24),a=n(67),o=n(62),i=n(130),s=n(156),c=n(100),u="No one promise resolved";r({target:"Promise",stat:!0},{any:function(e){var t=this,n=i.f(t),r=n.resolve,l=n.reject,p=s((function(){var n=a(t.resolve),i=[],s=0,p=1,f=!1;c(e,(function(e){var a=s++,c=!1;i.push(void 0),p++,n.call(t,e).then((function(e){c||f||(f=!0,r(e))}),(function(e){c||f||(c=!0,i[a]=e,--p||l(new(o("AggregateError"))(i,u)))}))})),--p||l(new(o("AggregateError"))(i,u))}));return p.error&&l(p.value),n.promise}})},function(e,t,n){var r=n(44),a=n(122),o=n(58),i=n(138).f,s=function(e){return function(t){for(var n,s=o(t),c=a(s),u=c.length,l=0,p=[];u>l;)n=c[l++],r&&!i.call(s,n)||p.push(e?[n,s[n]]:s[n]);return p}};e.exports={entries:s(!0),values:s(!1)}},function(e,t,n){var r=n(157),a=n(106),o=n(154),i=n(51),s=n(107);e.exports=function(e,t,n,c){if(!i(e))return e;for(var u=-1,l=(t=a(t,e)).length,p=l-1,f=e;null!=f&&++u<l;){var d=s(t[u]),h=n;if("__proto__"===d||"constructor"===d||"prototype"===d)return e;if(u!=p){var m=f[d];void 0===(h=c?c(m,d,f):void 0)&&(h=i(m)?m:o(t[u+1])?[]:{})}r(f,d,h),f=f[d]}return e}},function(e,t,n){var r=n(362);e.exports=function(e,t,n){"__proto__"==t&&r?r(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}},function(e,t,n){var r=n(97),a=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=a},function(e,t,n){n(671);var r=n(31).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){e.exports=n(673)},function(e,t,n){e.exports=n(676)},function(e,t,n){var r=n(198),a=n(685),o=n(157),i=n(686),s=n(687),c=n(690),u=n(691),l=n(692),p=n(693),f=n(332),d=n(368),h=n(128),m=n(694),v=n(695),g=n(700),y=n(47),b=n(153),E=n(702),x=n(51),S=n(704),w=n(98),j=n(208),O="[object Arguments]",C="[object Function]",_="[object Object]",A={};A[O]=A["[object Array]"]=A["[object ArrayBuffer]"]=A["[object DataView]"]=A["[object Boolean]"]=A["[object Date]"]=A["[object Float32Array]"]=A["[object Float64Array]"]=A["[object Int8Array]"]=A["[object Int16Array]"]=A["[object Int32Array]"]=A["[object Map]"]=A["[object Number]"]=A[_]=A["[object RegExp]"]=A["[object Set]"]=A["[object String]"]=A["[object Symbol]"]=A["[object Uint8Array]"]=A["[object Uint8ClampedArray]"]=A["[object Uint16Array]"]=A["[object Uint32Array]"]=!0,A["[object Error]"]=A[C]=A["[object WeakMap]"]=!1,e.exports=function e(t,n,k,I,P,T){var R,N=1&n,M=2&n,D=4&n;if(k&&(R=P?k(t,I,P,T):k(t)),void 0!==R)return R;if(!x(t))return t;var q=y(t);if(q){if(R=m(t),!N)return u(t,R)}else{var B=h(t),L=B==C||"[object GeneratorFunction]"==B;if(b(t))return c(t,N);if(B==_||B==O||L&&!P){if(R=M||L?{}:g(t),!N)return M?p(t,s(R,t)):l(t,i(R,t))}else{if(!A[B])return P?t:{};R=v(t,B,N)}}T||(T=new r);var U=T.get(t);if(U)return U;T.set(t,R),S(t)?t.forEach((function(r){R.add(e(r,n,k,r,t,T))})):E(t)&&t.forEach((function(r,a){R.set(a,e(r,n,k,a,t,T))}));var V=q?void 0:(D?M?d:f:M?j:w)(t);return a(V||t,(function(r,a){V&&(r=t[a=r]),o(R,a,e(r,n,k,a,t,T))})),R}},function(e,t,n){var r=n(199),a=n(209),o=n(200),i=n(334),s=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)r(t,o(e)),e=a(e);return t}:i;e.exports=s},function(e,t,n){var r=n(333),a=n(367),o=n(208);e.exports=function(e){return r(e,o,a)}},function(e,t,n){var r=n(710),a=n(370),o=n(371);e.exports=function(e){return o(a(e,void 0,r),e+"")}},function(e,t,n){var r=n(713),a=Math.max;e.exports=function(e,t,n){return t=a(void 0===t?e.length-1:t,0),function(){for(var o=arguments,i=-1,s=a(o.length-t,0),c=Array(s);++i<s;)c[i]=o[t+i];i=-1;for(var u=Array(t+1);++i<t;)u[i]=o[i];return u[t]=n(c),r(e,this,u)}}},function(e,t,n){var r=n(714),a=n(716)(r);e.exports=a},function(e,t,n){"use strict";var r=n(24),a=n(38),o=n(158),i=n(34),s=n(59),c=n(100),u=n(108),l=n(40),p=n(82),f=n(60).f,d=n(75).forEach,h=n(44),m=n(69),v=m.set,g=m.getterFor;e.exports=function(e,t,n){var m,y=-1!==e.indexOf("Map"),b=-1!==e.indexOf("Weak"),E=y?"set":"add",x=a[e],S=x&&x.prototype,w={};if(h&&"function"==typeof x&&(b||S.forEach&&!i((function(){(new x).entries().next()})))){m=t((function(t,n){v(u(t,m,e),{type:e,collection:new x}),null!=n&&c(n,t[E],{that:t,AS_ENTRIES:y})}));var j=g(e);d(["add","clear","delete","forEach","get","has","set","keys","values","entries"],(function(e){var t="add"==e||"set"==e;!(e in S)||b&&"clear"==e||s(m.prototype,e,(function(n,r){var a=j(this).collection;if(!t&&b&&!l(n))return"get"==e&&void 0;var o=a[e](0===n?0:n,r);return t?this:o}))})),b||f(m.prototype,"size",{configurable:!0,get:function(){return j(this).collection.size}})}else m=n.getConstructor(t,e,y,E),o.REQUIRED=!0;return p(m,e,!1,!0),w[e]=m,r({global:!0,forced:!0},w),b||n.setStrong(m,e,y),m}},function(e,t,n){var r=n(34),a=n(36),o=n(81),i=a("iterator");e.exports=!r((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),n+=r+e})),o&&!e.toJSON||!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[i]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host}))},function(e,t,n){"use strict";n(125);var r=n(24),a=n(62),o=n(373),i=n(93),s=n(129),c=n(82),u=n(292),l=n(69),p=n(108),f=n(48),d=n(91),h=n(74),m=n(46),v=n(40),g=n(92),y=n(90),b=n(314),E=n(126),x=n(36),S=a("fetch"),w=a("Headers"),j=x("iterator"),O="URLSearchParams",C="URLSearchParamsIterator",_=l.set,A=l.getterFor(O),k=l.getterFor(C),I=/\+/g,P=Array(4),T=function(e){return P[e-1]||(P[e-1]=RegExp("((?:%[\\da-f]{2}){"+e+"})","gi"))},R=function(e){try{return decodeURIComponent(e)}catch(t){return e}},N=function(e){var t=e.replace(I," "),n=4;try{return decodeURIComponent(t)}catch(e){for(;n;)t=t.replace(T(n--),R);return t}},M=/[!'()~]|%20/g,D={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},q=function(e){return D[e]},B=function(e){return encodeURIComponent(e).replace(M,q)},L=function(e,t){if(t)for(var n,r,a=t.split("&"),o=0;o<a.length;)(n=a[o++]).length&&(r=n.split("="),e.push({key:N(r.shift()),value:N(r.join("="))}))},U=function(e){this.entries.length=0,L(this.entries,e)},V=function(e,t){if(e<t)throw TypeError("Not enough arguments")},z=u((function(e,t){_(this,{type:C,iterator:b(A(e).entries),kind:t})}),"Iterator",(function(){var e=k(this),t=e.kind,n=e.iterator.next(),r=n.value;return n.done||(n.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),n})),F=function(){p(this,F,O);var e,t,n,r,a,o,i,s,c,u=arguments.length>0?arguments[0]:void 0,l=this,d=[];if(_(l,{type:O,entries:d,updateURL:function(){},updateSearchParams:U}),void 0!==u)if(v(u))if("function"==typeof(e=E(u)))for(n=(t=e.call(u)).next;!(r=n.call(t)).done;){if((i=(o=(a=b(m(r.value))).next).call(a)).done||(s=o.call(a)).done||!o.call(a).done)throw TypeError("Expected sequence with length 2");d.push({key:i.value+"",value:s.value+""})}else for(c in u)f(u,c)&&d.push({key:c,value:u[c]+""});else L(d,"string"==typeof u?"?"===u.charAt(0)?u.slice(1):u:u+"")},J=F.prototype;s(J,{append:function(e,t){V(arguments.length,2);var n=A(this);n.entries.push({key:e+"",value:t+""}),n.updateURL()},delete:function(e){V(arguments.length,1);for(var t=A(this),n=t.entries,r=e+"",a=0;a<n.length;)n[a].key===r?n.splice(a,1):a++;t.updateURL()},get:function(e){V(arguments.length,1);for(var t=A(this).entries,n=e+"",r=0;r<t.length;r++)if(t[r].key===n)return t[r].value;return null},getAll:function(e){V(arguments.length,1);for(var t=A(this).entries,n=e+"",r=[],a=0;a<t.length;a++)t[a].key===n&&r.push(t[a].value);return r},has:function(e){V(arguments.length,1);for(var t=A(this).entries,n=e+"",r=0;r<t.length;)if(t[r++].key===n)return!0;return!1},set:function(e,t){V(arguments.length,1);for(var n,r=A(this),a=r.entries,o=!1,i=e+"",s=t+"",c=0;c<a.length;c++)(n=a[c]).key===i&&(o?a.splice(c--,1):(o=!0,n.value=s));o||a.push({key:i,value:s}),r.updateURL()},sort:function(){var e,t,n,r=A(this),a=r.entries,o=a.slice();for(a.length=0,n=0;n<o.length;n++){for(e=o[n],t=0;t<n;t++)if(a[t].key>e.key){a.splice(t,0,e);break}t===n&&a.push(e)}r.updateURL()},forEach:function(e){for(var t,n=A(this).entries,r=d(e,arguments.length>1?arguments[1]:void 0,3),a=0;a<n.length;)r((t=n[a++]).value,t.key,this)},keys:function(){return new z(this,"keys")},values:function(){return new z(this,"values")},entries:function(){return new z(this,"entries")}},{enumerable:!0}),i(J,j,J.entries),i(J,"toString",(function(){for(var e,t=A(this).entries,n=[],r=0;r<t.length;)e=t[r++],n.push(B(e.key)+"="+B(e.value));return n.join("&")}),{enumerable:!0}),c(F,O),r({global:!0,forced:!o},{URLSearchParams:F}),o||"function"!=typeof S||"function"!=typeof w||r({global:!0,enumerable:!0,forced:!0},{fetch:function(e){var t,n,r,a=[e];return arguments.length>1&&(v(t=arguments[1])&&(n=t.body,h(n)===O&&((r=t.headers?new w(t.headers):new w).has("content-type")||r.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),t=g(t,{body:y(0,String(n)),headers:y(0,r)}))),a.push(t)),S.apply(this,a)}}),e.exports={URLSearchParams:F,getState:A}},function(e,t){e.exports="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwcHgiICBoZWlnaHQ9IjIwMHB4IiAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgcHJlc2VydmVBc3BlY3RSYXRpbz0ieE1pZFlNaWQiIGNsYXNzPSJsZHMtcm9sbGluZyIgc3R5bGU9ImJhY2tncm91bmQtaW1hZ2U6IG5vbmU7IGJhY2tncm91bmQtcG9zaXRpb246IGluaXRpYWwgaW5pdGlhbDsgYmFja2dyb3VuZC1yZXBlYXQ6IGluaXRpYWwgaW5pdGlhbDsiPjxjaXJjbGUgY3g9IjUwIiBjeT0iNTAiIGZpbGw9Im5vbmUiIG5nLWF0dHItc3Ryb2tlPSJ7e2NvbmZpZy5jb2xvcn19IiBuZy1hdHRyLXN0cm9rZS13aWR0aD0ie3tjb25maWcud2lkdGh9fSIgbmctYXR0ci1yPSJ7e2NvbmZpZy5yYWRpdXN9fSIgbmctYXR0ci1zdHJva2UtZGFzaGFycmF5PSJ7e2NvbmZpZy5kYXNoYXJyYXl9fSIgc3Ryb2tlPSIjNTU1NTU1IiBzdHJva2Utd2lkdGg9IjEwIiByPSIzNSIgc3Ryb2tlLWRhc2hhcnJheT0iMTY0LjkzMzYxNDMxMzQ2NDE1IDU2Ljk3Nzg3MTQzNzgyMTM4Ij48YW5pbWF0ZVRyYW5zZm9ybSBhdHRyaWJ1dGVOYW1lPSJ0cmFuc2Zvcm0iIHR5cGU9InJvdGF0ZSIgY2FsY01vZGU9ImxpbmVhciIgdmFsdWVzPSIwIDUwIDUwOzM2MCA1MCA1MCIga2V5VGltZXM9IjA7MSIgZHVyPSIxcyIgYmVnaW49IjBzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSI+PC9hbmltYXRlVHJhbnNmb3JtPjwvY2lyY2xlPjwvc3ZnPgo="},function(e,t){e.exports=require("redux-immutable")},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function a(e){return null===e?"null":void 0===e?"undefined":"object"===(void 0===e?"undefined":r(e))?Array.isArray(e)?"array":"object":void 0===e?"undefined":r(e)}function o(e){return"object"===a(e)?s(e):"array"===a(e)?i(e):e}function i(e){return e.map(o)}function s(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=o(e[n]));return t}function c(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r={arrayBehaviour:n.arrayBehaviour||"replace"},o=t.map((function(e){return e||{}})),u=e||{},l=0;l<o.length;l++)for(var p=o[l],f=Object.keys(p),d=0;d<f.length;d++){var h=f[d],m=p[h],v=a(m),g=a(u[h]);if("object"===v)if("undefined"!==g){var y="object"===g?u[h]:{};u[h]=c({},[y,s(m)],r)}else u[h]=s(m);else if("array"===v)if("array"===g){var b=i(m);u[h]="merge"===r.arrayBehaviour?u[h].concat(b):b}else u[h]=i(m);else u[h]=m}return u}e.exports=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return c(e,n)},e.exports.noMutate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return c({},t)},e.exports.withOptions=function(e,t,n){return c(e,t,n)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.sanitizeUrl=void 0;var r=/^(%20|\s)*(javascript|data|vbscript)/im,a=/[^\x20-\x7EÀ-ž]/gim,o=/^([^:]+):/gm,i=[".","/"];t.sanitizeUrl=function(e){if(!e)return"about:blank";var t=e.replace(a,"").trim();if(function(e){return i.indexOf(e[0])>-1}(t))return t;var n=t.match(o);if(!n)return t;var s=n[0];return r.test(s)?"about:blank":t}},function(e,t,n){var r=n(534),a=n(542)((function(e,t,n){return t=t.toLowerCase(),e+(n?r(t):t)}));e.exports=a},function(e,t,n){(function(t){var r=n(618),a=n(619).Stream;function o(e,t,n){n=n||0;var a,i,s=(a=t,new Array(n||0).join(a||"")),c=e;if("object"==typeof e&&((c=e[i=Object.keys(e)[0]])&&c._elem))return c._elem.name=i,c._elem.icount=n,c._elem.indent=t,c._elem.indents=s,c._elem.interrupt=c,c._elem;var u,l=[],p=[];function f(e){Object.keys(e).forEach((function(t){l.push(function(e,t){return e+'="'+r(t)+'"'}(t,e[t]))}))}switch(typeof c){case"object":if(null===c)break;c._attr&&f(c._attr),c._cdata&&p.push(("<![CDATA["+c._cdata).replace(/\]\]>/g,"]]]]><![CDATA[>")+"]]>"),c.forEach&&(u=!1,p.push(""),c.forEach((function(e){"object"==typeof e?"_attr"==Object.keys(e)[0]?f(e._attr):p.push(o(e,t,n+1)):(p.pop(),u=!0,p.push(r(e)))})),u||p.push(""));break;default:p.push(r(c))}return{name:i,interrupt:!1,attributes:l,content:p,icount:n,indents:s,indent:t}}function i(e,t,n){if("object"!=typeof t)return e(!1,t);var r=t.interrupt?1:t.content.length;function a(){for(;t.content.length;){var a=t.content.shift();if(void 0!==a){if(o(a))return;i(e,a)}}e(!1,(r>1?t.indents:"")+(t.name?"</"+t.name+">":"")+(t.indent&&!n?"\n":"")),n&&n()}function o(t){return!!t.interrupt&&(t.interrupt.append=e,t.interrupt.end=a,t.interrupt=!1,e(!0),!0)}if(e(!1,t.indents+(t.name?"<"+t.name:"")+(t.attributes.length?" "+t.attributes.join(" "):"")+(r?t.name?">":"":t.name?"/>":"")+(t.indent&&r>1?"\n":"")),!r)return e(!1,t.indent?"\n":"");o(t)||a()}e.exports=function(e,n){"object"!=typeof n&&(n={indent:n});var r,s,c=n.stream?new a:null,u="",l=!1,p=n.indent?!0===n.indent?" ":n.indent:"",f=!0;function d(e){f?t.nextTick(e):e()}function h(e,t){if(void 0!==t&&(u+=t),e&&!l&&(c=c||new a,l=!0),e&&l){var n=u;d((function(){c.emit("data",n)})),u=""}}function m(e,t){i(h,o(e,p,p?1:0),t)}function v(){if(c){var e=u;d((function(){c.emit("data",e),c.emit("end"),c.readable=!1,c.emit("close")}))}}return d((function(){f=!1})),n.declaration&&(r=n.declaration,s={version:"1.0",encoding:r.encoding||"UTF-8"},r.standalone&&(s.standalone=r.standalone),m({"?xml":{_attr:s}}),u=u.replace("/>","?>")),e&&e.forEach?e.forEach((function(t,n){var r;n+1===e.length&&(r=v),m(t,r)})):m(e,v),c?(c.readable=!0,c):u},e.exports.element=e.exports.Element=function(){var e=Array.prototype.slice.call(arguments),t={_elem:o(e),push:function(e){if(!this.append)throw new Error("not assigned to a parent!");var t=this,n=this._elem.indent;i(this.append,o(e,n,this._elem.icount+(n?1:0)),(function(){t.append(!0)}))},close:function(e){void 0!==e&&this.push(e),this.end&&this.end()}};return t}}).call(this,n(617))},function(e,t){e.exports=require("css.escape")},function(e,t){e.exports=require("randombytes")},function(e,t){e.exports=require("sha.js")},function(e,t,n){var r=n(326),a=n(343),o=n(151),i=n(624),s=n(47);e.exports=function(e,t,n){var c=s(e)?r:i,u=arguments.length<3;return c(e,o(t,4),n,u,a)}},function(e,t,n){var r=n(51),a=n(666),o=n(342),i=Math.max,s=Math.min;e.exports=function(e,t,n){var c,u,l,p,f,d,h=0,m=!1,v=!1,g=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function y(t){var n=c,r=u;return c=u=void 0,h=t,p=e.apply(r,n)}function b(e){return h=e,f=setTimeout(x,t),m?y(e):p}function E(e){var n=e-d;return void 0===d||n>=t||n<0||v&&e-h>=l}function x(){var e=a();if(E(e))return S(e);f=setTimeout(x,function(e){var n=t-(e-d);return v?s(n,l-(e-h)):n}(e))}function S(e){return f=void 0,g&&c?y(e):(c=u=void 0,p)}function w(){var e=a(),n=E(e);if(c=arguments,u=this,d=e,n){if(void 0===f)return b(d);if(v)return clearTimeout(f),f=setTimeout(x,t),y(d)}return void 0===f&&(f=setTimeout(x,t)),p}return t=o(t)||0,r(n)&&(m=!!n.leading,l=(v="maxWait"in n)?i(o(n.maxWait)||0,t):l,g="trailing"in n?!!n.trailing:g),w.cancel=function(){void 0!==f&&clearTimeout(f),h=0,c=d=u=f=void 0},w.flush=function(){return void 0===f?p:S(a())},w}},function(e,t){e.exports=require("react-dom")},function(e,t,n){var r=n(323),a=n(366),o=n(706),i=n(106),s=n(109),c=n(709),u=n(369),l=n(368),p=u((function(e,t){var n={};if(null==e)return n;var u=!1;t=r(t,(function(t){return t=i(t,e),u||(u=t.length>1),t})),s(e,l(e),n),u&&(n=a(n,7,c));for(var p=t.length;p--;)o(n,t[p]);return n}));e.exports=p},function(e,t,n){e.exports=n(717)},function(e,t,n){var r=n(724),a=n(347),o=n(728);function i(t,n,s){return"undefined"!=typeof Reflect&&r?(e.exports=i=r,e.exports.default=e.exports,e.exports.__esModule=!0):(e.exports=i=function(e,t,n){var r=o(e,t);if(r){var i=a(r,t);return i.get?i.get.call(n):i.value}},e.exports.default=e.exports,e.exports.__esModule=!0),i(t,n,s||t)}e.exports=i,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=require("isomorphic-form-data")},function(e,t,n){e.exports=n(729)},function(e,t,n){var r=n(366);e.exports=function(e){return r(e,5)}},function(e,t,n){e.exports=n(734)},function(e,t){e.exports=require("cross-fetch")},function(e,t){e.exports=require("traverse")},function(e,t){e.exports=require("cookie")},function(e,t){e.exports=require("zenscroll")},function(e,t,n){e.exports=n(749)},function(e,t){e.exports=function(e){const t={literal:"true false null"},n=[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],r=[e.QUOTE_STRING_MODE,e.C_NUMBER_MODE],a={end:",",endsWithParent:!0,excludeEnd:!0,contains:r,keywords:t},o={begin:/\{/,end:/\}/,contains:[{className:"attr",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE],illegal:"\\n"},e.inherit(a,{begin:/:/})].concat(n),illegal:"\\S"},i={begin:"\\[",end:"\\]",contains:[e.inherit(a)],illegal:"\\S"};return r.push(o,i),n.forEach((function(e){r.push(e)})),{name:"JSON",contains:r,keywords:t,illegal:"\\S"}}},function(e,t){const n="[A-Za-z$_][0-9A-Za-z$_]*",r=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends"],a=["true","false","null","undefined","NaN","Infinity"],o=[].concat(["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],["arguments","this","super","console","window","document","localStorage","module","global"],["Intl","DataView","Number","Math","Date","String","RegExp","Object","Function","Boolean","Error","Symbol","Set","Map","WeakSet","WeakMap","Proxy","Reflect","JSON","Promise","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Float32Array","Array","Uint8Array","Uint8ClampedArray","ArrayBuffer"],["EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]);function i(e){return s("(?=",e,")")}function s(...e){return e.map((e=>{return(t=e)?"string"==typeof t?t:t.source:null;var t})).join("")}e.exports=function(e){const t=n,c="<>",u="</>",l={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{const n=e[0].length+e.index,r=e.input[n];"<"!==r?">"===r&&(((e,{after:t})=>{const n="</"+e[0].slice(1);return-1!==e.input.indexOf(n,t)})(e,{after:n})||t.ignoreMatch()):t.ignoreMatch()}},p={$pattern:n,keyword:r.join(" "),literal:a.join(" "),built_in:o.join(" ")},f="\\.([0-9](_?[0-9])*)",d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${d})((${f})|\\.)?|(${f}))[eE][+-]?([0-9](_?[0-9])*)\\b`},{begin:`\\b(${d})\\b((${f})\\b|\\.)?|(${f})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},m={className:"subst",begin:"\\$\\{",end:"\\}",keywords:p,contains:[]},v={begin:"html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"xml"}},g={begin:"css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,m],subLanguage:"css"}},y={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,m]},b={className:"comment",variants:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+",contains:[{className:"type",begin:"\\{",end:"\\}",relevance:0},{className:"variable",begin:t+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},E=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,v,g,y,h,e.REGEXP_MODE];m.contains=E.concat({begin:/\{/,end:/\}/,keywords:p,contains:["self"].concat(E)});const x=[].concat(b,m.contains),S=x.concat([{begin:/\(/,end:/\)/,keywords:p,contains:["self"].concat(x)}]),w={className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:p,contains:S};return{name:"Javascript",aliases:["js","jsx","mjs","cjs"],keywords:p,exports:{PARAMS_CONTAINS:S},illegal:/#(?![$_A-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),{label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,v,g,y,b,h,{begin:s(/[{,\n]\s*/,i(s(/(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/,t+"\\s*:"))),relevance:0,contains:[{className:"attr",begin:t+i("\\s*:"),relevance:0}]},{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",contains:[b,e.REGEXP_MODE,{className:"function",begin:"(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:p,contains:S}]}]},{begin:/,/,relevance:0},{className:"",begin:/\s/,end:/\s*/,skip:!0},{variants:[{begin:c,end:u},{begin:l.begin,"on:begin":l.isTrulyOpeningTag,end:l.end}],subLanguage:"xml",contains:[{begin:l.begin,end:l.end,skip:!0,contains:["self"]}]}],relevance:0},{className:"function",beginKeywords:"function",end:/[{;]/,excludeEnd:!0,keywords:p,contains:["self",e.inherit(e.TITLE_MODE,{begin:t}),w],illegal:/%/},{beginKeywords:"while if switch catch for"},{className:"function",begin:e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,contains:[w,e.inherit(e.TITLE_MODE,{begin:t})]},{variants:[{begin:"\\."+t},{begin:"\\$"+t}],relevance:0},{className:"class",beginKeywords:"class",end:/[{;=]/,excludeEnd:!0,illegal:/[:"[\]]/,contains:[{beginKeywords:"extends"},e.UNDERSCORE_TITLE_MODE]},{begin:/\b(?=constructor)/,end:/[{;]/,excludeEnd:!0,contains:[e.inherit(e.TITLE_MODE,{begin:t}),"self",w]},{begin:"(get|set)\\s+(?="+t+"\\()",end:/\{/,keywords:"get set",contains:[e.inherit(e.TITLE_MODE,{begin:t}),{begin:/\(\)/},w]},{begin:/\$[(.]/}]}}},function(e,t){function n(e){return e?"string"==typeof e?e:e.source:null}function r(e){return a("(?=",e,")")}function a(...e){return e.map((e=>n(e))).join("")}function o(...e){return"("+e.map((e=>n(e))).join("|")+")"}e.exports=function(e){const t=a(/[A-Z_]/,a("(",/[A-Z0-9_.-]+:/,")?"),/[A-Z0-9_.-]*/),n={className:"symbol",begin:"&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;"},i={begin:"\\s",contains:[{className:"meta-keyword",begin:"#?[a-z_][a-z1-9_-]+",illegal:"\\n"}]},s=e.inherit(i,{begin:"\\(",end:"\\)"}),c=e.inherit(e.APOS_STRING_MODE,{className:"meta-string"}),u=e.inherit(e.QUOTE_STRING_MODE,{className:"meta-string"}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:"[A-Za-z0-9\\._:-]+",relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[n]},{begin:/'/,end:/'/,contains:[n]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin:"<![a-z]",end:">",relevance:10,contains:[i,u,c,s,{begin:"\\[",end:"\\]",contains:[{className:"meta",begin:"<![a-z]",end:">",contains:[i,s,u,c]}]}]},e.COMMENT("\x3c!--","--\x3e",{relevance:10}),{begin:"<!\\[CDATA\\[",end:"\\]\\]>",relevance:10},n,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:"<style(?=\\s|>)",end:">",keywords:{name:"style"},contains:[l],starts:{end:"</style>",returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:"<script(?=\\s|>)",end:">",keywords:{name:"script"},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:a(/</,r(a(t,o(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:t,relevance:0,starts:l}]},{className:"tag",begin:a(/<\//,r(a(t,/>/))),contains:[{className:"name",begin:t,relevance:0},{begin:/>/,relevance:0}]}]}}},function(e,t){e.exports=function(e){var t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},a=e.inherit(r,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),o={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},i={end:",",endsWithParent:!0,excludeEnd:!0,contains:[],keywords:t,relevance:0},s={begin:/\{/,end:/\}/,contains:[i],illegal:"\\n",relevance:0},c={begin:"\\[",end:"\\]",contains:[i],illegal:"\\n",relevance:0},u=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},o,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},s,c,r],l=[...u];return l.pop(),l.push(a),i.contains=l,{name:"YAML",case_insensitive:!0,aliases:["yml","YAML"],contains:u}}},function(e,t){e.exports=function(e){var t="HTTP/[0-9\\.]+";return{name:"HTTP",aliases:["https"],illegal:"\\S",contains:[{begin:"^"+t,end:"$",contains:[{className:"number",begin:"\\b\\d{3}\\b"}]},{begin:"^[A-Z]+ (.*?) "+t+"$",returnBegin:!0,end:"$",contains:[{className:"string",begin:" ",end:" ",excludeBegin:!0,excludeEnd:!0},{begin:t},{className:"keyword",begin:"[A-Z]+"}]},{className:"attribute",begin:"^\\w",end:": ",excludeEnd:!0,illegal:"\\n|\\s|=",starts:{end:"$",relevance:0}},{begin:"\\n\\n",starts:{subLanguage:[],endsWithParent:!0}}]}}},function(e,t){function n(...e){return e.map((e=>{return(t=e)?"string"==typeof t?t:t.source:null;var t})).join("")}e.exports=function(e){const t={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[t]}]};Object.assign(t,{className:"variable",variants:[{begin:n(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},i={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t,a]};a.contains.push(i);const s={begin:/\$\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,t]},c=e.SHEBANG({binary:`(${["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"].join("|")})`,relevance:10}),u={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0};return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z._-]+\b/,keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp"},contains:[c,e.SHEBANG(),u,s,e.HASH_COMMENT_MODE,o,i,{className:"",begin:/\\"/},{className:"string",begin:/'/,end:/'/},t]}}},function(e,t){e.exports=require("js-file-download")},function(e,t,n){e.exports=n(756)},function(e,t,n){e.exports=n(759)},function(e,t){e.exports=require("xml-but-prettier")},function(e,t,n){var r=n(77);e.exports=function(e){return r(e).toLowerCase()}},function(e,t){e.exports=require("react-immutable-pure-component")},function(e,t){e.exports=require("autolinker")},function(e,t,n){e.exports=n(765)},function(e,t,n){var r=n(414);n(434),n(435),n(436),n(437),n(438),e.exports=r},function(e,t,n){n(281),n(143),n(285),n(418),n(419),n(420),n(421),n(290),n(422),n(423),n(424),n(425),n(426),n(427),n(428),n(429),n(430),n(431),n(432),n(433);var r=n(31);e.exports=r.Symbol},function(e,t,n){var r=n(38),a=n(59);e.exports=function(e,t){try{a(r,e,t)}catch(n){r[e]=t}return t}},function(e,t,n){var r=n(58),a=n(187).f,o={}.toString,i="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){return i&&"[object Window]"==o.call(e)?function(e){try{return a(e)}catch(e){return i.slice()}}(e):a(r(e))}},function(e,t,n){"use strict";var r=n(190),a=n(74);e.exports=r?{}.toString:function(){return"[object "+a(this)+"]"}},function(e,t,n){n(43)("asyncIterator")},function(e,t){},function(e,t,n){n(43)("hasInstance")},function(e,t,n){n(43)("isConcatSpreadable")},function(e,t,n){n(43)("match")},function(e,t,n){n(43)("matchAll")},function(e,t,n){n(43)("replace")},function(e,t,n){n(43)("search")},function(e,t,n){n(43)("species")},function(e,t,n){n(43)("split")},function(e,t,n){n(43)("toPrimitive")},function(e,t,n){n(43)("toStringTag")},function(e,t,n){n(43)("unscopables")},function(e,t,n){var r=n(38);n(82)(r.JSON,"JSON",!0)},function(e,t){},function(e,t){},function(e,t,n){n(43)("asyncDispose")},function(e,t,n){n(43)("dispose")},function(e,t,n){n(43)("observable")},function(e,t,n){n(43)("patternMatch")},function(e,t,n){n(43)("replaceAll")},function(e,t,n){e.exports=n(440)},function(e,t,n){var r=n(441);e.exports=r},function(e,t,n){n(290),n(83),n(63);var r=n(189);e.exports=r.f("iterator")},function(e,t,n){var r=n(40);e.exports=function(e){if(!r(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e}},function(e,t){e.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(e,t,n){var r=n(445);e.exports=r},function(e,t,n){var r=n(446),a=Array.prototype;e.exports=function(e){var t=e.concat;return e===a||e instanceof Array&&t===a.concat?r:t}},function(e,t,n){n(281);var r=n(39);e.exports=r("Array").concat},function(e,t,n){var r=n(295);e.exports=r},function(e,t,n){n(449);var r=n(39);e.exports=r("Array").filter},function(e,t,n){"use strict";var r=n(24),a=n(75).filter;r({target:"Array",proto:!0,forced:!n(121)("filter")},{filter:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(296);e.exports=r},function(e,t,n){var r=n(24),a=n(61),o=n(122);r({target:"Object",stat:!0,forced:n(34)((function(){o(1)}))},{keys:function(e){return o(a(e))}})},function(e,t,n){var r=n(453);e.exports=r},function(e,t,n){n(454);var r=n(31);r.JSON||(r.JSON={stringify:JSON.stringify}),e.exports=function(e,t,n){return r.JSON.stringify.apply(null,arguments)}},function(e,t,n){var r=n(24),a=n(62),o=n(34),i=a("JSON","stringify"),s=/[\uD800-\uDFFF]/g,c=/^[\uD800-\uDBFF]$/,u=/^[\uDC00-\uDFFF]$/,l=function(e,t,n){var r=n.charAt(t-1),a=n.charAt(t+1);return c.test(e)&&!u.test(a)||u.test(e)&&!c.test(r)?"\\u"+e.charCodeAt(0).toString(16):e},p=o((function(){return'"\\udf06\\ud834"'!==i("\udf06\ud834")||'"\\udead"'!==i("\udead")}));i&&r({target:"JSON",stat:!0,forced:p},{stringify:function(e,t,n){var r=i.apply(null,arguments);return"string"==typeof r?r.replace(s,l):r}})},function(e,t,n){var r=n(297);e.exports=r},function(e,t,n){var r=n(24),a=n(44);r({target:"Object",stat:!0,forced:!a,sham:!a},{defineProperty:n(60).f})},function(e,t,n){var r=n(458);e.exports=r},function(e,t,n){var r=n(459),a=Function.prototype;e.exports=function(e){var t=e.bind;return e===a||e instanceof Function&&t===a.bind?r:t}},function(e,t,n){n(460);var r=n(39);e.exports=r("Function").bind},function(e,t,n){n(24)({target:"Function",proto:!0},{bind:n(298)})},function(e,t,n){var r=n(299);e.exports=r},function(e,t,n){var r=n(24),a=n(300);r({target:"Object",stat:!0,forced:Object.assign!==a},{assign:a})},function(e,t,n){var r=n(301);e.exports=r},function(e,t,n){n(465);var r=n(39);e.exports=r("Array").slice},function(e,t,n){"use strict";var r=n(24),a=n(40),o=n(116),i=n(185),s=n(68),c=n(58),u=n(118),l=n(36),p=n(121)("slice"),f=l("species"),d=[].slice,h=Math.max;r({target:"Array",proto:!0,forced:!p},{slice:function(e,t){var n,r,l,p=c(this),m=s(p.length),v=i(e,m),g=i(void 0===t?m:t,m);if(o(p)&&("function"!=typeof(n=p.constructor)||n!==Array&&!o(n.prototype)?a(n)&&null===(n=n[f])&&(n=void 0):n=void 0,n===Array||void 0===n))return d.call(p,v,g);for(r=new(void 0===n?Array:n)(h(g-v,0)),l=0;v<g;v++,l++)v in p&&u(r,l,p[v]);return r.length=l,r}})},function(e,t,n){var r=n(302);e.exports=r},function(e,t,n){n(24)({target:"Array",stat:!0},{isArray:n(116)})},function(e,t,n){var r=n(469);e.exports=r},function(e,t,n){var r=n(470),a=Array.prototype;e.exports=function(e){var t=e.reduce;return e===a||e instanceof Array&&t===a.reduce?r:t}},function(e,t,n){n(471);var r=n(39);e.exports=r("Array").reduce},function(e,t,n){"use strict";var r=n(24),a=n(472).left,o=n(95),i=n(120),s=n(119);r({target:"Array",proto:!0,forced:!o("reduce")||!s&&i>79&&i<83},{reduce:function(e){return a(this,e,arguments.length,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(67),a=n(61),o=n(139),i=n(68),s=function(e){return function(t,n,s,c){r(n);var u=a(t),l=o(u),p=i(u.length),f=e?p-1:0,d=e?-1:1;if(s<2)for(;;){if(f in l){c=l[f],f+=d;break}if(f+=d,e?f<0:p<=f)throw TypeError("Reduce of empty array with no initial value")}for(;e?f>=0:p>f;f+=d)f in l&&(c=n(c,l[f],f,u));return c}};e.exports={left:s(!1),right:s(!0)}},function(e,t,n){var r=n(474);e.exports=r},function(e,t,n){var r=n(475),a=Array.prototype;e.exports=function(e){var t=e.map;return e===a||e instanceof Array&&t===a.map?r:t}},function(e,t,n){n(476);var r=n(39);e.exports=r("Array").map},function(e,t,n){"use strict";var r=n(24),a=n(75).map;r({target:"Array",proto:!0,forced:!n(121)("map")},{map:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){"use strict";(function(e){var r=n(478),a=n(479),o=n(480);function i(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(e,t){if(i()<t)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=c.prototype:(null===e&&(e=new c(t)),e.length=t),e}function c(e,t,n){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return p(this,e)}return u(this,e,t,n)}function u(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r);c.TYPED_ARRAY_SUPPORT?(e=t).__proto__=c.prototype:e=f(e,t);return e}(e,t,n,r):"string"==typeof t?function(e,t,n){"string"==typeof n&&""!==n||(n="utf8");if(!c.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|h(t,n),a=(e=s(e,r)).write(t,n);a!==r&&(e=e.slice(0,a));return e}(e,t,n):function(e,t){if(c.isBuffer(t)){var n=0|d(t.length);return 0===(e=s(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?s(e,0):f(e,t);if("Buffer"===t.type&&o(t.data))return f(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function p(e,t){if(l(t),e=s(e,t<0?0:0|d(t)),!c.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function f(e,t){var n=t.length<0?0:0|d(t.length);e=s(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function d(e){if(e>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function h(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return z(e).length;default:if(r)return V(e).length;t=(""+t).toLowerCase(),r=!0}}function m(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,n);case"utf8":case"utf-8":return C(this,t,n);case"ascii":return A(this,t,n);case"latin1":case"binary":return k(this,t,n);case"base64":return O(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function v(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function g(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:y(e,t,n,r,a);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,r,a){var o,i=1,s=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;i=2,s/=2,c/=2,n/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(a){var l=-1;for(o=n;o<s;o++)if(u(e,o)===u(t,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===c)return l*i}else-1!==l&&(o-=o-l),l=-1}else for(n+c>s&&(n=s-c),o=n;o>=0;o--){for(var p=!0,f=0;f<c;f++)if(u(e,o+f)!==u(t,f)){p=!1;break}if(p)return o}return-1}function b(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var i=0;i<r;++i){var s=parseInt(t.substr(2*i,2),16);if(isNaN(s))return i;e[n+i]=s}return i}function E(e,t,n,r){return F(V(t,e.length-n),e,n,r)}function x(e,t,n,r){return F(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function S(e,t,n,r){return x(e,t,n,r)}function w(e,t,n,r){return F(z(t),e,n,r)}function j(e,t,n,r){return F(function(e,t){for(var n,r,a,o=[],i=0;i<e.length&&!((t-=2)<0);++i)r=(n=e.charCodeAt(i))>>8,a=n%256,o.push(a),o.push(r);return o}(t,e.length-n),e,n,r)}function O(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function C(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var o,i,s,c,u=e[a],l=null,p=u>239?4:u>223?3:u>191?2:1;if(a+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(o=e[a+1]))&&(c=(31&u)<<6|63&o)>127&&(l=c);break;case 3:o=e[a+1],i=e[a+2],128==(192&o)&&128==(192&i)&&(c=(15&u)<<12|(63&o)<<6|63&i)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[a+1],i=e[a+2],s=e[a+3],128==(192&o)&&128==(192&i)&&128==(192&s)&&(c=(15&u)<<18|(63&o)<<12|(63&i)<<6|63&s)>65535&&c<1114112&&(l=c)}null===l?(l=65533,p=1):l>65535&&(l-=65536,r.push(l>>>10&1023|55296),l=56320|1023&l),r.push(l),a+=p}return function(e){var t=e.length;if(t<=_)return String.fromCharCode.apply(String,e);var n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=_));return n}(r)}t.Buffer=c,t.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},t.INSPECT_MAX_BYTES=50,c.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=i(),c.poolSize=8192,c._augment=function(e){return e.__proto__=c.prototype,e},c.from=function(e,t,n){return u(null,e,t,n)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(e,t,n){return function(e,t,n,r){return l(t),t<=0?s(e,t):void 0!==n?"string"==typeof r?s(e,t).fill(n,r):s(e,t).fill(n):s(e,t)}(null,e,t,n)},c.allocUnsafe=function(e){return p(null,e)},c.allocUnsafeSlow=function(e){return p(null,e)},c.isBuffer=function(e){return!(null==e||!e._isBuffer)},c.compare=function(e,t){if(!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,o=Math.min(n,r);a<o;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!o(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=c.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var i=e[n];if(!c.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,a),a+=i.length}return r},c.byteLength=h,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)v(this,t,t+1);return this},c.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)v(this,t,t+3),v(this,t+1,t+2);return this},c.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)v(this,t,t+7),v(this,t+1,t+6),v(this,t+2,t+5),v(this,t+3,t+4);return this},c.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?C(this,0,e):m.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},c.prototype.compare=function(e,t,n,r,a){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var o=(a>>>=0)-(r>>>=0),i=(n>>>=0)-(t>>>=0),s=Math.min(o,i),u=this.slice(r,a),l=e.slice(t,n),p=0;p<s;++p)if(u[p]!==l[p]){o=u[p],i=l[p];break}return o<i?-1:i<o?1:0},c.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},c.prototype.indexOf=function(e,t,n){return g(this,e,t,n,!0)},c.prototype.lastIndexOf=function(e,t,n){return g(this,e,t,n,!1)},c.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return b(this,e,t,n);case"utf8":case"utf-8":return E(this,e,t,n);case"ascii":return x(this,e,t,n);case"latin1":case"binary":return S(this,e,t,n);case"base64":return w(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,e,t,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var _=4096;function A(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function k(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function I(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",o=t;o<n;++o)a+=U(e[o]);return a}function P(e,t,n){for(var r=e.slice(t,n),a="",o=0;o<r.length;o+=2)a+=String.fromCharCode(r[o]+256*r[o+1]);return a}function T(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function R(e,t,n,r,a,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<o)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function N(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,o=Math.min(e.length-n,2);a<o;++a)e[n+a]=(t&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function M(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,o=Math.min(e.length-n,4);a<o;++a)e[n+a]=t>>>8*(r?a:3-a)&255}function D(e,t,n,r,a,o){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function q(e,t,n,r,o){return o||D(e,0,n,4),a.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,o){return o||D(e,0,n,8),a.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),c.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=c.prototype;else{var a=t-e;n=new c(a,void 0);for(var o=0;o<a;++o)n[o]=this[o+e]}return n},c.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r},c.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},c.prototype.readUInt8=function(e,t){return t||T(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||T(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||T(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=this[e],a=1,o=0;++o<t&&(a*=256);)r+=this[e+o]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||T(e,t,this.length);for(var r=t,a=1,o=this[e+--r];r>0&&(a*=256);)o+=this[e+--r]*a;return o>=(a*=128)&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||T(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){t||T(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||T(e,4,this.length),a.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||T(e,4,this.length),a.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||T(e,8,this.length),a.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||T(e,8,this.length),a.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||R(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,o=0;for(this[t]=255&e;++o<n&&(a*=256);)this[t+o]=e/a&255;return t+n},c.prototype.writeUIntBE=function(e,t,n,r){(e=+e,t|=0,n|=0,r)||R(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,o=1;for(this[t+a]=255&e;--a>=0&&(o*=256);)this[t+a]=e/o&255;return t+n},c.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):M(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);R(this,e,t,n,a-1,-a)}var o=0,i=1,s=0;for(this[t]=255&e;++o<n&&(i*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/i>>0)-s&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);R(this,e,t,n,a-1,-a)}var o=n-1,i=1,s=0;for(this[t+o]=255&e;--o>=0&&(i*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/i>>0)-s&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):N(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):N(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):M(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||R(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,n){return q(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return q(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a,o=r-n;if(this===e&&n<t&&t<r)for(a=o-1;a>=0;--a)e[a+t]=this[a+n];else if(o<1e3||!c.TYPED_ARRAY_SUPPORT)for(a=0;a<o;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+o),t);return o},c.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var a=e.charCodeAt(0);a<256&&(e=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!c.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var o;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(o=t;o<n;++o)this[o]=e;else{var i=c.isBuffer(e)?e:V(new c(e,r).toString()),s=i.length;for(o=0;o<n-t;++o)this[o+t]=i[o%s]}return this};var L=/[^+\/0-9A-Za-z-_]/g;function U(e){return e<16?"0"+e.toString(16):e.toString(16)}function V(e,t){var n;t=t||1/0;for(var r=e.length,a=null,o=[],i=0;i<r;++i){if((n=e.charCodeAt(i))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(i+1===r){(t-=3)>-1&&o.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&o.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&o.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;o.push(n)}else if(n<2048){if((t-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function z(e){return r.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}}).call(this,n(177))},function(e,t){e.exports=require("base64-js")},function(e,t){e.exports=require("ieee754")},function(e,t){e.exports=require("isarray")},function(e,t,n){var r=n(195),a=n(303);e.exports=function(e){if(r(e))return a(e)},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(302);e.exports=r},function(e,t,n){n(63),n(83);var r=n(484);e.exports=r},function(e,t,n){var r=n(74),a=n(36),o=n(94),i=a("iterator");e.exports=function(e){var t=Object(e);return void 0!==t[i]||"@@iterator"in t||o.hasOwnProperty(r(t))}},function(e,t,n){var r=n(307);e.exports=r},function(e,t,n){var r=n(24),a=n(308);r({target:"Array",stat:!0,forced:!n(311)((function(e){Array.from(e)}))},{from:a})},function(e,t,n){var r=n(46),a=n(309);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){throw a(e),t}}},function(e,t,n){e.exports=n(489)},function(e,t,n){var r=n(301);e.exports=r},function(e,t){e.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(137),a=n(305),o=n(313);e.exports=function(e,t){if(void 0!==r&&a(Object(e))){var n=[],i=!0,s=!1,c=void 0;try{for(var u,l=o(e);!(i=(u=l.next()).done)&&(n.push(u.value),!t||n.length!==t);i=!0);}catch(e){s=!0,c=e}finally{try{i||null==l.return||l.return()}finally{if(s)throw c}}return n}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){n(63),n(83);var r=n(314);e.exports=r},function(e,t,n){e.exports=n(494)},function(e,t,n){n(63),n(83);var r=n(126);e.exports=r},function(e,t,n){n(63);var r=n(496),a=n(74),o=Array.prototype,i={DOMTokenList:!0,NodeList:!0};e.exports=function(e){var t=e.entries;return e===o||e instanceof Array&&t===o.entries||i.hasOwnProperty(a(e))?r:t}},function(e,t,n){var r=n(497);e.exports=r},function(e,t,n){n(125);var r=n(39);e.exports=r("Array").entries},function(e,t,n){var r=n(499);e.exports=r},function(e,t,n){n(500);var r=n(39);e.exports=r("Array").forEach},function(e,t,n){"use strict";var r=n(24),a=n(501);r({target:"Array",proto:!0,forced:[].forEach!=a},{forEach:a})},function(e,t,n){"use strict";var r=n(75).forEach,a=n(95)("forEach");e.exports=a?[].forEach:function(e){return r(this,e,arguments.length>1?arguments[1]:void 0)}},function(e,t,n){var r=n(503);e.exports=r},function(e,t,n){var r=n(504),a=Array.prototype;e.exports=function(e){var t=e.sort;return e===a||e instanceof Array&&t===a.sort?r:t}},function(e,t,n){n(505);var r=n(39);e.exports=r("Array").sort},function(e,t,n){"use strict";var r=n(24),a=n(67),o=n(61),i=n(34),s=n(95),c=[],u=c.sort,l=i((function(){c.sort(void 0)})),p=i((function(){c.sort(null)})),f=s("sort");r({target:"Array",proto:!0,forced:l||!p||!f},{sort:function(e){return void 0===e?u.call(o(this)):u.call(o(this),a(e))}})},function(e,t,n){var r=n(507);e.exports=r},function(e,t,n){var r=n(508),a=Array.prototype;e.exports=function(e){var t=e.some;return e===a||e instanceof Array&&t===a.some?r:t}},function(e,t,n){n(509);var r=n(39);e.exports=r("Array").some},function(e,t,n){"use strict";var r=n(24),a=n(75).some;r({target:"Array",proto:!0,forced:!n(95)("some")},{some:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(511);e.exports=r},function(e,t,n){var r=n(512),a=n(514),o=Array.prototype,i=String.prototype;e.exports=function(e){var t=e.includes;return e===o||e instanceof Array&&t===o.includes?r:"string"==typeof e||e===i||e instanceof String&&t===i.includes?a:t}},function(e,t,n){n(513);var r=n(39);e.exports=r("Array").includes},function(e,t,n){"use strict";var r=n(24),a=n(184).includes,o=n(193);r({target:"Array",proto:!0},{includes:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}}),o("includes")},function(e,t,n){n(515);var r=n(39);e.exports=r("String").includes},function(e,t,n){"use strict";var r=n(24),a=n(317),o=n(104);r({target:"String",proto:!0,forced:!n(318)("includes")},{includes:function(e){return!!~String(o(this)).indexOf(a(e),arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(40),a=n(115),o=n(36)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[o])?!!t:"RegExp"==a(e))}},function(e,t,n){var r=n(319);e.exports=r},function(e,t,n){n(519);var r=n(39);e.exports=r("Array").indexOf},function(e,t,n){"use strict";var r=n(24),a=n(184).indexOf,o=n(95),i=[].indexOf,s=!!i&&1/[1].indexOf(1,-0)<0,c=o("indexOf");r({target:"Array",proto:!0,forced:s||!c},{indexOf:function(e){return s?i.apply(this,arguments)||0:a(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){var r=n(521);e.exports=r},function(e,t,n){var r=n(522),a=Array.prototype;e.exports=function(e){var t=e.find;return e===a||e instanceof Array&&t===a.find?r:t}},function(e,t,n){n(523);var r=n(39);e.exports=r("Array").find},function(e,t,n){"use strict";var r=n(24),a=n(75).find,o=n(193),i="find",s=!0;i in[]&&Array(1).find((function(){s=!1})),r({target:"Array",proto:!0,forced:s},{find:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}}),o(i)},function(e,t,n){var r=n(525);e.exports=r},function(e,t,n){var r=n(526),a=String.prototype;e.exports=function(e){var t=e.startsWith;return"string"==typeof e||e===a||e instanceof String&&t===a.startsWith?r:t}},function(e,t,n){n(527);var r=n(39);e.exports=r("String").startsWith},function(e,t,n){"use strict";var r,a=n(24),o=n(89).f,i=n(68),s=n(317),c=n(104),u=n(318),l=n(81),p="".startsWith,f=Math.min,d=u("startsWith");a({target:"String",proto:!0,forced:!!(l||d||(r=o(String.prototype,"startsWith"),!r||r.writable))&&!d},{startsWith:function(e){var t=String(c(this));s(e);var n=i(f(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return p?p.call(t,r,n):t.slice(n,n+r.length)===r}})},function(e,t,n){var r=n(529);e.exports=r},function(e,t,n){var r=n(530),a=String.prototype;e.exports=function(e){var t=e.trim;return"string"==typeof e||e===a||e instanceof String&&t===a.trim?r:t}},function(e,t,n){n(531);var r=n(39);e.exports=r("String").trim},function(e,t,n){"use strict";var r=n(24),a=n(532).trim;r({target:"String",proto:!0,forced:n(533)("trim")},{trim:function(){return a(this)}})},function(e,t,n){var r=n(104),a="["+n(320)+"]",o=RegExp("^"+a+a+"*"),i=RegExp(a+a+"*$"),s=function(e){return function(t){var n=String(r(t));return 1&e&&(n=n.replace(o,"")),2&e&&(n=n.replace(i,"")),n}};e.exports={start:s(1),end:s(2),trim:s(3)}},function(e,t,n){var r=n(34),a=n(320);e.exports=function(e){return r((function(){return!!a[e]()||"
"!="
"[e]()||a[e].name!==e}))}},function(e,t,n){var r=n(77),a=n(211);e.exports=function(e){return a(r(e).toLowerCase())}},function(e,t,n){var r=n(105),a=Object.prototype,o=a.hasOwnProperty,i=a.toString,s=r?r.toStringTag:void 0;e.exports=function(e){var t=o.call(e,s),n=e[s];try{e[s]=void 0;var r=!0}catch(e){}var a=i.call(e);return r&&(t?e[s]=n:delete e[s]),a}},function(e,t){var n=Object.prototype.toString;e.exports=function(e){return n.call(e)}},function(e,t,n){var r=n(538),a=n(325),o=n(539),i=n(77);e.exports=function(e){return function(t){t=i(t);var n=a(t)?o(t):void 0,s=n?n[0]:t.charAt(0),c=n?r(n,1).join(""):t.slice(1);return s[e]()+c}}},function(e,t,n){var r=n(324);e.exports=function(e,t,n){var a=e.length;return n=void 0===n?a:n,!t&&n>=a?e:r(e,t,n)}},function(e,t,n){var r=n(540),a=n(325),o=n(541);e.exports=function(e){return a(e)?o(e):r(e)}},function(e,t){e.exports=function(e){return e.split("")}},function(e,t){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",a="\\ud83c[\\udffb-\\udfff]",o="[^\\ud800-\\udfff]",i="(?:\\ud83c[\\udde6-\\uddff]){2}",s="[\\ud800-\\udbff][\\udc00-\\udfff]",c="(?:"+r+"|"+a+")"+"?",u="[\\ufe0e\\ufe0f]?",l=u+c+("(?:\\u200d(?:"+[o,i,s].join("|")+")"+u+c+")*"),p="(?:"+[o+r+"?",r,i,s,n].join("|")+")",f=RegExp(a+"(?="+a+")|"+p+l,"g");e.exports=function(e){return e.match(f)||[]}},function(e,t,n){var r=n(326),a=n(543),o=n(546),i=RegExp("['’]","g");e.exports=function(e){return function(t){return r(o(a(t).replace(i,"")),e,"")}}},function(e,t,n){var r=n(544),a=n(77),o=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,i=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g");e.exports=function(e){return(e=a(e))&&e.replace(o,r).replace(i,"")}},function(e,t,n){var r=n(545)({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"});e.exports=r},function(e,t){e.exports=function(e){return function(t){return null==e?void 0:e[t]}}},function(e,t,n){var r=n(547),a=n(548),o=n(77),i=n(549);e.exports=function(e,t,n){return e=o(e),void 0===(t=n?void 0:t)?a(e)?i(e):r(e):e.match(t)||[]}},function(e,t){var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=function(e){return e.match(n)||[]}},function(e,t){var n=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=function(e){return n.test(e)}},function(e,t){var n="\\u2700-\\u27bf",r="a-z\\xdf-\\xf6\\xf8-\\xff",a="A-Z\\xc0-\\xd6\\xd8-\\xde",o="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",i="["+o+"]",s="\\d+",c="[\\u2700-\\u27bf]",u="["+r+"]",l="[^\\ud800-\\udfff"+o+s+n+r+a+"]",p="(?:\\ud83c[\\udde6-\\uddff]){2}",f="[\\ud800-\\udbff][\\udc00-\\udfff]",d="["+a+"]",h="(?:"+u+"|"+l+")",m="(?:"+d+"|"+l+")",v="(?:['’](?:d|ll|m|re|s|t|ve))?",g="(?:['’](?:D|LL|M|RE|S|T|VE))?",y="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",b="[\\ufe0e\\ufe0f]?",E=b+y+("(?:\\u200d(?:"+["[^\\ud800-\\udfff]",p,f].join("|")+")"+b+y+")*"),x="(?:"+[c,p,f].join("|")+")"+E,S=RegExp([d+"?"+u+"+"+v+"(?="+[i,d,"$"].join("|")+")",m+"+"+g+"(?="+[i,d+h,"$"].join("|")+")",d+"?"+h+"+"+v,d+"+"+g,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",s,x].join("|"),"g");e.exports=function(e){return e.match(S)||[]}},function(e,t,n){var r=n(551),a=n(148),o=n(197);e.exports=function(){this.size=0,this.__data__={hash:new r,map:new(o||a),string:new r}}},function(e,t,n){var r=n(552),a=n(557),o=n(558),i=n(559),s=n(560);function c(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}c.prototype.clear=r,c.prototype.delete=a,c.prototype.get=o,c.prototype.has=i,c.prototype.set=s,e.exports=c},function(e,t,n){var r=n(147);e.exports=function(){this.__data__=r?r(null):{},this.size=0}},function(e,t,n){var r=n(55),a=n(554),o=n(51),i=n(327),s=/^\[object .+?Constructor\]$/,c=Function.prototype,u=Object.prototype,l=c.toString,p=u.hasOwnProperty,f=RegExp("^"+l.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=function(e){return!(!o(e)||a(e))&&(r(e)?f:s).test(i(e))}},function(e,t,n){var r,a=n(555),o=(r=/[^.]+$/.exec(a&&a.keys&&a.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";e.exports=function(e){return!!o&&o in e}},function(e,t,n){var r=n(64)["__core-js_shared__"];e.exports=r},function(e,t){e.exports=function(e,t){return null==e?void 0:e[t]}},function(e,t){e.exports=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}},function(e,t,n){var r=n(147),a=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;if(r){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return a.call(t,e)?t[e]:void 0}},function(e,t,n){var r=n(147),a=Object.prototype.hasOwnProperty;e.exports=function(e){var t=this.__data__;return r?void 0!==t[e]:a.call(t,e)}},function(e,t,n){var r=n(147);e.exports=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=r&&void 0===t?"__lodash_hash_undefined__":t,this}},function(e,t){e.exports=function(){this.__data__=[],this.size=0}},function(e,t,n){var r=n(149),a=Array.prototype.splice;e.exports=function(e){var t=this.__data__,n=r(t,e);return!(n<0)&&(n==t.length-1?t.pop():a.call(t,n,1),--this.size,!0)}},function(e,t,n){var r=n(149);e.exports=function(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}},function(e,t,n){var r=n(149);e.exports=function(e){return r(this.__data__,e)>-1}},function(e,t,n){var r=n(149);e.exports=function(e,t){var n=this.__data__,a=r(n,e);return a<0?(++this.size,n.push([e,t])):n[a][1]=t,this}},function(e,t,n){var r=n(150);e.exports=function(e){var t=r(this,e).delete(e);return this.size-=t?1:0,t}},function(e,t){e.exports=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}},function(e,t,n){var r=n(150);e.exports=function(e){return r(this,e).get(e)}},function(e,t,n){var r=n(150);e.exports=function(e){return r(this,e).has(e)}},function(e,t,n){var r=n(150);e.exports=function(e,t){var n=r(this,e),a=n.size;return n.set(e,t),this.size+=n.size==a?0:1,this}},function(e,t,n){var r=n(151),a=n(99),o=n(98);e.exports=function(e){return function(t,n,i){var s=Object(t);if(!a(t)){var c=r(n,3);t=o(t),n=function(e){return c(s[e],e,s)}}var u=e(t,n,i);return u>-1?s[c?t[u]:u]:void 0}}},function(e,t,n){var r=n(573),a=n(598),o=n(339);e.exports=function(e){var t=a(e);return 1==t.length&&t[0][2]?o(t[0][0],t[0][1]):function(n){return n===e||r(n,e,t)}}},function(e,t,n){var r=n(198),a=n(328);e.exports=function(e,t,n,o){var i=n.length,s=i,c=!o;if(null==e)return!s;for(e=Object(e);i--;){var u=n[i];if(c&&u[2]?u[1]!==e[u[0]]:!(u[0]in e))return!1}for(;++i<s;){var l=(u=n[i])[0],p=e[l],f=u[1];if(c&&u[2]){if(void 0===p&&!(l in e))return!1}else{var d=new r;if(o)var h=o(p,f,l,e,t,d);if(!(void 0===h?a(f,p,3,o,d):h))return!1}}return!0}},function(e,t,n){var r=n(148);e.exports=function(){this.__data__=new r,this.size=0}},function(e,t){e.exports=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}},function(e,t){e.exports=function(e){return this.__data__.get(e)}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t,n){var r=n(148),a=n(197),o=n(196);e.exports=function(e,t){var n=this.__data__;if(n instanceof r){var i=n.__data__;if(!a||i.length<199)return i.push([e,t]),this.size=++n.size,this;n=this.__data__=new o(i)}return n.set(e,t),this.size=n.size,this}},function(e,t,n){var r=n(198),a=n(329),o=n(584),i=n(587),s=n(128),c=n(47),u=n(153),l=n(202),p="[object Arguments]",f="[object Array]",d="[object Object]",h=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,m,v,g){var y=c(e),b=c(t),E=y?f:s(e),x=b?f:s(t),S=(E=E==p?d:E)==d,w=(x=x==p?d:x)==d,j=E==x;if(j&&u(e)){if(!u(t))return!1;y=!0,S=!1}if(j&&!S)return g||(g=new r),y||l(e)?a(e,t,n,m,v,g):o(e,t,E,n,m,v,g);if(!(1&n)){var O=S&&h.call(e,"__wrapped__"),C=w&&h.call(t,"__wrapped__");if(O||C){var _=O?e.value():e,A=C?t.value():t;return g||(g=new r),v(_,A,n,m,g)}}return!!j&&(g||(g=new r),i(e,t,n,m,v,g))}},function(e,t,n){var r=n(196),a=n(581),o=n(582);function i(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new r;++t<n;)this.add(e[t])}i.prototype.add=i.prototype.push=a,i.prototype.has=o,e.exports=i},function(e,t){e.exports=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this}},function(e,t){e.exports=function(e){return this.__data__.has(e)}},function(e,t){e.exports=function(e,t){return e.has(t)}},function(e,t,n){var r=n(105),a=n(331),o=n(101),i=n(329),s=n(585),c=n(586),u=r?r.prototype:void 0,l=u?u.valueOf:void 0;e.exports=function(e,t,n,r,u,p,f){switch(n){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!p(new a(e),new a(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return o(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var d=s;case"[object Set]":var h=1&r;if(d||(d=c),e.size!=t.size&&!h)return!1;var m=f.get(e);if(m)return m==t;r|=2,f.set(e,t);var v=i(d(e),d(t),r,u,p,f);return f.delete(e),v;case"[object Symbol]":if(l)return l.call(e)==l.call(t)}return!1}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}},function(e,t){e.exports=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}},function(e,t,n){var r=n(332),a=Object.prototype.hasOwnProperty;e.exports=function(e,t,n,o,i,s){var c=1&n,u=r(e),l=u.length;if(l!=r(t).length&&!c)return!1;for(var p=l;p--;){var f=u[p];if(!(c?f in t:a.call(t,f)))return!1}var d=s.get(e),h=s.get(t);if(d&&h)return d==t&&h==e;var m=!0;s.set(e,t),s.set(t,e);for(var v=c;++p<l;){var g=e[f=u[p]],y=t[f];if(o)var b=c?o(y,g,f,t,e,s):o(g,y,f,e,t,s);if(!(void 0===b?g===y||i(g,y,n,o,s):b)){m=!1;break}v||(v="constructor"==f)}if(m&&!v){var E=e.constructor,x=t.constructor;E==x||!("constructor"in e)||!("constructor"in t)||"function"==typeof E&&E instanceof E&&"function"==typeof x&&x instanceof x||(m=!1)}return s.delete(e),s.delete(t),m}},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length,a=0,o=[];++n<r;){var i=e[n];t(i,n,e)&&(o[a++]=i)}return o}},function(e,t){e.exports=function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}},function(e,t,n){var r=n(96),a=n(76);e.exports=function(e){return a(e)&&"[object Arguments]"==r(e)}},function(e,t){e.exports=function(){return!1}},function(e,t,n){var r=n(96),a=n(203),o=n(76),i={};i["[object Float32Array]"]=i["[object Float64Array]"]=i["[object Int8Array]"]=i["[object Int16Array]"]=i["[object Int32Array]"]=i["[object Uint8Array]"]=i["[object Uint8ClampedArray]"]=i["[object Uint16Array]"]=i["[object Uint32Array]"]=!0,i["[object Arguments]"]=i["[object Array]"]=i["[object ArrayBuffer]"]=i["[object Boolean]"]=i["[object DataView]"]=i["[object Date]"]=i["[object Error]"]=i["[object Function]"]=i["[object Map]"]=i["[object Number]"]=i["[object Object]"]=i["[object RegExp]"]=i["[object Set]"]=i["[object String]"]=i["[object WeakMap]"]=!1,e.exports=function(e){return o(e)&&a(e.length)&&!!i[r(e)]}},function(e,t,n){var r=n(337)(Object.keys,Object);e.exports=r},function(e,t,n){var r=n(97)(n(64),"DataView");e.exports=r},function(e,t,n){var r=n(97)(n(64),"Promise");e.exports=r},function(e,t,n){var r=n(97)(n(64),"Set");e.exports=r},function(e,t,n){var r=n(97)(n(64),"WeakMap");e.exports=r},function(e,t,n){var r=n(338),a=n(98);e.exports=function(e){for(var t=a(e),n=t.length;n--;){var o=t[n],i=e[o];t[n]=[o,i,r(i)]}return t}},function(e,t,n){var r=n(328),a=n(41),o=n(340),i=n(206),s=n(338),c=n(339),u=n(107);e.exports=function(e,t){return i(e)&&s(t)?c(u(e),t):function(n){var i=a(n,e);return void 0===i&&i===t?o(n,e):r(t,i,3)}}},function(e,t,n){var r=n(601),a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,o=/\\(\\)?/g,i=r((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(a,(function(e,n,r,a){t.push(r?a.replace(o,"$1"):n||e)})),t}));e.exports=i},function(e,t,n){var r=n(212);e.exports=function(e){var t=r(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}},function(e,t){e.exports=function(e,t){return null!=e&&t in Object(e)}},function(e,t,n){var r=n(106),a=n(152),o=n(47),i=n(154),s=n(203),c=n(107);e.exports=function(e,t,n){for(var u=-1,l=(t=r(t,e)).length,p=!1;++u<l;){var f=c(t[u]);if(!(p=null!=e&&n(e,f)))break;e=e[f]}return p||++u!=l?p:!!(l=null==e?0:e.length)&&s(l)&&i(f,l)&&(o(e)||a(e))}},function(e,t,n){var r=n(605),a=n(606),o=n(206),i=n(107);e.exports=function(e){return o(e)?r(i(e)):a(e)}},function(e,t){e.exports=function(e){return function(t){return null==t?void 0:t[e]}}},function(e,t,n){var r=n(155);e.exports=function(e){return function(t){return r(t,e)}}},function(e,t,n){var r=n(608),a=n(151),o=n(341),i=Math.max;e.exports=function(e,t,n){var s=null==e?0:e.length;if(!s)return-1;var c=null==n?0:o(n);return c<0&&(c=i(s+c,0)),r(e,a(t,3),c)}},function(e,t){e.exports=function(e,t,n,r){for(var a=e.length,o=n+(r?1:-1);r?o--:++o<a;)if(t(e[o],o,e))return o;return-1}},function(e,t,n){var r=n(342),a=1/0;e.exports=function(e){return e?(e=r(e))===a||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}},function(e,t,n){var r=n(611),a=/^\s+/;e.exports=function(e){return e?e.slice(0,r(e)+1).replace(a,""):e}},function(e,t){var n=/\s/;e.exports=function(e){for(var t=e.length;t--&&n.test(e.charAt(t)););return t}},function(e,t,n){var r=n(343);e.exports=function(e,t){var n;return r(e,(function(e,r,a){return!(n=t(e,r,a))})),!!n}},function(e,t,n){var r=n(614),a=n(98);e.exports=function(e,t){return e&&r(e,t,a)}},function(e,t,n){var r=n(615)();e.exports=r},function(e,t){e.exports=function(e){return function(t,n,r){for(var a=-1,o=Object(t),i=r(t),s=i.length;s--;){var c=i[e?s:++a];if(!1===n(o[c],c,o))break}return t}}},function(e,t,n){var r=n(99);e.exports=function(e,t){return function(n,a){if(null==n)return n;if(!r(n))return e(n,a);for(var o=n.length,i=t?o:-1,s=Object(n);(t?i--:++i<o)&&!1!==a(s[i],i,s););return n}}},function(e,t){var n,r,a=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(e){n=o}try{r="function"==typeof clearTimeout?clearTimeout:i}catch(e){r=i}}();var c,u=[],l=!1,p=-1;function f(){l&&c&&(l=!1,c.length?u=c.concat(u):p=-1,u.length&&d())}function d(){if(!l){var e=s(f);l=!0;for(var t=u.length;t;){for(c=u,u=[];++p<t;)c&&c[p].run();p=-1,t=u.length}c=null,l=!1,function(e){if(r===clearTimeout)return clearTimeout(e);if((r===i||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(e);try{r(e)}catch(t){try{return r.call(null,e)}catch(t){return r.call(this,e)}}}(e)}}function h(e,t){this.fun=e,this.array=t}function m(){}a.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new h(e,t)),1!==u.length||l||s(d)},h.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=m,a.addListener=m,a.once=m,a.off=m,a.removeListener=m,a.removeAllListeners=m,a.emit=m,a.prependListener=m,a.prependOnceListener=m,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(e,t){var n={"&":"&",'"':""","'":"'","<":"<",">":">"};e.exports=function(e){return e&&e.replace?e.replace(/([&"<>'])/g,(function(e,t){return n[t]})):e}},function(e,t){e.exports=require("stream")},function(e,t,n){var r=n(621);e.exports=r},function(e,t,n){var r=n(622),a=Array.prototype;e.exports=function(e){var t=e.every;return e===a||e instanceof Array&&t===a.every?r:t}},function(e,t,n){n(623);var r=n(39);e.exports=r("Array").every},function(e,t,n){"use strict";var r=n(24),a=n(75).every;r({target:"Array",proto:!0,forced:!n(95)("every")},{every:function(e){return a(this,e,arguments.length>1?arguments[1]:void 0)}})},function(e,t){e.exports=function(e,t,n,r,a){return a(e,(function(e,a,o){n=r?(r=!1,e):t(n,e,a,o)})),n}},function(e,t,n){var r=n(296);e.exports=r},function(e,t,n){var r=n(627);e.exports=r},function(e,t,n){n(285);var r=n(31);e.exports=r.Object.getOwnPropertySymbols},function(e,t,n){e.exports=n(629)},function(e,t,n){var r=n(295);e.exports=r},function(e,t,n){var r=n(631);e.exports=r},function(e,t,n){n(632);var r=n(31).Object,a=e.exports=function(e,t){return r.getOwnPropertyDescriptor(e,t)};r.getOwnPropertyDescriptor.sham&&(a.sham=!0)},function(e,t,n){var r=n(24),a=n(34),o=n(58),i=n(89).f,s=n(44),c=a((function(){i(1)}));r({target:"Object",stat:!0,forced:!s||c,sham:!s},{getOwnPropertyDescriptor:function(e,t){return i(o(e),t)}})},function(e,t,n){e.exports=n(634)},function(e,t,n){var r=n(316);e.exports=r},function(e,t,n){e.exports=n(636)},function(e,t,n){var r=n(637);e.exports=r},function(e,t,n){n(638);var r=n(31);e.exports=r.Object.getOwnPropertyDescriptors},function(e,t,n){var r=n(24),a=n(44),o=n(639),i=n(58),s=n(89),c=n(118);r({target:"Object",stat:!0,sham:!a},{getOwnPropertyDescriptors:function(e){for(var t,n,r=i(e),a=s.f,u=o(r),l={},p=0;u.length>p;)void 0!==(n=a(r,t=u[p++]))&&c(l,t,n);return l}})},function(e,t,n){var r=n(62),a=n(187),o=n(188),i=n(46);e.exports=r("Reflect","ownKeys")||function(e){var t=a.f(i(e)),n=o.f;return n?t.concat(n(e)):t}},function(e,t,n){e.exports=n(641)},function(e,t,n){var r=n(642);e.exports=r},function(e,t,n){n(643);var r=n(31).Object,a=e.exports=function(e,t){return r.defineProperties(e,t)};r.defineProperties.sham&&(a.sham=!0)},function(e,t,n){var r=n(24),a=n(44);r({target:"Object",stat:!0,forced:!a,sham:!a},{defineProperties:n(183)})},function(e,t,n){var r=n(319);e.exports=r},function(e,t,n){var r=n(345),a=n(348);e.exports=function(e,t){if(null==e)return{};var n,o,i={},s=r(e);for(o=0;o<s.length;o++)n=s[o],a(t).call(t,n)>=0||(i[n]=e[n]);return i},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){e.exports=n(647)},function(e,t,n){var r=n(349);n(653),n(654),n(655),n(656),e.exports=r},function(e,t,n){"use strict";var r,a,o,i,s=n(24),c=n(81),u=n(38),l=n(62),p=n(351),f=n(93),d=n(129),h=n(82),m=n(352),v=n(40),g=n(67),y=n(108),b=n(289),E=n(100),x=n(311),S=n(353),w=n(354).set,j=n(649),O=n(356),C=n(651),_=n(130),A=n(156),k=n(69),I=n(283),P=n(36),T=n(119),R=n(120),N=P("species"),M="Promise",D=k.get,q=k.set,B=k.getterFor(M),L=p,U=u.TypeError,V=u.document,z=u.process,F=l("fetch"),J=_.f,W=J,H=!!(V&&V.createEvent&&u.dispatchEvent),$="function"==typeof PromiseRejectionEvent,Y="unhandledrejection",K=I(M,(function(){if(!(b(L)!==String(L))){if(66===R)return!0;if(!T&&!$)return!0}if(c&&!L.prototype.finally)return!0;if(R>=51&&/native code/.test(L))return!1;var e=L.resolve(1),t=function(e){e((function(){}),(function(){}))};return(e.constructor={})[N]=t,!(e.then((function(){}))instanceof t)})),G=K||!x((function(e){L.all(e).catch((function(){}))})),Z=function(e){var t;return!(!v(e)||"function"!=typeof(t=e.then))&&t},X=function(e,t){if(!e.notified){e.notified=!0;var n=e.reactions;j((function(){for(var r=e.value,a=1==e.state,o=0;n.length>o;){var i,s,c,u=n[o++],l=a?u.ok:u.fail,p=u.resolve,f=u.reject,d=u.domain;try{l?(a||(2===e.rejection&&ne(e),e.rejection=1),!0===l?i=r:(d&&d.enter(),i=l(r),d&&(d.exit(),c=!0)),i===u.promise?f(U("Promise-chain cycle")):(s=Z(i))?s.call(i,p,f):p(i)):f(r)}catch(e){d&&!c&&d.exit(),f(e)}}e.reactions=[],e.notified=!1,t&&!e.rejection&&ee(e)}))}},Q=function(e,t,n){var r,a;H?((r=V.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),u.dispatchEvent(r)):r={promise:t,reason:n},!$&&(a=u["on"+e])?a(r):e===Y&&C("Unhandled promise rejection",n)},ee=function(e){w.call(u,(function(){var t,n=e.facade,r=e.value;if(te(e)&&(t=A((function(){T?z.emit("unhandledRejection",r,n):Q(Y,n,r)})),e.rejection=T||te(e)?2:1,t.error))throw t.value}))},te=function(e){return 1!==e.rejection&&!e.parent},ne=function(e){w.call(u,(function(){var t=e.facade;T?z.emit("rejectionHandled",t):Q("rejectionhandled",t,e.value)}))},re=function(e,t,n){return function(r){e(t,r,n)}},ae=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,X(e,!0))},oe=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw U("Promise can't be resolved itself");var r=Z(t);r?j((function(){var n={done:!1};try{r.call(t,re(oe,n,e),re(ae,n,e))}catch(t){ae(n,t,e)}})):(e.value=t,e.state=1,X(e,!1))}catch(t){ae({done:!1},t,e)}}};K&&(L=function(e){y(this,L,M),g(e),r.call(this);var t=D(this);try{e(re(oe,t),re(ae,t))}catch(e){ae(t,e)}},(r=function(e){q(this,{type:M,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=d(L.prototype,{then:function(e,t){var n=B(this),r=J(S(this,L));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=T?z.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&X(n,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),a=function(){var e=new r,t=D(e);this.promise=e,this.resolve=re(oe,t),this.reject=re(ae,t)},_.f=J=function(e){return e===L||e===o?new a(e):W(e)},c||"function"!=typeof p||(i=p.prototype.then,f(p.prototype,"then",(function(e,t){var n=this;return new L((function(e,t){i.call(n,e,t)})).then(e,t)}),{unsafe:!0}),"function"==typeof F&&s({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return O(L,F.apply(u,arguments))}}))),s({global:!0,wrap:!0,forced:K},{Promise:L}),h(L,M,!1,!0),m(M),o=l(M),s({target:M,stat:!0,forced:K},{reject:function(e){var t=J(this);return t.reject.call(void 0,e),t.promise}}),s({target:M,stat:!0,forced:c||K},{resolve:function(e){return O(c&&this===o?L:this,e)}}),s({target:M,stat:!0,forced:G},{all:function(e){var t=this,n=J(t),r=n.resolve,a=n.reject,o=A((function(){var n=g(t.resolve),o=[],i=0,s=1;E(e,(function(e){var c=i++,u=!1;o.push(void 0),s++,n.call(t,e).then((function(e){u||(u=!0,o[c]=e,--s||r(o))}),a)})),--s||r(o)}));return o.error&&a(o.value),n.promise},race:function(e){var t=this,n=J(t),r=n.reject,a=A((function(){var a=g(t.resolve);E(e,(function(e){a.call(t,e).then(n.resolve,r)}))}));return a.error&&r(a.value),n.promise}})},function(e,t,n){var r,a,o,i,s,c,u,l,p=n(38),f=n(89).f,d=n(354).set,h=n(355),m=n(650),v=n(119),g=p.MutationObserver||p.WebKitMutationObserver,y=p.document,b=p.process,E=p.Promise,x=f(p,"queueMicrotask"),S=x&&x.value;S||(r=function(){var e,t;for(v&&(e=b.domain)&&e.exit();a;){t=a.fn,a=a.next;try{t()}catch(e){throw a?i():o=void 0,e}}o=void 0,e&&e.enter()},h||v||m||!g||!y?E&&E.resolve?(u=E.resolve(void 0),l=u.then,i=function(){l.call(u,r)}):i=v?function(){b.nextTick(r)}:function(){d.call(p,r)}:(s=!0,c=y.createTextNode(""),new g(r).observe(c,{characterData:!0}),i=function(){c.data=s=!s})),e.exports=S||function(e){var t={fn:e,next:void 0};o&&(o.next=t),a||(a=t,i()),o=t}},function(e,t,n){var r=n(142);e.exports=/web0s(?!.*chrome)/i.test(r)},function(e,t,n){var r=n(38);e.exports=function(e,t){var n=r.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))}},function(e,t,n){"use strict";var r=n(24),a=n(81),o=n(351),i=n(34),s=n(62),c=n(353),u=n(356),l=n(93);r({target:"Promise",proto:!0,real:!0,forced:!!o&&i((function(){o.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=c(this,s("Promise")),n="function"==typeof e;return this.then(n?function(n){return u(t,e()).then((function(){return n}))}:e,n?function(n){return u(t,e()).then((function(){throw n}))}:e)}}),a||"function"!=typeof o||o.prototype.finally||l(o.prototype,"finally",s("Promise").prototype.finally)},function(e,t,n){n(350)},function(e,t,n){n(357)},function(e,t,n){"use strict";var r=n(24),a=n(130),o=n(156);r({target:"Promise",stat:!0},{try:function(e){var t=a.f(this),n=o(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}})},function(e,t,n){n(358)},function(e,t){e.exports=require("regenerator-runtime")},function(e,t,n){var r=n(297);e.exports=r},function(e,t,n){var r=n(349);e.exports=r},function(e,t,n){var r=n(661);e.exports=r},function(e,t,n){n(662);var r=n(31);e.exports=r.Object.values},function(e,t,n){var r=n(24),a=n(359).values;r({target:"Object",stat:!0},{values:function(e){return a(e)}})},function(e,t,n){var r=n(664);e.exports=r},function(e,t,n){n(665);var r=n(31);e.exports=r.Date.now},function(e,t,n){n(24)({target:"Date",stat:!0},{now:function(){return(new Date).getTime()}})},function(e,t,n){var r=n(64);e.exports=function(){return r.Date.now()}},function(e,t,n){e.exports=n(668)},function(e,t,n){var r=n(299);e.exports=r},function(e,t,n){e.exports=n(670)},function(e,t,n){var r=n(363);e.exports=r},function(e,t,n){n(24)({target:"Object",stat:!0,sham:!n(44)},{create:n(92)})},function(e,t,n){var r=n(364);function a(t,n){return e.exports=a=r||function(e,t){return e.__proto__=t,e},e.exports.default=e.exports,e.exports.__esModule=!0,a(t,n)}e.exports=a,e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(674);e.exports=r},function(e,t,n){n(675);var r=n(31);e.exports=r.Object.setPrototypeOf},function(e,t,n){n(24)({target:"Object",stat:!0},{setPrototypeOf:n(192)})},function(e,t,n){var r=n(677);e.exports=r},function(e,t,n){n(678);var r=n(31);e.exports=r.Reflect.construct},function(e,t,n){var r=n(24),a=n(62),o=n(67),i=n(46),s=n(40),c=n(92),u=n(298),l=n(34),p=a("Reflect","construct"),f=l((function(){function e(){}return!(p((function(){}),[],e)instanceof e)})),d=!l((function(){p((function(){}))})),h=f||d;r({target:"Reflect",stat:!0,forced:h,sham:h},{construct:function(e,t){o(e),i(t);var n=arguments.length<3?e:o(arguments[2]);if(d&&!f)return p(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return r.push.apply(r,t),new(u.apply(e,r))}var a=n.prototype,l=c(s(a)?a:Object.prototype),h=Function.apply.call(e,l,t);return s(h)?h:l}})},function(e,t,n){e.exports=n(680)},function(e,t,n){var r=n(681);e.exports=r},function(e,t,n){n(682);var r=n(31);e.exports=r.Object.getPrototypeOf},function(e,t,n){var r=n(24),a=n(34),o=n(61),i=n(124),s=n(294);r({target:"Object",stat:!0,forced:a((function(){i(1)})),sham:!s},{getPrototypeOf:function(e){return i(o(e))}})},function(e,t,n){var r=n(365);e.exports=function(){if("undefined"==typeof Reflect||!r)return!1;if(r.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(r(Boolean,[],(function(){}))),!0}catch(e){return!1}},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(19).default,a=n(10);e.exports=function(e,t){return!t||"object"!==r(t)&&"function"!=typeof t?a(e):t},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t){e.exports=function(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&!1!==t(e[n],n,e););return e}},function(e,t,n){var r=n(109),a=n(98);e.exports=function(e,t){return e&&r(t,a(t),e)}},function(e,t,n){var r=n(109),a=n(208);e.exports=function(e,t){return e&&r(t,a(t),e)}},function(e,t,n){var r=n(51),a=n(127),o=n(689),i=Object.prototype.hasOwnProperty;e.exports=function(e){if(!r(e))return o(e);var t=a(e),n=[];for(var s in e)("constructor"!=s||!t&&i.call(e,s))&&n.push(s);return n}},function(e,t){e.exports=function(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}},function(e,t,n){(function(e){var r=n(64),a=t&&!t.nodeType&&t,o=a&&"object"==typeof e&&e&&!e.nodeType&&e,i=o&&o.exports===a?r.Buffer:void 0,s=i?i.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var n=e.length,r=s?s(n):new e.constructor(n);return e.copy(r),r}}).call(this,n(201)(e))},function(e,t){e.exports=function(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}},function(e,t,n){var r=n(109),a=n(200);e.exports=function(e,t){return r(e,a(e),t)}},function(e,t,n){var r=n(109),a=n(367);e.exports=function(e,t){return r(e,a(e),t)}},function(e,t){var n=Object.prototype.hasOwnProperty;e.exports=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&n.call(e,"index")&&(r.index=e.index,r.input=e.input),r}},function(e,t,n){var r=n(210),a=n(696),o=n(697),i=n(698),s=n(699);e.exports=function(e,t,n){var c=e.constructor;switch(t){case"[object ArrayBuffer]":return r(e);case"[object Boolean]":case"[object Date]":return new c(+e);case"[object DataView]":return a(e,n);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Uint16Array]":case"[object Uint32Array]":return s(e,n);case"[object Map]":return new c;case"[object Number]":case"[object String]":return new c(e);case"[object RegExp]":return o(e);case"[object Set]":return new c;case"[object Symbol]":return i(e)}}},function(e,t,n){var r=n(210);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}},function(e,t){var n=/\w*$/;e.exports=function(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}},function(e,t,n){var r=n(105),a=r?r.prototype:void 0,o=a?a.valueOf:void 0;e.exports=function(e){return o?Object(o.call(e)):{}}},function(e,t,n){var r=n(210);e.exports=function(e,t){var n=t?r(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}},function(e,t,n){var r=n(701),a=n(209),o=n(127);e.exports=function(e){return"function"!=typeof e.constructor||o(e)?{}:r(a(e))}},function(e,t,n){var r=n(51),a=Object.create,o=function(){function e(){}return function(t){if(!r(t))return{};if(a)return a(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();e.exports=o},function(e,t,n){var r=n(703),a=n(204),o=n(205),i=o&&o.isMap,s=i?a(i):r;e.exports=s},function(e,t,n){var r=n(128),a=n(76);e.exports=function(e){return a(e)&&"[object Map]"==r(e)}},function(e,t,n){var r=n(705),a=n(204),o=n(205),i=o&&o.isSet,s=i?a(i):r;e.exports=s},function(e,t,n){var r=n(128),a=n(76);e.exports=function(e){return a(e)&&"[object Set]"==r(e)}},function(e,t,n){var r=n(106),a=n(707),o=n(708),i=n(107);e.exports=function(e,t){return t=r(t,e),null==(e=o(e,t))||delete e[i(a(t))]}},function(e,t){e.exports=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}},function(e,t,n){var r=n(155),a=n(324);e.exports=function(e,t){return t.length<2?e:r(e,a(t,0,-1))}},function(e,t,n){var r=n(225);e.exports=function(e){return r(e)?void 0:e}},function(e,t,n){var r=n(711);e.exports=function(e){return(null==e?0:e.length)?r(e,1):[]}},function(e,t,n){var r=n(199),a=n(712);e.exports=function e(t,n,o,i,s){var c=-1,u=t.length;for(o||(o=a),s||(s=[]);++c<u;){var l=t[c];n>0&&o(l)?n>1?e(l,n-1,o,i,s):r(s,l):i||(s[s.length]=l)}return s}},function(e,t,n){var r=n(105),a=n(152),o=n(47),i=r?r.isConcatSpreadable:void 0;e.exports=function(e){return o(e)||a(e)||!!(i&&e&&e[i])}},function(e,t){e.exports=function(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}},function(e,t,n){var r=n(715),a=n(362),o=n(207),i=a?function(e,t){return a(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:o;e.exports=i},function(e,t){e.exports=function(e){return function(){return e}}},function(e,t){var n=Date.now;e.exports=function(e){var t=0,r=0;return function(){var a=n(),o=16-(a-r);if(r=a,o>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}},function(e,t,n){var r=n(718);e.exports=r},function(e,t,n){n(719);var r=n(31);e.exports=r.Object.entries},function(e,t,n){var r=n(24),a=n(359).entries;r({target:"Object",stat:!0},{entries:function(e){return a(e)}})},function(e,t,n){var r=n(307);e.exports=r},function(e,t){!function(e){!function(t){var n="URLSearchParams"in e,r="Symbol"in e&&"iterator"in Symbol,a="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),o="FormData"in e,i="ArrayBuffer"in e;if(i)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&s.indexOf(Object.prototype.toString.call(e))>-1};function u(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function p(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r&&(t[Symbol.iterator]=function(){return t}),t}function f(e){this.map={},e instanceof f?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function d(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function h(e){return new Promise((function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}}))}function m(e){var t=new FileReader,n=h(t);return t.readAsArrayBuffer(e),n}function v(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function g(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:a&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:n&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():i&&a&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=v(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):i&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=v(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a&&(this.blob=function(){var e=d(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?d(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(m)}),this.text=function(){var e,t,n,r=d(this);if(r)return r;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=h(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o&&(this.formData=function(){return this.text().then(E)}),this.json=function(){return this.text().then(JSON.parse)},this}f.prototype.append=function(e,t){e=u(e),t=l(t);var n=this.map[e];this.map[e]=n?n+", "+t:t},f.prototype.delete=function(e){delete this.map[u(e)]},f.prototype.get=function(e){return e=u(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(u(e))},f.prototype.set=function(e,t){this.map[u(e)]=l(t)},f.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},f.prototype.keys=function(){var e=[];return this.forEach((function(t,n){e.push(n)})),p(e)},f.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),p(e)},f.prototype.entries=function(){var e=[];return this.forEach((function(t,n){e.push([n,t])})),p(e)},r&&(f.prototype[Symbol.iterator]=f.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function b(e,t){var n,r,a=(t=t||{}).body;if(e instanceof b){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new f(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,a||null==e._bodyInit||(a=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new f(t.headers)),this.method=(n=t.method||this.method||"GET",r=n.toUpperCase(),y.indexOf(r)>-1?r:n),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}function E(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),a=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(a))}})),t}function x(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},g.call(b.prototype),g.call(x.prototype),x.prototype.clone=function(){return new x(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},x.error=function(){var e=new x(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];x.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new x(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var n=Error(e);this.stack=n.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function w(e,n){return new Promise((function(r,o){var i=new b(e,n);if(i.signal&&i.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var s=new XMLHttpRequest;function c(){s.abort()}s.onload=function(){var e,t,n={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",t=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var n=e.split(":"),r=n.shift().trim();if(r){var a=n.join(":").trim();t.append(r,a)}})),t)};n.url="responseURL"in s?s.responseURL:n.headers.get("X-Request-URL");var a="response"in s?s.response:s.responseText;r(new x(a,n))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},s.open(i.method,i.url,!0),"include"===i.credentials?s.withCredentials=!0:"omit"===i.credentials&&(s.withCredentials=!1),"responseType"in s&&a&&(s.responseType="blob"),i.headers.forEach((function(e,t){s.setRequestHeader(t,e)})),i.signal&&(i.signal.addEventListener("abort",c),s.onreadystatechange=function(){4===s.readyState&&i.signal.removeEventListener("abort",c)}),s.send(void 0===i._bodyInit?null:i._bodyInit)}))}w.polyfill=!0,e.fetch||(e.fetch=w,e.Headers=f,e.Request=b,e.Response=x),t.Headers=f,t.Request=b,t.Response=x,t.fetch=w}({})}("undefined"!=typeof self?self:this)},function(e,t,n){var r=n(723),a=n(340);e.exports=function(e,t){return r(e,t,(function(t,n){return a(e,n)}))}},function(e,t,n){var r=n(155),a=n(360),o=n(106);e.exports=function(e,t,n){for(var i=-1,s=t.length,c={};++i<s;){var u=t[i],l=r(e,u);n(l,u)&&a(c,o(u,e),l)}return c}},function(e,t,n){e.exports=n(725)},function(e,t,n){var r=n(726);e.exports=r},function(e,t,n){n(727);var r=n(31);e.exports=r.Reflect.get},function(e,t,n){var r=n(24),a=n(40),o=n(46),i=n(48),s=n(89),c=n(124);r({target:"Reflect",stat:!0},{get:function e(t,n){var r,u,l=arguments.length<3?t:arguments[2];return o(t)===l?t[n]:(r=s.f(t,n))?i(r,"value")?r.value:void 0===r.get?void 0:r.get.call(l):a(u=c(t))?e(u,n,l):void 0}})},function(e,t,n){var r=n(159);e.exports=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=r(e)););return e},e.exports.default=e.exports,e.exports.__esModule=!0},function(e,t,n){var r=n(730);e.exports=r},function(e,t,n){var r=n(731),a=Array.prototype;e.exports=function(e){var t=e.splice;return e===a||e instanceof Array&&t===a.splice?r:t}},function(e,t,n){n(732);var r=n(39);e.exports=r("Array").splice},function(e,t,n){"use strict";var r=n(24),a=n(185),o=n(117),i=n(68),s=n(61),c=n(179),u=n(118),l=n(121)("splice"),p=Math.max,f=Math.min,d=9007199254740991,h="Maximum allowed length exceeded";r({target:"Array",proto:!0,forced:!l},{splice:function(e,t){var n,r,l,m,v,g,y=s(this),b=i(y.length),E=a(e,b),x=arguments.length;if(0===x?n=r=0:1===x?(n=0,r=b-E):(n=x-2,r=f(p(o(t),0),b-E)),b+n-r>d)throw TypeError(h);for(l=c(y,r),m=0;m<r;m++)(v=E+m)in y&&u(l,m,y[v]);if(l.length=r,n<r){for(m=E;m<b-r;m++)g=m+n,(v=m+r)in y?y[g]=y[v]:delete y[g];for(m=b;m>b-r+n;m--)delete y[m-1]}else if(n>r)for(m=b-r;m>E;m--)g=m+n-1,(v=m+r-1)in y?y[g]=y[v]:delete y[g];for(m=0;m<n;m++)y[m+E]=arguments[m+2];return y.length=b-r+n,l}})},function(e,t,n){var r=n(363);e.exports=r},function(e,t,n){var r=n(735);e.exports=r},function(e,t,n){n(143),n(736),n(63);var r=n(31);e.exports=r.WeakMap},function(e,t,n){"use strict";var r,a=n(38),o=n(129),i=n(158),s=n(372),c=n(738),u=n(40),l=n(69).enforce,p=n(288),f=!a.ActiveXObject&&"ActiveXObject"in a,d=Object.isExtensible,h=function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},m=e.exports=s("WeakMap",h,c);if(p&&f){r=c.getConstructor(h,"WeakMap",!0),i.REQUIRED=!0;var v=m.prototype,g=v.delete,y=v.has,b=v.get,E=v.set;o(v,{delete:function(e){if(u(e)&&!d(e)){var t=l(this);return t.frozen||(t.frozen=new r),g.call(this,e)||t.frozen.delete(e)}return g.call(this,e)},has:function(e){if(u(e)&&!d(e)){var t=l(this);return t.frozen||(t.frozen=new r),y.call(this,e)||t.frozen.has(e)}return y.call(this,e)},get:function(e){if(u(e)&&!d(e)){var t=l(this);return t.frozen||(t.frozen=new r),y.call(this,e)?b.call(this,e):t.frozen.get(e)}return b.call(this,e)},set:function(e,t){if(u(e)&&!d(e)){var n=l(this);n.frozen||(n.frozen=new r),y.call(this,e)?E.call(this,e,t):n.frozen.set(e,t)}else E.call(this,e,t);return this}})}},function(e,t,n){var r=n(34);e.exports=!r((function(){return Object.isExtensible(Object.preventExtensions({}))}))},function(e,t,n){"use strict";var r=n(129),a=n(158).getWeakData,o=n(46),i=n(40),s=n(108),c=n(100),u=n(75),l=n(48),p=n(69),f=p.set,d=p.getterFor,h=u.find,m=u.findIndex,v=0,g=function(e){return e.frozen||(e.frozen=new y)},y=function(){this.entries=[]},b=function(e,t){return h(e.entries,(function(e){return e[0]===t}))};y.prototype={get:function(e){var t=b(this,e);if(t)return t[1]},has:function(e){return!!b(this,e)},set:function(e,t){var n=b(this,e);n?n[1]=t:this.entries.push([e,t])},delete:function(e){var t=m(this.entries,(function(t){return t[0]===e}));return~t&&this.entries.splice(t,1),!!~t}},e.exports={getConstructor:function(e,t,n,u){var p=e((function(e,r){s(e,p,t),f(e,{type:t,id:v++,frozen:void 0}),null!=r&&c(r,e[u],{that:e,AS_ENTRIES:n})})),h=d(t),m=function(e,t,n){var r=h(e),i=a(o(t),!0);return!0===i?g(r).set(t,n):i[r.id]=n,e};return r(p.prototype,{delete:function(e){var t=h(this);if(!i(e))return!1;var n=a(e);return!0===n?g(t).delete(e):n&&l(n,t.id)&&delete n[t.id]},has:function(e){var t=h(this);if(!i(e))return!1;var n=a(e);return!0===n?g(t).has(e):n&&l(n,t.id)}}),r(p.prototype,n?{get:function(e){var t=h(this);if(i(e)){var n=a(e);return!0===n?g(t).get(e):n?n[t.id]:void 0}},set:function(e,t){return m(this,e,t)}}:{add:function(e){return m(this,e,!0)}}),p}}},function(e,t){e.exports=function(e,t,n){return e==e&&(void 0!==n&&(e=e<=n?e:n),void 0!==t&&(e=e>=t?e:t)),e}},function(e,t,n){var r=n(741),a=n(344);e.exports=function(e){return r((function(t,n){var r=-1,o=n.length,i=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,s&&a(n[0],n[1],s)&&(i=o<3?void 0:i,o=1),t=Object(t);++r<o;){var c=n[r];c&&e(t,c,r,i)}return t}))}},function(e,t,n){var r=n(207),a=n(370),o=n(371);e.exports=function(e,t){return o(a(e,t,r),e+"")}},function(e,t,n){var r=n(743);e.exports=r},function(e,t,n){n(744),n(746),n(374);var r=n(31);e.exports=r.URL},function(e,t,n){"use strict";n(83);var r,a=n(24),o=n(44),i=n(373),s=n(38),c=n(183),u=n(93),l=n(108),p=n(48),f=n(300),d=n(308),h=n(291).codeAt,m=n(745),v=n(82),g=n(374),y=n(69),b=s.URL,E=g.URLSearchParams,x=g.getState,S=y.set,w=y.getterFor("URL"),j=Math.floor,O=Math.pow,C="Invalid scheme",_="Invalid host",A="Invalid port",k=/[A-Za-z]/,I=/[\d+-.A-Za-z]/,P=/\d/,T=/^(0x|0X)/,R=/^[0-7]+$/,N=/^\d+$/,M=/^[\dA-Fa-f]+$/,D=/[\u0000\t\u000A\u000D #%/:?@[\\]]/,q=/[\u0000\t\u000A\u000D #/:?@[\\]]/,B=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,L=/[\t\u000A\u000D]/g,U=function(e,t){var n,r,a;if("["==t.charAt(0)){if("]"!=t.charAt(t.length-1))return _;if(!(n=z(t.slice(1,-1))))return _;e.host=n}else if(G(e)){if(t=m(t),D.test(t))return _;if(null===(n=V(t)))return _;e.host=n}else{if(q.test(t))return _;for(n="",r=d(t),a=0;a<r.length;a++)n+=Y(r[a],J);e.host=n}},V=function(e){var t,n,r,a,o,i,s,c=e.split(".");if(c.length&&""==c[c.length-1]&&c.pop(),(t=c.length)>4)return e;for(n=[],r=0;r<t;r++){if(""==(a=c[r]))return e;if(o=10,a.length>1&&"0"==a.charAt(0)&&(o=T.test(a)?16:8,a=a.slice(8==o?1:2)),""===a)i=0;else{if(!(10==o?N:8==o?R:M).test(a))return e;i=parseInt(a,o)}n.push(i)}for(r=0;r<t;r++)if(i=n[r],r==t-1){if(i>=O(256,5-t))return null}else if(i>255)return null;for(s=n.pop(),r=0;r<n.length;r++)s+=n[r]*O(256,3-r);return s},z=function(e){var t,n,r,a,o,i,s,c=[0,0,0,0,0,0,0,0],u=0,l=null,p=0,f=function(){return e.charAt(p)};if(":"==f()){if(":"!=e.charAt(1))return;p+=2,l=++u}for(;f();){if(8==u)return;if(":"!=f()){for(t=n=0;n<4&&M.test(f());)t=16*t+parseInt(f(),16),p++,n++;if("."==f()){if(0==n)return;if(p-=n,u>6)return;for(r=0;f();){if(a=null,r>0){if(!("."==f()&&r<4))return;p++}if(!P.test(f()))return;for(;P.test(f());){if(o=parseInt(f(),10),null===a)a=o;else{if(0==a)return;a=10*a+o}if(a>255)return;p++}c[u]=256*c[u]+a,2!=++r&&4!=r||u++}if(4!=r)return;break}if(":"==f()){if(p++,!f())return}else if(f())return;c[u++]=t}else{if(null!==l)return;p++,l=++u}}if(null!==l)for(i=u-l,u=7;0!=u&&i>0;)s=c[u],c[u--]=c[l+i-1],c[l+--i]=s;else if(8!=u)return;return c},F=function(e){var t,n,r,a;if("number"==typeof e){for(t=[],n=0;n<4;n++)t.unshift(e%256),e=j(e/256);return t.join(".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,n=1,r=null,a=0,o=0;o<8;o++)0!==e[o]?(a>n&&(t=r,n=a),r=null,a=0):(null===r&&(r=o),++a);return a>n&&(t=r,n=a),t}(e),n=0;n<8;n++)a&&0===e[n]||(a&&(a=!1),r===n?(t+=n?":":"::",a=!0):(t+=e[n].toString(16),n<7&&(t+=":")));return"["+t+"]"}return e},J={},W=f({},J,{" ":1,'"':1,"<":1,">":1,"`":1}),H=f({},W,{"#":1,"?":1,"{":1,"}":1}),$=f({},H,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Y=function(e,t){var n=h(e,0);return n>32&&n<127&&!p(t,e)?e:encodeURIComponent(e)},K={ftp:21,file:null,http:80,https:443,ws:80,wss:443},G=function(e){return p(K,e.scheme)},Z=function(e){return""!=e.username||""!=e.password},X=function(e){return!e.host||e.cannotBeABaseURL||"file"==e.scheme},Q=function(e,t){var n;return 2==e.length&&k.test(e.charAt(0))&&(":"==(n=e.charAt(1))||!t&&"|"==n)},ee=function(e){var t;return e.length>1&&Q(e.slice(0,2))&&(2==e.length||"/"===(t=e.charAt(2))||"\\"===t||"?"===t||"#"===t)},te=function(e){var t=e.path,n=t.length;!n||"file"==e.scheme&&1==n&&Q(t[0],!0)||t.pop()},ne=function(e){return"."===e||"%2e"===e.toLowerCase()},re={},ae={},oe={},ie={},se={},ce={},ue={},le={},pe={},fe={},de={},he={},me={},ve={},ge={},ye={},be={},Ee={},xe={},Se={},we={},je=function(e,t,n,a){var o,i,s,c,u,l=n||re,f=0,h="",m=!1,v=!1,g=!1;for(n||(e.scheme="",e.username="",e.password="",e.host=null,e.port=null,e.path=[],e.query=null,e.fragment=null,e.cannotBeABaseURL=!1,t=t.replace(B,"")),t=t.replace(L,""),o=d(t);f<=o.length;){switch(i=o[f],l){case re:if(!i||!k.test(i)){if(n)return C;l=oe;continue}h+=i.toLowerCase(),l=ae;break;case ae:if(i&&(I.test(i)||"+"==i||"-"==i||"."==i))h+=i.toLowerCase();else{if(":"!=i){if(n)return C;h="",l=oe,f=0;continue}if(n&&(G(e)!=p(K,h)||"file"==h&&(Z(e)||null!==e.port)||"file"==e.scheme&&!e.host))return;if(e.scheme=h,n)return void(G(e)&&K[e.scheme]==e.port&&(e.port=null));h="","file"==e.scheme?l=ve:G(e)&&a&&a.scheme==e.scheme?l=ie:G(e)?l=le:"/"==o[f+1]?(l=se,f++):(e.cannotBeABaseURL=!0,e.path.push(""),l=xe)}break;case oe:if(!a||a.cannotBeABaseURL&&"#"!=i)return C;if(a.cannotBeABaseURL&&"#"==i){e.scheme=a.scheme,e.path=a.path.slice(),e.query=a.query,e.fragment="",e.cannotBeABaseURL=!0,l=we;break}l="file"==a.scheme?ve:ce;continue;case ie:if("/"!=i||"/"!=o[f+1]){l=ce;continue}l=pe,f++;break;case se:if("/"==i){l=fe;break}l=Ee;continue;case ce:if(e.scheme=a.scheme,i==r)e.username=a.username,e.password=a.password,e.host=a.host,e.port=a.port,e.path=a.path.slice(),e.query=a.query;else if("/"==i||"\\"==i&&G(e))l=ue;else if("?"==i)e.username=a.username,e.password=a.password,e.host=a.host,e.port=a.port,e.path=a.path.slice(),e.query="",l=Se;else{if("#"!=i){e.username=a.username,e.password=a.password,e.host=a.host,e.port=a.port,e.path=a.path.slice(),e.path.pop(),l=Ee;continue}e.username=a.username,e.password=a.password,e.host=a.host,e.port=a.port,e.path=a.path.slice(),e.query=a.query,e.fragment="",l=we}break;case ue:if(!G(e)||"/"!=i&&"\\"!=i){if("/"!=i){e.username=a.username,e.password=a.password,e.host=a.host,e.port=a.port,l=Ee;continue}l=fe}else l=pe;break;case le:if(l=pe,"/"!=i||"/"!=h.charAt(f+1))continue;f++;break;case pe:if("/"!=i&&"\\"!=i){l=fe;continue}break;case fe:if("@"==i){m&&(h="%40"+h),m=!0,s=d(h);for(var y=0;y<s.length;y++){var b=s[y];if(":"!=b||g){var E=Y(b,$);g?e.password+=E:e.username+=E}else g=!0}h=""}else if(i==r||"/"==i||"?"==i||"#"==i||"\\"==i&&G(e)){if(m&&""==h)return"Invalid authority";f-=d(h).length+1,h="",l=de}else h+=i;break;case de:case he:if(n&&"file"==e.scheme){l=ye;continue}if(":"!=i||v){if(i==r||"/"==i||"?"==i||"#"==i||"\\"==i&&G(e)){if(G(e)&&""==h)return _;if(n&&""==h&&(Z(e)||null!==e.port))return;if(c=U(e,h))return c;if(h="",l=be,n)return;continue}"["==i?v=!0:"]"==i&&(v=!1),h+=i}else{if(""==h)return _;if(c=U(e,h))return c;if(h="",l=me,n==he)return}break;case me:if(!P.test(i)){if(i==r||"/"==i||"?"==i||"#"==i||"\\"==i&&G(e)||n){if(""!=h){var x=parseInt(h,10);if(x>65535)return A;e.port=G(e)&&x===K[e.scheme]?null:x,h=""}if(n)return;l=be;continue}return A}h+=i;break;case ve:if(e.scheme="file","/"==i||"\\"==i)l=ge;else{if(!a||"file"!=a.scheme){l=Ee;continue}if(i==r)e.host=a.host,e.path=a.path.slice(),e.query=a.query;else if("?"==i)e.host=a.host,e.path=a.path.slice(),e.query="",l=Se;else{if("#"!=i){ee(o.slice(f).join(""))||(e.host=a.host,e.path=a.path.slice(),te(e)),l=Ee;continue}e.host=a.host,e.path=a.path.slice(),e.query=a.query,e.fragment="",l=we}}break;case ge:if("/"==i||"\\"==i){l=ye;break}a&&"file"==a.scheme&&!ee(o.slice(f).join(""))&&(Q(a.path[0],!0)?e.path.push(a.path[0]):e.host=a.host),l=Ee;continue;case ye:if(i==r||"/"==i||"\\"==i||"?"==i||"#"==i){if(!n&&Q(h))l=Ee;else if(""==h){if(e.host="",n)return;l=be}else{if(c=U(e,h))return c;if("localhost"==e.host&&(e.host=""),n)return;h="",l=be}continue}h+=i;break;case be:if(G(e)){if(l=Ee,"/"!=i&&"\\"!=i)continue}else if(n||"?"!=i)if(n||"#"!=i){if(i!=r&&(l=Ee,"/"!=i))continue}else e.fragment="",l=we;else e.query="",l=Se;break;case Ee:if(i==r||"/"==i||"\\"==i&&G(e)||!n&&("?"==i||"#"==i)){if(".."===(u=(u=h).toLowerCase())||"%2e."===u||".%2e"===u||"%2e%2e"===u?(te(e),"/"==i||"\\"==i&&G(e)||e.path.push("")):ne(h)?"/"==i||"\\"==i&&G(e)||e.path.push(""):("file"==e.scheme&&!e.path.length&&Q(h)&&(e.host&&(e.host=""),h=h.charAt(0)+":"),e.path.push(h)),h="","file"==e.scheme&&(i==r||"?"==i||"#"==i))for(;e.path.length>1&&""===e.path[0];)e.path.shift();"?"==i?(e.query="",l=Se):"#"==i&&(e.fragment="",l=we)}else h+=Y(i,H);break;case xe:"?"==i?(e.query="",l=Se):"#"==i?(e.fragment="",l=we):i!=r&&(e.path[0]+=Y(i,J));break;case Se:n||"#"!=i?i!=r&&("'"==i&&G(e)?e.query+="%27":e.query+="#"==i?"%23":Y(i,J)):(e.fragment="",l=we);break;case we:i!=r&&(e.fragment+=Y(i,W))}f++}},Oe=function(e){var t,n,r=l(this,Oe,"URL"),a=arguments.length>1?arguments[1]:void 0,i=String(e),s=S(r,{type:"URL"});if(void 0!==a)if(a instanceof Oe)t=w(a);else if(n=je(t={},String(a)))throw TypeError(n);if(n=je(s,i,null,t))throw TypeError(n);var c=s.searchParams=new E,u=x(c);u.updateSearchParams(s.query),u.updateURL=function(){s.query=String(c)||null},o||(r.href=_e.call(r),r.origin=Ae.call(r),r.protocol=ke.call(r),r.username=Ie.call(r),r.password=Pe.call(r),r.host=Te.call(r),r.hostname=Re.call(r),r.port=Ne.call(r),r.pathname=Me.call(r),r.search=De.call(r),r.searchParams=qe.call(r),r.hash=Be.call(r))},Ce=Oe.prototype,_e=function(){var e=w(this),t=e.scheme,n=e.username,r=e.password,a=e.host,o=e.port,i=e.path,s=e.query,c=e.fragment,u=t+":";return null!==a?(u+="//",Z(e)&&(u+=n+(r?":"+r:"")+"@"),u+=F(a),null!==o&&(u+=":"+o)):"file"==t&&(u+="//"),u+=e.cannotBeABaseURL?i[0]:i.length?"/"+i.join("/"):"",null!==s&&(u+="?"+s),null!==c&&(u+="#"+c),u},Ae=function(){var e=w(this),t=e.scheme,n=e.port;if("blob"==t)try{return new URL(t.path[0]).origin}catch(e){return"null"}return"file"!=t&&G(e)?t+"://"+F(e.host)+(null!==n?":"+n:""):"null"},ke=function(){return w(this).scheme+":"},Ie=function(){return w(this).username},Pe=function(){return w(this).password},Te=function(){var e=w(this),t=e.host,n=e.port;return null===t?"":null===n?F(t):F(t)+":"+n},Re=function(){var e=w(this).host;return null===e?"":F(e)},Ne=function(){var e=w(this).port;return null===e?"":String(e)},Me=function(){var e=w(this),t=e.path;return e.cannotBeABaseURL?t[0]:t.length?"/"+t.join("/"):""},De=function(){var e=w(this).query;return e?"?"+e:""},qe=function(){return w(this).searchParams},Be=function(){var e=w(this).fragment;return e?"#"+e:""},Le=function(e,t){return{get:e,set:t,configurable:!0,enumerable:!0}};if(o&&c(Ce,{href:Le(_e,(function(e){var t=w(this),n=String(e),r=je(t,n);if(r)throw TypeError(r);x(t.searchParams).updateSearchParams(t.query)})),origin:Le(Ae),protocol:Le(ke,(function(e){var t=w(this);je(t,String(e)+":",re)})),username:Le(Ie,(function(e){var t=w(this),n=d(String(e));if(!X(t)){t.username="";for(var r=0;r<n.length;r++)t.username+=Y(n[r],$)}})),password:Le(Pe,(function(e){var t=w(this),n=d(String(e));if(!X(t)){t.password="";for(var r=0;r<n.length;r++)t.password+=Y(n[r],$)}})),host:Le(Te,(function(e){var t=w(this);t.cannotBeABaseURL||je(t,String(e),de)})),hostname:Le(Re,(function(e){var t=w(this);t.cannotBeABaseURL||je(t,String(e),he)})),port:Le(Ne,(function(e){var t=w(this);X(t)||(""==(e=String(e))?t.port=null:je(t,e,me))})),pathname:Le(Me,(function(e){var t=w(this);t.cannotBeABaseURL||(t.path=[],je(t,e+"",be))})),search:Le(De,(function(e){var t=w(this);""==(e=String(e))?t.query=null:("?"==e.charAt(0)&&(e=e.slice(1)),t.query="",je(t,e,Se)),x(t.searchParams).updateSearchParams(t.query)})),searchParams:Le(qe),hash:Le(Be,(function(e){var t=w(this);""!=(e=String(e))?("#"==e.charAt(0)&&(e=e.slice(1)),t.fragment="",je(t,e,we)):t.fragment=null}))}),u(Ce,"toJSON",(function(){return _e.call(this)}),{enumerable:!0}),u(Ce,"toString",(function(){return _e.call(this)}),{enumerable:!0}),b){var Ue=b.createObjectURL,Ve=b.revokeObjectURL;Ue&&u(Oe,"createObjectURL",(function(e){return Ue.apply(b,arguments)})),Ve&&u(Oe,"revokeObjectURL",(function(e){return Ve.apply(b,arguments)}))}v(Oe,"URL"),a({global:!0,forced:!i,sham:!o},{URL:Oe})},function(e,t,n){"use strict";var r=2147483647,a=/[^\0-\u007E]/,o=/[.\u3002\uFF0E\uFF61]/g,i="Overflow: input needs wider integers to process",s=Math.floor,c=String.fromCharCode,u=function(e){return e+22+75*(e<26)},l=function(e,t,n){var r=0;for(e=n?s(e/700):e>>1,e+=s(e/t);e>455;r+=36)e=s(e/35);return s(r+36*e/(e+38))},p=function(e){var t,n,a=[],o=(e=function(e){for(var t=[],n=0,r=e.length;n<r;){var a=e.charCodeAt(n++);if(a>=55296&&a<=56319&&n<r){var o=e.charCodeAt(n++);56320==(64512&o)?t.push(((1023&a)<<10)+(1023&o)+65536):(t.push(a),n--)}else t.push(a)}return t}(e)).length,p=128,f=0,d=72;for(t=0;t<e.length;t++)(n=e[t])<128&&a.push(c(n));var h=a.length,m=h;for(h&&a.push("-");m<o;){var v=r;for(t=0;t<e.length;t++)(n=e[t])>=p&&n<v&&(v=n);var g=m+1;if(v-p>s((r-f)/g))throw RangeError(i);for(f+=(v-p)*g,p=v,t=0;t<e.length;t++){if((n=e[t])<p&&++f>r)throw RangeError(i);if(n==p){for(var y=f,b=36;;b+=36){var E=b<=d?1:b>=d+26?26:b-d;if(y<E)break;var x=y-E,S=36-E;a.push(c(u(E+x%S))),y=s(x/S)}a.push(c(u(y))),d=l(f,g,m==h),f=0,++m}}++f,++p}return a.join("")};e.exports=function(e){var t,n,r=[],i=e.toLowerCase().replace(o,".").split(".");for(t=0;t<i.length;t++)n=i[t],r.push(a.test(n)?"xn--"+p(n):n);return r.join(".")}},function(e,t){},function(e,t,n){n(748);var r=n(31);e.exports=r.setTimeout},function(e,t,n){var r=n(24),a=n(38),o=n(142),i=[].slice,s=function(e){return function(t,n){var r=arguments.length>2,a=r?i.call(arguments,2):void 0;return e(r?function(){("function"==typeof t?t:Function(t)).apply(this,a)}:t,n)}};r({global:!0,bind:!0,forced:/MSIE .\./.test(o)},{setTimeout:s(a.setTimeout),setInterval:s(a.setInterval)})},function(e,t,n){var r=n(750);e.exports=r},function(e,t,n){n(751),n(143),n(83),n(63);var r=n(31);e.exports=r.Map},function(e,t,n){"use strict";var r=n(372),a=n(752);e.exports=r("Map",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),a)},function(e,t,n){"use strict";var r=n(60).f,a=n(92),o=n(129),i=n(91),s=n(108),c=n(100),u=n(191),l=n(352),p=n(44),f=n(158).fastKey,d=n(69),h=d.set,m=d.getterFor;e.exports={getConstructor:function(e,t,n,u){var l=e((function(e,r){s(e,l,t),h(e,{type:t,index:a(null),first:void 0,last:void 0,size:0}),p||(e.size=0),null!=r&&c(r,e[u],{that:e,AS_ENTRIES:n})})),d=m(t),v=function(e,t,n){var r,a,o=d(e),i=g(e,t);return i?i.value=n:(o.last=i={index:a=f(t,!0),key:t,value:n,previous:r=o.last,next:void 0,removed:!1},o.first||(o.first=i),r&&(r.next=i),p?o.size++:e.size++,"F"!==a&&(o.index[a]=i)),e},g=function(e,t){var n,r=d(e),a=f(t);if("F"!==a)return r.index[a];for(n=r.first;n;n=n.next)if(n.key==t)return n};return o(l.prototype,{clear:function(){for(var e=d(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,p?e.size=0:this.size=0},delete:function(e){var t=this,n=d(t),r=g(t,e);if(r){var a=r.next,o=r.previous;delete n.index[r.index],r.removed=!0,o&&(o.next=a),a&&(a.previous=o),n.first==r&&(n.first=a),n.last==r&&(n.last=o),p?n.size--:t.size--}return!!r},forEach:function(e){for(var t,n=d(this),r=i(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!g(this,e)}}),o(l.prototype,n?{get:function(e){var t=g(this,e);return t&&t.value},set:function(e,t){return v(this,0===e?0:e,t)}}:{add:function(e){return v(this,e=0===e?0:e,e)}}),p&&r(l.prototype,"size",{get:function(){return d(this).size}}),l},setStrong:function(e,t,n){var r=t+" Iterator",a=m(t),o=m(r);u(e,t,(function(e,t){h(this,{type:r,target:e,state:a(e),kind:t,last:void 0})}),(function(){for(var e=o(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:(e.target=void 0,{value:void 0,done:!0})}),n?"entries":"values",!n,!0),l(t)}}},function(e,t,n){n(63);var r=n(754),a=n(74),o=Array.prototype,i={DOMTokenList:!0,NodeList:!0};e.exports=function(e){var t=e.keys;return e===o||e instanceof Array&&t===o.keys||i.hasOwnProperty(a(e))?r:t}},function(e,t,n){var r=n(755);e.exports=r},function(e,t,n){n(125);var r=n(39);e.exports=r("Array").keys},function(e,t,n){n(63);var r=n(757),a=n(74),o=Array.prototype,i={DOMTokenList:!0,NodeList:!0};e.exports=function(e){var t=e.values;return e===o||e instanceof Array&&t===o.values||i.hasOwnProperty(a(e))?r:t}},function(e,t,n){var r=n(758);e.exports=r},function(e,t,n){n(125);var r=n(39);e.exports=r("Array").values},function(e,t,n){var r=n(760);e.exports=r},function(e,t,n){var r=n(761),a=Array.prototype;e.exports=function(e){var t=e.lastIndexOf;return e===a||e instanceof Array&&t===a.lastIndexOf?r:t}},function(e,t,n){n(762);var r=n(39);e.exports=r("Array").lastIndexOf},function(e,t,n){var r=n(24),a=n(763);r({target:"Array",proto:!0,forced:a!==[].lastIndexOf},{lastIndexOf:a})},function(e,t,n){"use strict";var r=n(58),a=n(117),o=n(68),i=n(95),s=Math.min,c=[].lastIndexOf,u=!!c&&1/[1].lastIndexOf(1,-0)<0,l=i("lastIndexOf"),p=u||!l;e.exports=p?function(e){if(u)return c.apply(this,arguments)||0;var t=r(this),n=o(t.length),i=n-1;for(arguments.length>1&&(i=s(i,a(arguments[1]))),i<0&&(i=n+i);i>=0;i--)if(i in t&&t[i]===e)return i||0;return-1}:c},function(e,t,n){var r={"./all.js":266,"./auth/actions.js":73,"./auth/index.js":229,"./auth/reducers.js":230,"./auth/selectors.js":231,"./auth/spec-wrap-actions.js":232,"./configs/actions.js":112,"./configs/helpers.js":131,"./configs/index.js":268,"./configs/reducers.js":237,"./configs/selectors.js":236,"./configs/spec-actions.js":235,"./deep-linking/helpers.js":135,"./deep-linking/index.js":238,"./deep-linking/layout.js":239,"./deep-linking/operation-tag-wrapper.jsx":241,"./deep-linking/operation-wrapper.jsx":240,"./download-url.js":234,"./err/actions.js":53,"./err/error-transformers/hook.js":103,"./err/error-transformers/transformers/not-of-type.js":215,"./err/error-transformers/transformers/parameter-oneof.js":216,"./err/index.js":213,"./err/reducers.js":214,"./err/selectors.js":217,"./filter/index.js":242,"./filter/opsFilter.js":243,"./layout/actions.js":86,"./layout/index.js":218,"./layout/reducers.js":219,"./layout/selectors.js":220,"./logs/index.js":227,"./oas3/actions.js":50,"./oas3/auth-extensions/wrap-selectors.js":247,"./oas3/components/callbacks.jsx":250,"./oas3/components/http-auth.jsx":255,"./oas3/components/index.js":249,"./oas3/components/operation-link.jsx":251,"./oas3/components/operation-servers.jsx":256,"./oas3/components/request-body-editor.jsx":254,"./oas3/components/request-body.jsx":132,"./oas3/components/servers-container.jsx":253,"./oas3/components/servers.jsx":252,"./oas3/helpers.jsx":32,"./oas3/index.js":245,"./oas3/reducers.js":265,"./oas3/selectors.js":264,"./oas3/spec-extensions/selectors.js":248,"./oas3/spec-extensions/wrap-selectors.js":246,"./oas3/wrap-components/auth-item.jsx":259,"./oas3/wrap-components/index.js":257,"./oas3/wrap-components/json-schema-string.jsx":263,"./oas3/wrap-components/markdown.jsx":258,"./oas3/wrap-components/model.jsx":262,"./oas3/wrap-components/online-validator-badge.js":261,"./oas3/wrap-components/version-stamp.jsx":260,"./on-complete/index.js":244,"./samples/fn.js":111,"./samples/index.js":226,"./spec/actions.js":42,"./spec/index.js":221,"./spec/reducers.js":222,"./spec/selectors.js":78,"./spec/wrap-actions.js":223,"./swagger-js/configs-wrap-actions.js":228,"./swagger-js/index.js":267,"./util/index.js":233,"./view/index.js":224,"./view/root-injects.jsx":134};function a(e){var t=o(e);return n(t)}function o(e){if(!n.o(r,e)){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}return r[e]}a.keys=function(){return Object.keys(r)},a.resolve=o,e.exports=a,a.id=764},function(e,t,n){"use strict";n.r(t);var r={};n.r(r),n.d(r,"Container",(function(){return Nn})),n.d(r,"Col",(function(){return Dn})),n.d(r,"Row",(function(){return qn})),n.d(r,"Button",(function(){return Bn})),n.d(r,"TextArea",(function(){return Ln})),n.d(r,"Input",(function(){return Un})),n.d(r,"Select",(function(){return Vn})),n.d(r,"Link",(function(){return zn})),n.d(r,"Collapse",(function(){return Jn}));var a={};n.r(a),n.d(a,"JsonSchemaForm",(function(){return Nr})),n.d(a,"JsonSchema_string",(function(){return Mr})),n.d(a,"JsonSchema_array",(function(){return Dr})),n.d(a,"JsonSchemaArrayItemText",(function(){return qr})),n.d(a,"JsonSchemaArrayItemFile",(function(){return Br})),n.d(a,"JsonSchema_boolean",(function(){return Lr})),n.d(a,"JsonSchema_object",(function(){return Vr}));var o=n(19),i=n.n(o),s=n(2),c=n.n(s),u=n(12),l=n.n(u),p=n(17),f=n.n(p),d=n(30),h=n.n(d),m=n(70),v=n.n(m),g=n(3),y=n.n(g),b=n(6),E=n.n(b),x=n(7),S=n.n(x),w=n(29),j=n.n(w),O=n(22),C=n.n(O),_=n(23),A=n.n(_),k=n(13),I=n.n(k),P=n(21),T=n.n(P),R=n(4),N=n.n(R),M=n(0),D=n.n(M),q=n(136),B=n(1),L=n.n(B),U=n(376),V=n(110),z=n.n(V),F=n(377),J=n.n(F),W=n(53),H=n(26),$=n(5),Y=function(e){return e};var K=function(){function e(){var t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};E()(this,e),v()(this,{state:{},plugins:[],system:{configs:{},fn:{},components:{},rootInjects:{},statePlugins:{}},boundSystem:{},toolbox:{}},n),this.getSystem=j()(t=this._getSystem).call(t,this),this.store=ee(Y,Object(B.fromJS)(this.state),this.getSystem),this.buildSystem(!1),this.register(this.plugins)}return S()(e,[{key:"getStore",value:function(){return this.store}},{key:"register",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=G(e,this.getSystem());X(this.system,n),t&&this.buildSystem();var r=Z.call(this.system,e,this.getSystem());r&&this.buildSystem()}},{key:"buildSystem",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=this.getStore().dispatch,n=this.getStore().getState;this.boundSystem=C()({},this.getRootInjects(),this.getWrappedAndBoundActions(t),this.getWrappedAndBoundSelectors(n,this.getSystem),this.getStateThunks(n),this.getFn(),this.getConfigs()),e&&this.rebuildReducer()}},{key:"_getSystem",value:function(){return this.boundSystem}},{key:"getRootInjects",value:function(){var e,t,n;return C()({getSystem:this.getSystem,getStore:j()(e=this.getStore).call(e,this),getComponents:j()(t=this.getComponents).call(t,this),getState:this.getStore().getState,getConfigs:j()(n=this._getConfigs).call(n,this),Im:L.a,React:D.a},this.system.rootInjects||{})}},{key:"_getConfigs",value:function(){return this.system.configs}},{key:"getConfigs",value:function(){return{configs:this.system.configs}}},{key:"setConfigs",value:function(e){this.system.configs=e}},{key:"rebuildReducer",value:function(){var e,t,n,r;this.store.replaceReducer((r=this.system.statePlugins,e=Object($.y)(r,(function(e){return e.reducers})),n=T()(t=f()(e)).call(t,(function(t,n){return t[n]=function(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new B.Map,n=arguments.length>1?arguments[1]:void 0;if(!e)return t;var r=e[n.type];if(r){var a=Q(r)(t,n);return null===a?t:a}return t}}(e[n]),t}),{}),f()(n).length?Object(U.combineReducers)(n):Y))}},{key:"getType",value:function(e){var t=e[0].toUpperCase()+A()(e).call(e,1);return Object($.z)(this.system.statePlugins,(function(n,r){var a=n[e];if(a)return y()({},r+t,a)}))}},{key:"getSelectors",value:function(){return this.getType("selectors")}},{key:"getActions",value:function(){var e=this.getType("actions");return Object($.y)(e,(function(e){return Object($.z)(e,(function(e,t){if(Object($.r)(e))return y()({},t,e)}))}))}},{key:"getWrappedAndBoundActions",value:function(e){var t=this,n=this.getBoundActions(e);return Object($.y)(n,(function(e,n){var r=t.system.statePlugins[A()(n).call(n,0,-7)].wrapActions;return r?Object($.y)(e,(function(e,n){var a=r[n];return a?(I()(a)||(a=[a]),T()(a).call(a,(function(e,n){var r=function(){return n(e,t.getSystem()).apply(void 0,arguments)};if(!Object($.r)(r))throw new TypeError("wrapActions needs to return a function that returns a new function (ie the wrapped action)");return Q(r)}),e||Function.prototype)):e})):e}))}},{key:"getWrappedAndBoundSelectors",value:function(e,t){var n=this,r=this.getBoundSelectors(e,t);return Object($.y)(r,(function(t,r){var a=[A()(r).call(r,0,-9)],o=n.system.statePlugins[a].wrapSelectors;return o?Object($.y)(t,(function(t,r){var i=o[r];return i?(I()(i)||(i=[i]),T()(i).call(i,(function(t,r){var o=function(){for(var o,i=arguments.length,s=new Array(i),u=0;u<i;u++)s[u]=arguments[u];return r(t,n.getSystem()).apply(void 0,c()(o=[e().getIn(a)]).call(o,s))};if(!Object($.r)(o))throw new TypeError("wrapSelector needs to return a function that returns a new function (ie the wrapped action)");return o}),t||Function.prototype)):t})):t}))}},{key:"getStates",value:function(e){var t;return T()(t=f()(this.system.statePlugins)).call(t,(function(t,n){return t[n]=e.get(n),t}),{})}},{key:"getStateThunks",value:function(e){var t;return T()(t=f()(this.system.statePlugins)).call(t,(function(t,n){return t[n]=function(){return e().get(n)},t}),{})}},{key:"getFn",value:function(){return{fn:this.system.fn}}},{key:"getComponents",value:function(e){var t=this,n=this.system.components[e];return I()(n)?T()(n).call(n,(function(e,n){return n(e,t.getSystem())})):void 0!==e?this.system.components[e]:this.system.components}},{key:"getBoundSelectors",value:function(e,t){return Object($.y)(this.getSelectors(),(function(n,r){var a=[A()(r).call(r,0,-9)],o=function(){return e().getIn(a)};return Object($.y)(n,(function(e){return function(){for(var n,r=arguments.length,a=new Array(r),i=0;i<r;i++)a[i]=arguments[i];var s=Q(e).apply(null,c()(n=[o()]).call(n,a));return"function"==typeof s&&(s=Q(s)(t())),s}}))}))}},{key:"getBoundActions",value:function(e){e=e||this.getStore().dispatch;var t=this.getActions(),n=function e(t){return"function"!=typeof t?Object($.y)(t,(function(t){return e(t)})):function(){var e=null;try{e=t.apply(void 0,arguments)}catch(t){e={type:W.NEW_THROWN_ERR,error:!0,payload:z()(t)}}finally{return e}}};return Object($.y)(t,(function(t){return Object(q.bindActionCreators)(n(t),e)}))}},{key:"getMapStateToProps",value:function(){var e=this;return function(){return C()({},e.getSystem())}}},{key:"getMapDispatchToProps",value:function(e){var t=this;return function(n){return v()({},t.getWrappedAndBoundActions(n),t.getFn(),e)}}}]),e}();function G(e,t){return Object($.u)(e)&&!Object($.p)(e)?J()({},e):Object($.s)(e)?G(e(t),t):Object($.p)(e)?T()(n=N()(e).call(e,(function(e){return G(e,t)}))).call(n,X,{}):{};var n}function Z(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=r.hasLoaded,o=a;return Object($.u)(e)&&!Object($.p)(e)&&"function"==typeof e.afterLoad&&(o=!0,Q(e.afterLoad).call(this,t)),Object($.s)(e)?Z.call(this,e(t),t,{hasLoaded:o}):Object($.p)(e)?N()(e).call(e,(function(e){return Z.call(n,e,t,{hasLoaded:o})})):o}function X(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!Object($.u)(e))return{};if(!Object($.u)(t))return e;t.wrapComponents&&(Object($.y)(t.wrapComponents,(function(n,r){var a=e.components&&e.components[r];a&&I()(a)?(e.components[r]=c()(a).call(a,[n]),delete t.wrapComponents[r]):a&&(e.components[r]=[a,n],delete t.wrapComponents[r])})),f()(t.wrapComponents).length||delete t.wrapComponents);var n=e.statePlugins;if(Object($.u)(n))for(var r in n){var a=n[r];if(Object($.u)(a)&&Object($.u)(a.wrapActions)){var o=a.wrapActions;for(var i in o){var s,u=o[i];if(I()(u)||(u=[u],o[i]=u),t&&t.statePlugins&&t.statePlugins[r]&&t.statePlugins[r].wrapActions&&t.statePlugins[r].wrapActions[i])t.statePlugins[r].wrapActions[i]=c()(s=o[i]).call(s,t.statePlugins[r].wrapActions[i])}}}return v()(e,t)}function Q(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.logErrors,r=void 0===n||n;return"function"!=typeof e?e:function(){try{for(var t,n=arguments.length,a=new Array(n),o=0;o<n;o++)a[o]=arguments[o];return e.call.apply(e,c()(t=[this]).call(t,a))}catch(e){return r&&console.error(e),null}}}function ee(e,t,n){return function(e,t,n){var r=[Object($.K)(n)],a=H.a.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||q.compose;return Object(q.createStore)(e,t,a(q.applyMiddleware.apply(void 0,r)))}(e,t,n)}var te=n(213),ne=n(218),re=n(221),ae=n(224),oe=n(226),ie=n(227),se=n(267),ce=n(229),ue=n(233),le=n(234),pe=n(268),fe=n(238),de=n(242),he=n(244),me=n(10),ve=n.n(me),ge=n(8),ye=n.n(ge),be=n(9),Ee=n.n(be),xe=n(14),Se=n.n(xe),we=(n(11),n(27),n(52)),je=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"toggleShown",(function(){var e=a.props,t=e.layoutActions,n=e.tag,r=e.operationId,o=e.isShown,i=a.getResolvedSubtree();o||void 0!==i||a.requestResolvedSubtree(),t.show(["operations",n,r],!o)})),y()(ve()(a),"onCancelClick",(function(){a.setState({tryItOutEnabled:!a.state.tryItOutEnabled})})),y()(ve()(a),"onTryoutClick",(function(){a.setState({tryItOutEnabled:!a.state.tryItOutEnabled})})),y()(ve()(a),"onExecute",(function(){a.setState({executeInProgress:!0})})),y()(ve()(a),"getResolvedSubtree",(function(){var e=a.props,t=e.specSelectors,n=e.path,r=e.method,o=e.specPath;return o?t.specResolvedSubtree(o.toJS()):t.specResolvedSubtree(["paths",n,r])})),y()(ve()(a),"requestResolvedSubtree",(function(){var e=a.props,t=e.specActions,n=e.path,r=e.method,o=e.specPath;return o?t.requestResolvedSubtree(o.toJS()):t.requestResolvedSubtree(["paths",n,r])}));var o=e.getConfigs().tryItOutEnabled;return a.state={tryItOutEnabled:!0===o||"true"===o,executeInProgress:!1},a}return S()(n,[{key:"mapStateToProps",value:function(e,t){var n,r=t.op,a=t.layoutSelectors,o=(0,t.getConfigs)(),i=o.docExpansion,s=o.deepLinking,u=o.displayOperationId,l=o.displayRequestDuration,p=o.supportedSubmitMethods,f=a.showSummary(),d=r.getIn(["operation","__originalOperationId"])||r.getIn(["operation","operationId"])||Object(we.e)(r.get("operation"),t.path,t.method)||r.get("id"),h=["operations",t.tag,d],m=s&&"false"!==s,v=Se()(p).call(p,t.method)>=0&&(void 0===t.allowTryItOut?t.specSelectors.allowTryItOutFor(t.path,t.method):t.allowTryItOut),g=r.getIn(["operation","security"])||t.specSelectors.security();return{operationId:d,isDeepLinkingEnabled:m,showSummary:f,displayOperationId:u,displayRequestDuration:l,allowTryItOut:v,security:g,isAuthorized:t.authSelectors.isAuthorized(g),isShown:a.isShown(h,"full"===i),jumpToKey:c()(n="paths.".concat(t.path,".")).call(n,t.method),response:t.specSelectors.responseFor(t.path,t.method),request:t.specSelectors.requestFor(t.path,t.method)}}},{key:"componentDidMount",value:function(){var e=this.props.isShown,t=this.getResolvedSubtree();e&&void 0===t&&this.requestResolvedSubtree()}},{key:"componentWillReceiveProps",value:function(e){var t=e.response,n=e.isShown,r=this.getResolvedSubtree();t!==this.props.response&&this.setState({executeInProgress:!1}),n&&void 0===r&&this.requestResolvedSubtree()}},{key:"render",value:function(){var e=this.props,t=e.op,n=e.tag,r=e.path,a=e.method,o=e.security,i=e.isAuthorized,s=e.operationId,c=e.showSummary,u=e.isShown,l=e.jumpToKey,p=e.allowTryItOut,f=e.response,d=e.request,h=e.displayOperationId,m=e.displayRequestDuration,v=e.isDeepLinkingEnabled,g=e.specPath,y=e.specSelectors,b=e.specActions,E=e.getComponent,x=e.getConfigs,S=e.layoutSelectors,w=e.layoutActions,j=e.authActions,O=e.authSelectors,C=e.oas3Actions,_=e.oas3Selectors,A=e.fn,k=E("operation"),I=this.getResolvedSubtree()||Object(B.Map)(),P=Object(B.fromJS)({op:I,tag:n,path:r,summary:t.getIn(["operation","summary"])||"",deprecated:I.get("deprecated")||t.getIn(["operation","deprecated"])||!1,method:a,security:o,isAuthorized:i,operationId:s,originalOperationId:I.getIn(["operation","__originalOperationId"]),showSummary:c,isShown:u,jumpToKey:l,allowTryItOut:p,request:d,displayOperationId:h,displayRequestDuration:m,isDeepLinkingEnabled:v,executeInProgress:this.state.executeInProgress,tryItOutEnabled:this.state.tryItOutEnabled});return D.a.createElement(k,{operation:P,response:f,request:d,isShown:u,toggleShown:this.toggleShown,onTryoutClick:this.onTryoutClick,onCancelClick:this.onCancelClick,onExecute:this.onExecute,specPath:g,specActions:b,specSelectors:y,oas3Actions:C,oas3Selectors:_,layoutActions:w,layoutSelectors:S,authActions:j,authSelectors:O,getComponent:E,getConfigs:x,fn:A})}}]),n}(M.PureComponent);y()(je,"defaultProps",{showSummary:!0,response:null,allowTryItOut:!0,displayOperationId:!1,displayRequestDuration:!1});var Oe=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"getLayout",value:function(){var e=this.props,t=e.getComponent,n=e.layoutSelectors.current(),r=t(n,!0);return r||function(){return D.a.createElement("h1",null,' No layout defined for "',n,'" ')}}},{key:"render",value:function(){var e=this.getLayout();return D.a.createElement(e,null)}}]),n}(D.a.Component);Oe.defaultProps={};var Ce=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"close",(function(){r.props.authActions.showDefinitions(!1)})),r}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.authSelectors,r=t.authActions,a=t.getComponent,o=t.errSelectors,i=t.specSelectors,s=t.fn.AST,c=void 0===s?{}:s,u=n.shownDefinitions(),l=a("auths");return D.a.createElement("div",{className:"dialog-ux"},D.a.createElement("div",{className:"backdrop-ux"}),D.a.createElement("div",{className:"modal-ux"},D.a.createElement("div",{className:"modal-dialog-ux"},D.a.createElement("div",{className:"modal-ux-inner"},D.a.createElement("div",{className:"modal-ux-header"},D.a.createElement("h3",null,"Available authorizations"),D.a.createElement("button",{type:"button",className:"close-modal",onClick:this.close},D.a.createElement("svg",{width:"20",height:"20"},D.a.createElement("use",{href:"#close",xlinkHref:"#close"})))),D.a.createElement("div",{className:"modal-ux-content"},N()(e=u.valueSeq()).call(e,(function(e,t){return D.a.createElement(l,{key:t,AST:c,definitions:e,getComponent:a,errSelectors:o,authSelectors:n,authActions:r,specSelectors:i})})))))))}}]),n}(D.a.Component),_e=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.isAuthorized,n=e.showPopup,r=e.onClick,a=(0,e.getComponent)("authorizationPopup",!0);return D.a.createElement("div",{className:"auth-wrapper"},D.a.createElement("button",{className:t?"btn authorize locked":"btn authorize unlocked",onClick:r},D.a.createElement("span",null,"Authorize"),D.a.createElement("svg",{width:"20",height:"20"},D.a.createElement("use",{href:t?"#locked":"#unlocked",xlinkHref:t?"#locked":"#unlocked"}))),n&&D.a.createElement(a,null))}}]),n}(D.a.Component),Ae=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.authActions,n=e.authSelectors,r=e.specSelectors,a=e.getComponent,o=r.securityDefinitions(),i=n.definitionsToAuthorize(),s=a("authorizeBtn");return o?D.a.createElement(s,{onClick:function(){return t.showDefinitions(i)},isAuthorized:!!n.authorized().size,showPopup:!!n.shownDefinitions(),getComponent:a}):null}}]),n}(D.a.Component),ke=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onClick",(function(e){e.stopPropagation();var t=r.props.onClick;t&&t()})),r}return S()(n,[{key:"render",value:function(){var e=this.props.isAuthorized;return D.a.createElement("button",{className:e?"authorization__btn locked":"authorization__btn unlocked","aria-label":e?"authorization button locked":"authorization button unlocked",onClick:this.onClick},D.a.createElement("svg",{width:"20",height:"20"},D.a.createElement("use",{href:e?"#locked":"#unlocked",xlinkHref:e?"#locked":"#unlocked"})))}}]),n}(D.a.Component),Ie=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onAuthChange",(function(e){var t=e.name;a.setState(y()({},t,e))})),y()(ve()(a),"submitAuth",(function(e){e.preventDefault(),a.props.authActions.authorizeWithPersistOption(a.state)})),y()(ve()(a),"logoutClick",(function(e){e.preventDefault();var t=a.props,n=t.authActions,r=t.definitions,o=N()(r).call(r,(function(e,t){return t})).toArray();a.setState(T()(o).call(o,(function(e,t){return e[t]="",e}),{})),n.logoutWithPersistOption(o)})),y()(ve()(a),"close",(function(e){e.preventDefault(),a.props.authActions.showDefinitions(!1)})),a.state={},a}return S()(n,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.definitions,a=n.getComponent,o=n.authSelectors,i=n.errSelectors,s=a("AuthItem"),c=a("oauth2",!0),u=a("Button"),p=o.authorized(),f=l()(r).call(r,(function(e,t){return!!p.get(t)})),d=l()(r).call(r,(function(e){return"oauth2"!==e.get("type")})),h=l()(r).call(r,(function(e){return"oauth2"===e.get("type")}));return D.a.createElement("div",{className:"auth-container"},!!d.size&&D.a.createElement("form",{onSubmit:this.submitAuth},N()(d).call(d,(function(e,n){return D.a.createElement(s,{key:n,schema:e,name:n,getComponent:a,onAuthChange:t.onAuthChange,authorized:p,errSelectors:i})})).toArray(),D.a.createElement("div",{className:"auth-btn-wrapper"},d.size===f.size?D.a.createElement(u,{className:"btn modal-btn auth",onClick:this.logoutClick},"Logout"):D.a.createElement(u,{type:"submit",className:"btn modal-btn auth authorize"},"Authorize"),D.a.createElement(u,{className:"btn modal-btn auth btn-done",onClick:this.close},"Close"))),h&&h.size?D.a.createElement("div",null,D.a.createElement("div",{className:"scope-def"},D.a.createElement("p",null,"Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes."),D.a.createElement("p",null,"API requires the following scopes. Select which ones you want to grant to Swagger UI.")),N()(e=l()(r).call(r,(function(e){return"oauth2"===e.get("type")}))).call(e,(function(e,t){return D.a.createElement("div",{key:t},D.a.createElement(c,{authorized:p,schema:e,name:t}))})).toArray()):null)}}]),n}(D.a.Component),Pe=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.schema,r=t.name,a=t.getComponent,o=t.onAuthChange,i=t.authorized,s=t.errSelectors,c=a("apiKeyAuth"),u=a("basicAuth"),l=n.get("type");switch(l){case"apiKey":e=D.a.createElement(c,{key:r,schema:n,name:r,errSelectors:s,authorized:i,getComponent:a,onChange:o});break;case"basic":e=D.a.createElement(u,{key:r,schema:n,name:r,errSelectors:s,authorized:i,getComponent:a,onChange:o});break;default:e=D.a.createElement("div",{key:r},"Unknown security definition type ",l)}return D.a.createElement("div",{key:"".concat(r,"-jump")},e)}}]),n}(D.a.Component),Te=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props.error,t=e.get("level"),n=e.get("message"),r=e.get("source");return D.a.createElement("div",{className:"errors"},D.a.createElement("b",null,r," ",t),D.a.createElement("span",null,n))}}]),n}(D.a.Component),Re=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onChange",(function(e){var t=a.props.onChange,n=e.target.value,r=C()({},a.state,{value:n});a.setState(r),t(r)}));var o=a.props,i=o.name,s=o.schema,c=a.getValue();return a.state={name:i,schema:s,value:c},a}return S()(n,[{key:"getValue",value:function(){var e=this.props,t=e.name,n=e.authorized;return n&&n.getIn([t,"value"])}},{key:"render",value:function(){var e,t,n=this.props,r=n.schema,a=n.getComponent,o=n.errSelectors,i=n.name,s=a("Input"),c=a("Row"),u=a("Col"),p=a("authError"),f=a("Markdown",!0),d=a("JumpToPath",!0),h=this.getValue(),m=l()(e=o.allErrors()).call(e,(function(e){return e.get("authId")===i}));return D.a.createElement("div",null,D.a.createElement("h4",null,D.a.createElement("code",null,i||r.get("name"))," (apiKey)",D.a.createElement(d,{path:["securityDefinitions",i]})),h&&D.a.createElement("h6",null,"Authorized"),D.a.createElement(c,null,D.a.createElement(f,{source:r.get("description")})),D.a.createElement(c,null,D.a.createElement("p",null,"Name: ",D.a.createElement("code",null,r.get("name")))),D.a.createElement(c,null,D.a.createElement("p",null,"In: ",D.a.createElement("code",null,r.get("in")))),D.a.createElement(c,null,D.a.createElement("label",null,"Value:"),h?D.a.createElement("code",null," ****** "):D.a.createElement(u,null,D.a.createElement(s,{type:"text",onChange:this.onChange,autoFocus:!0}))),N()(t=m.valueSeq()).call(t,(function(e,t){return D.a.createElement(p,{error:e,key:t})})))}}]),n}(D.a.Component),Ne=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onChange",(function(e){var t=a.props.onChange,n=e.target,r=n.value,o=n.name,i=a.state.value;i[o]=r,a.setState({value:i}),t(a.state)}));var o=a.props,i=o.schema,s=o.name,c=a.getValue().username;return a.state={name:s,schema:i,value:c?{username:c}:{}},a}return S()(n,[{key:"getValue",value:function(){var e=this.props,t=e.authorized,n=e.name;return t&&t.getIn([n,"value"])||{}}},{key:"render",value:function(){var e,t,n=this.props,r=n.schema,a=n.getComponent,o=n.name,i=n.errSelectors,s=a("Input"),c=a("Row"),u=a("Col"),p=a("authError"),f=a("JumpToPath",!0),d=a("Markdown",!0),h=this.getValue().username,m=l()(e=i.allErrors()).call(e,(function(e){return e.get("authId")===o}));return D.a.createElement("div",null,D.a.createElement("h4",null,"Basic authorization",D.a.createElement(f,{path:["securityDefinitions",o]})),h&&D.a.createElement("h6",null,"Authorized"),D.a.createElement(c,null,D.a.createElement(d,{source:r.get("description")})),D.a.createElement(c,null,D.a.createElement("label",null,"Username:"),h?D.a.createElement("code",null," ",h," "):D.a.createElement(u,null,D.a.createElement(s,{type:"text",required:"required",name:"username",onChange:this.onChange,autoFocus:!0}))),D.a.createElement(c,null,D.a.createElement("label",null,"Password:"),h?D.a.createElement("code",null," ****** "):D.a.createElement(u,null,D.a.createElement(s,{autoComplete:"new-password",name:"password",type:"password",onChange:this.onChange}))),N()(t=m.valueSeq()).call(t,(function(e,t){return D.a.createElement(p,{error:e,key:t})})))}}]),n}(D.a.Component);function Me(e){var t=e.example,n=e.showValue,r=e.getComponent,a=e.getConfigs,o=r("Markdown",!0),i=r("highlightCode");return t?D.a.createElement("div",{className:"example"},t.get("description")?D.a.createElement("section",{className:"example__section"},D.a.createElement("div",{className:"example__section-header"},"Example Description"),D.a.createElement("p",null,D.a.createElement(o,{source:t.get("description")}))):null,n&&t.has("value")?D.a.createElement("section",{className:"example__section"},D.a.createElement("div",{className:"example__section-header"},"Example Value"),D.a.createElement(i,{getConfigs:a,value:Object($.J)(t.get("value"))})):null):null}var De=n(398),qe=n.n(De),Be=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"_onSelect",(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.isSyntheticChange,a=void 0!==n&&n;"function"==typeof r.props.onSelect&&r.props.onSelect(e,{isSyntheticChange:a})})),y()(ve()(r),"_onDomSelect",(function(e){if("function"==typeof r.props.onSelect){var t=e.target.selectedOptions[0].getAttribute("value");r._onSelect(t,{isSyntheticChange:!1})}})),y()(ve()(r),"getCurrentExample",(function(){var e=r.props,t=e.examples,n=e.currentExampleKey,a=t.get(n),o=t.keySeq().first(),i=t.get(o);return a||i||qe()({})})),r}return S()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.onSelect,n=e.examples;if("function"==typeof t){var r=n.first(),a=n.keyOf(r);this._onSelect(a,{isSyntheticChange:!0})}}},{key:"componentWillReceiveProps",value:function(e){var t=e.currentExampleKey,n=e.examples;if(n!==this.props.examples&&!n.has(t)){var r=n.first(),a=n.keyOf(r);this._onSelect(a,{isSyntheticChange:!0})}}},{key:"render",value:function(){var e=this.props,t=e.examples,n=e.currentExampleKey,r=e.isValueModified,a=e.isModifiedValueAvailable,o=e.showLabels;return D.a.createElement("div",{className:"examples-select"},o?D.a.createElement("span",{className:"examples-select__section-label"},"Examples: "):null,D.a.createElement("select",{onChange:this._onDomSelect,value:a&&r?"__MODIFIED__VALUE__":n||""},a?D.a.createElement("option",{value:"__MODIFIED__VALUE__"},"[Modified value]"):null,N()(t).call(t,(function(e,t){return D.a.createElement("option",{key:t,value:t},e.get("summary")||t)})).valueSeq()))}}]),n}(D.a.PureComponent);y()(Be,"defaultProps",{examples:L.a.Map({}),onSelect:function(){for(var e,t,n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return(e=console).log.apply(e,c()(t=["DEBUG: ExamplesSelect was not given an onSelect callback"]).call(t,r))},currentExampleKey:null,showLabels:!0});var Le=function(e){return B.List.isList(e)?e:Object($.J)(e)},Ue=function(e){ye()(n,e);var t=Ee()(n);function n(e){var r;E()(this,n),r=t.call(this,e),y()(ve()(r),"_getStateForCurrentNamespace",(function(){var e=r.props.currentNamespace;return(r.state[e]||Object(B.Map)()).toObject()})),y()(ve()(r),"_setStateForCurrentNamespace",(function(e){var t=r.props.currentNamespace;return r._setStateForNamespace(t,e)})),y()(ve()(r),"_setStateForNamespace",(function(e,t){var n=(r.state[e]||Object(B.Map)()).mergeDeep(t);return r.setState(y()({},e,n))})),y()(ve()(r),"_isCurrentUserInputSameAsExampleValue",(function(){var e=r.props.currentUserInputValue;return r._getCurrentExampleValue()===e})),y()(ve()(r),"_getValueForExample",(function(e,t){var n=(t||r.props).examples;return Le((n||Object(B.Map)({})).getIn([e,"value"]))})),y()(ve()(r),"_getCurrentExampleValue",(function(e){var t=(e||r.props).currentKey;return r._getValueForExample(t,e||r.props)})),y()(ve()(r),"_onExamplesSelect",(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.isSyntheticChange,a=r.props,o=a.onSelect,i=a.updateValue,s=a.currentUserInputValue,u=a.userHasEditedBody,l=r._getStateForCurrentNamespace(),p=l.lastUserEditedValue,f=r._getValueForExample(e);if("__MODIFIED__VALUE__"===e)return i(Le(p)),r._setStateForCurrentNamespace({isModifiedValueSelected:!0});if("function"==typeof o){for(var d,h=arguments.length,m=new Array(h>2?h-2:0),v=2;v<h;v++)m[v-2]=arguments[v];o.apply(void 0,c()(d=[e,{isSyntheticChange:n}]).call(d,m))}r._setStateForCurrentNamespace({lastDownstreamValue:f,isModifiedValueSelected:n&&u||!!s&&s!==f}),n||"function"==typeof i&&i(Le(f))}));var a=r._getCurrentExampleValue();return r.state=y()({},e.currentNamespace,Object(B.Map)({lastUserEditedValue:r.props.currentUserInputValue,lastDownstreamValue:a,isModifiedValueSelected:r.props.userHasEditedBody||r.props.currentUserInputValue!==a})),r}return S()(n,[{key:"componentWillUnmount",value:function(){this.props.setRetainRequestBodyValueFlag(!1)}},{key:"componentWillReceiveProps",value:function(e){var t=e.currentUserInputValue,n=e.examples,r=e.onSelect,a=e.userHasEditedBody,o=this._getStateForCurrentNamespace(),i=o.lastUserEditedValue,s=o.lastDownstreamValue,c=this._getValueForExample(e.currentKey,e),u=l()(n).call(n,(function(e){return e.get("value")===t||Object($.J)(e.get("value"))===t}));u.size?r(u.has(e.currentKey)?e.currentKey:u.keySeq().first(),{isSyntheticChange:!0}):t!==this.props.currentUserInputValue&&t!==i&&t!==s&&(this.props.setRetainRequestBodyValueFlag(!0),this._setStateForNamespace(e.currentNamespace,{lastUserEditedValue:e.currentUserInputValue,isModifiedValueSelected:a||t!==c}))}},{key:"render",value:function(){var e=this.props,t=e.currentUserInputValue,n=e.examples,r=e.currentKey,a=e.getComponent,o=e.userHasEditedBody,i=this._getStateForCurrentNamespace(),s=i.lastDownstreamValue,c=i.lastUserEditedValue,u=i.isModifiedValueSelected,l=a("ExamplesSelect");return D.a.createElement(l,{examples:n,currentExampleKey:r,onSelect:this._onExamplesSelect,isModifiedValueAvailable:!!c&&c!==s,isValueModified:void 0!==t&&u&&t!==this._getCurrentExampleValue()||o})}}]),n}(D.a.PureComponent);y()(Ue,"defaultProps",{userHasEditedBody:!1,examples:Object(B.Map)({}),currentNamespace:"__DEFAULT__NAMESPACE__",setRetainRequestBodyValueFlag:function(){},onSelect:function(){for(var e,t,n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return(e=console).log.apply(e,c()(t=["ExamplesSelectValueRetainer: no `onSelect` function was provided"]).call(t,r))},updateValue:function(){for(var e,t,n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return(e=console).log.apply(e,c()(t=["ExamplesSelectValueRetainer: no `updateValue` function was provided"]).call(t,r))}});var Ve=n(164),ze=n.n(Ve),Fe=n(102),Je=n.n(Fe),We=n(35),He=n.n(We),$e=n(79),Ye=n.n($e);var Ke=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"close",(function(e){e.preventDefault(),a.props.authActions.showDefinitions(!1)})),y()(ve()(a),"authorize",(function(){var e=a.props,t=e.authActions,n=e.errActions,r=e.getConfigs,o=e.authSelectors,i=e.oas3Selectors,s=r(),c=o.getConfigs();n.clear({authId:name,type:"auth",source:"auth"}),function(e){var t=e.auth,n=e.authActions,r=e.errActions,a=e.configs,o=e.authConfigs,i=void 0===o?{}:o,s=e.currentServer,c=t.schema,u=t.scopes,l=t.name,p=t.clientId,f=c.get("flow"),d=[];switch(f){case"password":return void n.authorizePassword(t);case"application":return void n.authorizeApplication(t);case"accessCode":d.push("response_type=code");break;case"implicit":d.push("response_type=token");break;case"clientCredentials":case"client_credentials":return void n.authorizeApplication(t);case"authorizationCode":case"authorization_code":d.push("response_type=code")}"string"==typeof p&&d.push("client_id="+encodeURIComponent(p));var h=a.oauth2RedirectUrl;if(void 0!==h){d.push("redirect_uri="+encodeURIComponent(h));var m=[];if(I()(u)?m=u:L.a.List.isList(u)&&(m=u.toArray()),m.length>0){var v=i.scopeSeparator||" ";d.push("scope="+encodeURIComponent(m.join(v)))}var g=Object($.a)(new Date);if(d.push("state="+encodeURIComponent(g)),void 0!==i.realm&&d.push("realm="+encodeURIComponent(i.realm)),("authorizationCode"===f||"authorization_code"===f||"accessCode"===f)&&i.usePkceWithAuthorizationCodeGrant){var y=Object($.j)(),b=Object($.c)(y);d.push("code_challenge="+b),d.push("code_challenge_method=S256"),t.codeVerifier=y}var E=i.additionalQueryStringParams;for(var x in E){var S;void 0!==E[x]&&d.push(N()(S=[x,E[x]]).call(S,encodeURIComponent).join("="))}var w,j=c.get("authorizationUrl"),O=[s?Ye()(Object($.G)(j),s,!0).toString():Object($.G)(j),d.join("&")].join(-1===Se()(j).call(j,"?")?"?":"&");w="implicit"===f?n.preAuthorizeImplicit:i.useBasicAuthenticationWithAccessCodeGrant?n.authorizeAccessCodeWithBasicAuthentication:n.authorizeAccessCodeWithFormParams,H.a.swaggerUIRedirectOauth2={auth:t,state:g,redirectUrl:h,callback:w,errCb:r.newAuthErr},H.a.open(O)}else r.newAuthErr({authId:l,source:"validation",level:"error",message:"oauth2RedirectUrl configuration is not passed. Oauth2 authorization cannot be performed."})}({auth:a.state,currentServer:i.serverEffectiveValue(i.selectedServer()),authActions:t,errActions:n,configs:s,authConfigs:c})})),y()(ve()(a),"onScopeChange",(function(e){var t,n,r=e.target,o=r.checked,i=r.dataset.value;if(o&&-1===Se()(t=a.state.scopes).call(t,i)){var s,u=c()(s=a.state.scopes).call(s,[i]);a.setState({scopes:u})}else if(!o&&Se()(n=a.state.scopes).call(n,i)>-1){var p;a.setState({scopes:l()(p=a.state.scopes).call(p,(function(e){return e!==i}))})}})),y()(ve()(a),"onInputChange",(function(e){var t=e.target,n=t.dataset.name,r=t.value,o=y()({},n,r);a.setState(o)})),y()(ve()(a),"selectScopes",(function(e){var t;e.target.dataset.all?a.setState({scopes:ze()(Je()(t=a.props.schema.get("allowedScopes")||a.props.schema.get("scopes")).call(t))}):a.setState({scopes:[]})})),y()(ve()(a),"logout",(function(e){e.preventDefault();var t=a.props,n=t.authActions,r=t.errActions,o=t.name;r.clear({authId:o,type:"auth",source:"auth"}),n.logoutWithPersistOption([o])}));var o=a.props,i=o.name,s=o.schema,u=o.authorized,p=o.authSelectors,f=u&&u.get(i),d=p.getConfigs()||{},h=f&&f.get("username")||"",m=f&&f.get("clientId")||d.clientId||"",v=f&&f.get("clientSecret")||d.clientSecret||"",g=f&&f.get("passwordType")||"basic",b=f&&f.get("scopes")||d.scopes||[];return"string"==typeof b&&(b=b.split(d.scopeSeparator||" ")),a.state={appName:d.appName,name:i,schema:s,scopes:b,clientId:m,clientSecret:v,username:h,password:"",passwordType:g},a}return S()(n,[{key:"render",value:function(){var e,t,n=this,r=this.props,a=r.schema,o=r.getComponent,i=r.authSelectors,s=r.errSelectors,u=r.name,p=r.specSelectors,f=o("Input"),d=o("Row"),h=o("Col"),m=o("Button"),v=o("authError"),g=o("JumpToPath",!0),y=o("Markdown",!0),b=o("InitializedInput"),E=p.isOAS3,x=E()?a.get("openIdConnectUrl"):null,S="implicit",w="password",j=E()?x?"authorization_code":"authorizationCode":"accessCode",O=E()?x?"client_credentials":"clientCredentials":"application",C=a.get("flow"),_=a.get("allowedScopes")||a.get("scopes"),A=!!i.authorized().get(u),k=l()(e=s.allErrors()).call(e,(function(e){return e.get("authId")===u})),I=!l()(k).call(k,(function(e){return"validation"===e.get("source")})).size,P=a.get("description");return D.a.createElement("div",null,D.a.createElement("h4",null,u," (OAuth2, ",a.get("flow"),") ",D.a.createElement(g,{path:["securityDefinitions",u]})),this.state.appName?D.a.createElement("h5",null,"Application: ",this.state.appName," "):null,P&&D.a.createElement(y,{source:a.get("description")}),A&&D.a.createElement("h6",null,"Authorized"),x&&D.a.createElement("p",null,"OpenID Connect URL: ",D.a.createElement("code",null,x)),(C===S||C===j)&&D.a.createElement("p",null,"Authorization URL: ",D.a.createElement("code",null,a.get("authorizationUrl"))),(C===w||C===j||C===O)&&D.a.createElement("p",null,"Token URL:",D.a.createElement("code",null," ",a.get("tokenUrl"))),D.a.createElement("p",{className:"flow"},"Flow: ",D.a.createElement("code",null,a.get("flow"))),C!==w?null:D.a.createElement(d,null,D.a.createElement(d,null,D.a.createElement("label",{htmlFor:"oauth_username"},"username:"),A?D.a.createElement("code",null," ",this.state.username," "):D.a.createElement(h,{tablet:10,desktop:10},D.a.createElement("input",{id:"oauth_username",type:"text","data-name":"username",onChange:this.onInputChange,autoFocus:!0}))),D.a.createElement(d,null,D.a.createElement("label",{htmlFor:"oauth_password"},"password:"),A?D.a.createElement("code",null," ****** "):D.a.createElement(h,{tablet:10,desktop:10},D.a.createElement("input",{id:"oauth_password",type:"password","data-name":"password",onChange:this.onInputChange}))),D.a.createElement(d,null,D.a.createElement("label",{htmlFor:"password_type"},"Client credentials location:"),A?D.a.createElement("code",null," ",this.state.passwordType," "):D.a.createElement(h,{tablet:10,desktop:10},D.a.createElement("select",{id:"password_type","data-name":"passwordType",onChange:this.onInputChange},D.a.createElement("option",{value:"basic"},"Authorization header"),D.a.createElement("option",{value:"request-body"},"Request body"))))),(C===O||C===S||C===j||C===w)&&(!A||A&&this.state.clientId)&&D.a.createElement(d,null,D.a.createElement("label",{htmlFor:"client_id"},"client_id:"),A?D.a.createElement("code",null," ****** "):D.a.createElement(h,{tablet:10,desktop:10},D.a.createElement(b,{id:"client_id",type:"text",required:C===w,initialValue:this.state.clientId,"data-name":"clientId",onChange:this.onInputChange}))),(C===O||C===j||C===w)&&D.a.createElement(d,null,D.a.createElement("label",{htmlFor:"client_secret"},"client_secret:"),A?D.a.createElement("code",null," ****** "):D.a.createElement(h,{tablet:10,desktop:10},D.a.createElement(b,{id:"client_secret",initialValue:this.state.clientSecret,type:"password","data-name":"clientSecret",onChange:this.onInputChange}))),!A&&_&&_.size?D.a.createElement("div",{className:"scopes"},D.a.createElement("h2",null,"Scopes:",D.a.createElement("a",{onClick:this.selectScopes,"data-all":!0},"select all"),D.a.createElement("a",{onClick:this.selectScopes},"select none")),N()(_).call(_,(function(e,t){var r,a,o,i,s;return D.a.createElement(d,{key:t},D.a.createElement("div",{className:"checkbox"},D.a.createElement(f,{"data-value":t,id:c()(r=c()(a="".concat(t,"-")).call(a,C,"-checkbox-")).call(r,n.state.name),disabled:A,checked:He()(o=n.state.scopes).call(o,t),type:"checkbox",onChange:n.onScopeChange}),D.a.createElement("label",{htmlFor:c()(i=c()(s="".concat(t,"-")).call(s,C,"-checkbox-")).call(i,n.state.name)},D.a.createElement("span",{className:"item"}),D.a.createElement("div",{className:"text"},D.a.createElement("p",{className:"name"},t),D.a.createElement("p",{className:"description"},e)))))})).toArray()):null,N()(t=k.valueSeq()).call(t,(function(e,t){return D.a.createElement(v,{error:e,key:t})})),D.a.createElement("div",{className:"auth-btn-wrapper"},I&&(A?D.a.createElement(m,{className:"btn modal-btn auth authorize",onClick:this.logout},"Logout"):D.a.createElement(m,{className:"btn modal-btn auth authorize",onClick:this.authorize},"Authorize")),D.a.createElement(m,{className:"btn modal-btn auth btn-done",onClick:this.close},"Close")))}}]),n}(D.a.Component),Ge=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onClick",(function(){var e=r.props,t=e.specActions,n=e.path,a=e.method;t.clearResponse(n,a),t.clearRequest(n,a)})),r}return S()(n,[{key:"render",value:function(){return D.a.createElement("button",{className:"btn btn-clear opblock-control__btn",onClick:this.onClick},"Clear")}}]),n}(M.Component),Ze=function(e){var t=e.headers;return D.a.createElement("div",null,D.a.createElement("h5",null,"Response headers"),D.a.createElement("pre",{className:"microlight"},t))},Xe=function(e){var t=e.duration;return D.a.createElement("div",null,D.a.createElement("h5",null,"Request duration"),D.a.createElement("pre",{className:"microlight"},t," ms"))},Qe=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"shouldComponentUpdate",value:function(e){return this.props.response!==e.response||this.props.path!==e.path||this.props.method!==e.method||this.props.displayRequestDuration!==e.displayRequestDuration}},{key:"render",value:function(){var e,t=this.props,n=t.response,r=t.getComponent,a=t.getConfigs,o=t.displayRequestDuration,i=t.specSelectors,s=t.path,u=t.method,l=a().showMutatedRequest?i.mutatedRequestFor(s,u):i.requestFor(s,u),p=n.get("status"),d=l.get("url"),h=n.get("headers").toJS(),m=n.get("notDocumented"),v=n.get("error"),g=n.get("text"),y=n.get("duration"),b=f()(h),E=h["content-type"]||h["Content-Type"],x=r("curl"),S=r("responseBody"),w=N()(b).call(b,(function(e){var t=I()(h[e])?h[e].join():h[e];return D.a.createElement("span",{className:"headerline",key:e}," ",e,": ",t," ")})),j=0!==w.length,O=r("Markdown",!0);return D.a.createElement("div",null,l&&D.a.createElement(x,{request:l,getConfigs:a}),d&&D.a.createElement("div",null,D.a.createElement("h4",null,"Request URL"),D.a.createElement("div",{className:"request-url"},D.a.createElement("pre",{className:"microlight"},d))),D.a.createElement("h4",null,"Server response"),D.a.createElement("table",{className:"responses-table live-responses-table"},D.a.createElement("thead",null,D.a.createElement("tr",{className:"responses-header"},D.a.createElement("td",{className:"col_header response-col_status"},"Code"),D.a.createElement("td",{className:"col_header response-col_description"},"Details"))),D.a.createElement("tbody",null,D.a.createElement("tr",{className:"response"},D.a.createElement("td",{className:"response-col_status"},p,m?D.a.createElement("div",{className:"response-undocumented"},D.a.createElement("i",null," Undocumented ")):null),D.a.createElement("td",{className:"response-col_description"},v?D.a.createElement(O,{source:c()(e="".concat(""!==n.get("name")?"".concat(n.get("name"),": "):"")).call(e,n.get("message"))}):null,g?D.a.createElement(S,{content:g,contentType:E,url:d,headers:h,getConfigs:a,getComponent:r}):null,j?D.a.createElement(Ze,{headers:w}):null,o&&y?D.a.createElement(Xe,{duration:y}):null)))))}}]),n}(D.a.Component),et=n(170),tt=["get","put","post","delete","options","head","patch"],nt=c()(tt).call(tt,["trace"]),rt=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,n=e.getComponent,r=e.oas3Selectors,a=e.layoutSelectors,o=e.layoutActions,i=e.getConfigs,s=e.fn,u=t.taggedOperations(),l=n("OperationContainer",!0),p=n("OperationTag"),f=i().maxDisplayedTags,d=a.currentFilter();return d&&!0!==d&&"true"!==d&&"false"!==d&&(u=s.opsFilter(u,d)),f&&!isNaN(f)&&f>=0&&(u=A()(u).call(u,0,f)),D.a.createElement("div",null,N()(u).call(u,(function(e,s){var u=e.get("operations");return D.a.createElement(p,{key:"operation-"+s,tagObj:e,tag:s,oas3Selectors:r,layoutSelectors:a,layoutActions:o,getConfigs:i,getComponent:n,specUrl:t.url()},N()(u).call(u,(function(e){var n,r=e.get("path"),a=e.get("method"),o=L.a.List(["paths",r,a]),i=t.isOAS3()?nt:tt;return-1===Se()(i).call(i,a)?null:D.a.createElement(l,{key:c()(n="".concat(r,"-")).call(n,a),specPath:o,op:e,path:r,method:a,tag:s})})).toArray())})).toArray(),u.size<1?D.a.createElement("h3",null," No operations defined in spec! "):null)}}]),n}(D.a.Component),at=n(80),ot=n.n(at);function it(e){return e.match(/^(?:[a-z]+:)?\/\//i)}function st(e,t){return e?it(e)?(n=e).match(/^\/\//i)?c()(r="".concat(window.location.protocol)).call(r,n):n:new ot.a(e,t).href:t;var n,r}function ct(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.selectedServer,a=void 0===r?"":r;if(e){if(it(e))return e;var o=st(a,t);return it(o)?new ot.a(e,o).href:new ot.a(e,window.location.href).href}}var ut=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.tagObj,r=t.tag,a=t.children,o=t.oas3Selectors,i=t.layoutSelectors,s=t.layoutActions,c=t.getConfigs,u=t.getComponent,l=t.specUrl,p=c(),f=p.docExpansion,d=p.deepLinking,h=d&&"false"!==d,m=u("Collapse"),v=u("Markdown",!0),g=u("DeepLink"),y=u("Link"),b=n.getIn(["tagDetails","description"],null),E=n.getIn(["tagDetails","externalDocs","description"]),x=n.getIn(["tagDetails","externalDocs","url"]);e=Object($.s)(o)&&Object($.s)(o.selectedServer)?ct(x,l,{selectedServer:o.selectedServer()}):x;var S=["operations-tag",r],w=i.isShown(S,"full"===f||"list"===f);return D.a.createElement("div",{className:w?"opblock-tag-section is-open":"opblock-tag-section"},D.a.createElement("h4",{onClick:function(){return s.show(S,!w)},className:b?"opblock-tag":"opblock-tag no-desc",id:N()(S).call(S,(function(e){return Object($.g)(e)})).join("-"),"data-tag":r,"data-is-open":w},D.a.createElement(g,{enabled:h,isShown:w,path:Object($.d)(r),text:r}),b?D.a.createElement("small",null,D.a.createElement(v,{source:b})):D.a.createElement("small",null),D.a.createElement("div",null,E?D.a.createElement("small",null,E,e?": ":null,e?D.a.createElement(y,{href:Object($.G)(e),onClick:function(e){return e.stopPropagation()},target:"_blank"},e):null):null),D.a.createElement("button",{className:"expand-operation",title:w?"Collapse operation":"Expand operation",onClick:function(){return s.show(S,!w)}},D.a.createElement("svg",{className:"arrow",width:"20",height:"20"},D.a.createElement("use",{href:w?"#large-arrow-down":"#large-arrow",xlinkHref:w?"#large-arrow-down":"#large-arrow"})))),D.a.createElement(m,{isOpened:w},a))}}]),n}(D.a.Component);y()(ut,"defaultProps",{tagObj:L.a.fromJS({}),tag:""});var lt=function(e){ye()(r,e);var t=Ee()(r);function r(){return E()(this,r),t.apply(this,arguments)}return S()(r,[{key:"render",value:function(){var e=this.props,t=e.specPath,r=e.response,a=e.request,o=e.toggleShown,i=e.onTryoutClick,s=e.onCancelClick,c=e.onExecute,u=e.fn,l=e.getComponent,p=e.getConfigs,f=e.specActions,d=e.specSelectors,h=e.authActions,m=e.authSelectors,v=e.oas3Actions,g=e.oas3Selectors,y=this.props.operation,b=y.toJS(),E=b.deprecated,x=b.isShown,S=b.path,w=b.method,j=b.op,O=b.tag,C=b.operationId,_=b.allowTryItOut,A=b.displayRequestDuration,k=b.tryItOutEnabled,I=b.executeInProgress,P=j.description,T=j.externalDocs,R=j.schemes,N=T?ct(T.url,d.url(),{selectedServer:g.selectedServer()}):"",M=y.getIn(["op"]),q=M.get("responses"),B=Object($.n)(M,["parameters"]),L=d.operationScheme(S,w),U=["operations",O,C],V=Object($.m)(M),z=l("responses"),F=l("parameters"),J=l("execute"),W=l("clear"),H=l("Collapse"),Y=l("Markdown",!0),K=l("schemes"),G=l("OperationServers"),Z=l("OperationExt"),X=l("OperationSummary"),Q=l("Link"),ee=p().showExtensions;if(q&&r&&r.size>0){var te=!q.get(String(r.get("status")))&&!q.get("default");r=r.set("notDocumented",te)}var ne=[S,w];return D.a.createElement("div",{className:E?"opblock opblock-deprecated":x?"opblock opblock-".concat(w," is-open"):"opblock opblock-".concat(w),id:Object($.g)(U.join("-"))},D.a.createElement(X,{operationProps:y,toggleShown:o,getComponent:l,authActions:h,authSelectors:m,specPath:t}),D.a.createElement(H,{isOpened:x},D.a.createElement("div",{className:"opblock-body"},M&&M.size||null===M?null:D.a.createElement("img",{height:"32px",width:"32px",src:n(375),className:"opblock-loading-animation"}),E&&D.a.createElement("h4",{className:"opblock-title_normal"}," Warning: Deprecated"),P&&D.a.createElement("div",{className:"opblock-description-wrapper"},D.a.createElement("div",{className:"opblock-description"},D.a.createElement(Y,{source:P}))),N?D.a.createElement("div",{className:"opblock-external-docs-wrapper"},D.a.createElement("h4",{className:"opblock-title_normal"},"Find more details"),D.a.createElement("div",{className:"opblock-external-docs"},D.a.createElement("span",{className:"opblock-external-docs__description"},D.a.createElement(Y,{source:T.description})),D.a.createElement(Q,{target:"_blank",className:"opblock-external-docs__link",href:Object($.G)(N)},N))):null,M&&M.size?D.a.createElement(F,{parameters:B,specPath:t.push("parameters"),operation:M,onChangeKey:ne,onTryoutClick:i,onCancelClick:s,tryItOutEnabled:k,allowTryItOut:_,fn:u,getComponent:l,specActions:f,specSelectors:d,pathMethod:[S,w],getConfigs:p,oas3Actions:v,oas3Selectors:g}):null,k?D.a.createElement(G,{getComponent:l,path:S,method:w,operationServers:M.get("servers"),pathServers:d.paths().getIn([S,"servers"]),getSelectedServer:g.selectedServer,setSelectedServer:v.setSelectedServer,setServerVariableValue:v.setServerVariableValue,getServerVariable:g.serverVariableValue,getEffectiveServerValue:g.serverEffectiveValue}):null,k&&_&&R&&R.size?D.a.createElement("div",{className:"opblock-schemes"},D.a.createElement(K,{schemes:R,path:S,method:w,specActions:f,currentScheme:L})):null,D.a.createElement("div",{className:k&&r&&_?"btn-group":"execute-wrapper"},k&&_?D.a.createElement(J,{operation:M,specActions:f,specSelectors:d,oas3Selectors:g,oas3Actions:v,path:S,method:w,onExecute:c,disabled:I}):null,k&&r&&_?D.a.createElement(W,{specActions:f,path:S,method:w}):null),I?D.a.createElement("div",{className:"loading-container"},D.a.createElement("div",{className:"loading"})):null,q?D.a.createElement(z,{responses:q,request:a,tryItOutResponse:r,getComponent:l,getConfigs:p,specSelectors:d,oas3Actions:v,oas3Selectors:g,specActions:f,produces:d.producesOptionsFor([S,w]),producesValue:d.currentProducesFor([S,w]),specPath:t.push("responses"),path:S,method:w,displayRequestDuration:A,fn:u}):null,ee&&V.size?D.a.createElement(Z,{extensions:V,getComponent:l}):null)))}}]),r}(M.PureComponent);y()(lt,"defaultProps",{operation:null,response:null,request:null,specPath:Object(B.List)(),summary:""});var pt=n(77),ft=n.n(pt),dt=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.toggleShown,n=e.getComponent,r=e.authActions,a=e.authSelectors,o=e.operationProps,i=e.specPath,s=o.toJS(),c=s.summary,u=s.isAuthorized,l=s.method,p=s.op,f=s.showSummary,d=s.operationId,h=s.originalOperationId,m=s.displayOperationId,v=p.summary,g=o.get("security"),y=n("authorizeOperationBtn"),b=n("OperationSummaryMethod"),E=n("OperationSummaryPath"),x=n("JumpToPath",!0),S=g&&!!g.count(),w=S&&1===g.size&&g.first().isEmpty(),j=!S||w;return D.a.createElement("div",{className:"opblock-summary opblock-summary-".concat(l),onClick:t},D.a.createElement(b,{method:l}),D.a.createElement(E,{getComponent:n,operationProps:o,specPath:i}),f?D.a.createElement("div",{className:"opblock-summary-description"},ft()(v||c)):null,m&&(h||d)?D.a.createElement("span",{className:"opblock-summary-operation-id"},h||d):null,j?null:D.a.createElement(y,{isAuthorized:u,onClick:function(){var e=a.definitionsForRequirements(g);r.showDefinitions(e)}}),D.a.createElement(x,{path:i}))}}]),n}(M.PureComponent);y()(dt,"defaultProps",{operationProps:null,specPath:Object(B.List)(),summary:""});var ht=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props.method;return D.a.createElement("span",{className:"opblock-summary-method"},e.toUpperCase())}}]),n}(M.PureComponent);y()(ht,"defaultProps",{operationProps:null});var mt=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onCopyCapture",(function(e){e.clipboardData.setData("text/plain",r.props.operationProps.get("path")),e.preventDefault()})),r}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.getComponent,r=t.operationProps.toJS(),a=r.deprecated,o=r.isShown,i=r.path,s=r.tag,u=r.operationId,l=r.isDeepLinkingEnabled,p=n("DeepLink");return D.a.createElement("span",{className:a?"opblock-summary-path__deprecated":"opblock-summary-path",onCopyCapture:this.onCopyCapture,"data-path":i},D.a.createElement(p,{enabled:l,isShown:o,path:Object($.d)(c()(e="".concat(s,"/")).call(e,u)),text:i.replace(/\//g,"/")}))}}]),n}(M.PureComponent),vt=n(16),gt=n.n(vt),yt=function(e){var t,n=e.extensions,r=(0,e.getComponent)("OperationExtRow");return D.a.createElement("div",{className:"opblock-section"},D.a.createElement("div",{className:"opblock-section-header"},D.a.createElement("h4",null,"Extensions")),D.a.createElement("div",{className:"table-container"},D.a.createElement("table",null,D.a.createElement("thead",null,D.a.createElement("tr",null,D.a.createElement("td",{className:"col_header"},"Field"),D.a.createElement("td",{className:"col_header"},"Value"))),D.a.createElement("tbody",null,N()(t=n.entrySeq()).call(t,(function(e){var t,n=gt()(e,2),a=n[0],o=n[1];return D.a.createElement(r,{key:c()(t="".concat(a,"-")).call(t,o),xKey:a,xVal:o})}))))))},bt=function(e){var t=e.xKey,n=e.xVal,r=n?n.toJS?n.toJS():n:null;return D.a.createElement("tr",null,D.a.createElement("td",null,t),D.a.createElement("td",null,h()(r)))},Et=n(88),xt=n(400),St=n.n(xt).a,wt=n(399),jt=n.n(wt).a,Ot=n(401),Ct=n.n(Ot).a,_t=n(404),At=n.n(_t).a,kt=n(402),It=n.n(kt).a,Pt=n(403),Tt=n.n(Pt).a,Rt={hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#333",color:"white"},"hljs-name":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-code":{fontStyle:"italic",color:"#888"},"hljs-emphasis":{fontStyle:"italic"},"hljs-tag":{color:"#62c8f3"},"hljs-variable":{color:"#ade5fc"},"hljs-template-variable":{color:"#ade5fc"},"hljs-selector-id":{color:"#ade5fc"},"hljs-selector-class":{color:"#ade5fc"},"hljs-string":{color:"#a2fca2"},"hljs-bullet":{color:"#d36363"},"hljs-type":{color:"#ffa"},"hljs-title":{color:"#ffa"},"hljs-section":{color:"#ffa"},"hljs-attribute":{color:"#ffa"},"hljs-quote":{color:"#ffa"},"hljs-built_in":{color:"#ffa"},"hljs-builtin-name":{color:"#ffa"},"hljs-number":{color:"#d36363"},"hljs-symbol":{color:"#d36363"},"hljs-keyword":{color:"#fcc28c"},"hljs-selector-tag":{color:"#fcc28c"},"hljs-literal":{color:"#fcc28c"},"hljs-comment":{color:"#888"},"hljs-deletion":{color:"#333",backgroundColor:"#fc9b9b"},"hljs-regexp":{color:"#c6b4f0"},"hljs-link":{color:"#c6b4f0"},"hljs-meta":{color:"#fc9b9b"},"hljs-addition":{backgroundColor:"#a2fca2",color:"#333"}};Et.Light.registerLanguage("json",jt),Et.Light.registerLanguage("js",St),Et.Light.registerLanguage("xml",Ct),Et.Light.registerLanguage("yaml",It),Et.Light.registerLanguage("http",Tt),Et.Light.registerLanguage("bash",At);var Nt={agate:Rt,arta:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#222",color:"#aaa"},"hljs-subst":{color:"#aaa"},"hljs-section":{color:"#fff",fontWeight:"bold"},"hljs-comment":{color:"#444"},"hljs-quote":{color:"#444"},"hljs-meta":{color:"#444"},"hljs-string":{color:"#ffcc33"},"hljs-symbol":{color:"#ffcc33"},"hljs-bullet":{color:"#ffcc33"},"hljs-regexp":{color:"#ffcc33"},"hljs-number":{color:"#00cc66"},"hljs-addition":{color:"#00cc66"},"hljs-built_in":{color:"#32aaee"},"hljs-builtin-name":{color:"#32aaee"},"hljs-literal":{color:"#32aaee"},"hljs-type":{color:"#32aaee"},"hljs-template-variable":{color:"#32aaee"},"hljs-attribute":{color:"#32aaee"},"hljs-link":{color:"#32aaee"},"hljs-keyword":{color:"#6644aa"},"hljs-selector-tag":{color:"#6644aa"},"hljs-name":{color:"#6644aa"},"hljs-selector-id":{color:"#6644aa"},"hljs-selector-class":{color:"#6644aa"},"hljs-title":{color:"#bb1166"},"hljs-variable":{color:"#bb1166"},"hljs-deletion":{color:"#bb1166"},"hljs-template-tag":{color:"#bb1166"},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},monokai:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#272822",color:"#ddd"},"hljs-tag":{color:"#f92672"},"hljs-keyword":{color:"#f92672",fontWeight:"bold"},"hljs-selector-tag":{color:"#f92672",fontWeight:"bold"},"hljs-literal":{color:"#f92672",fontWeight:"bold"},"hljs-strong":{color:"#f92672"},"hljs-name":{color:"#f92672"},"hljs-code":{color:"#66d9ef"},"hljs-class .hljs-title":{color:"white"},"hljs-attribute":{color:"#bf79db"},"hljs-symbol":{color:"#bf79db"},"hljs-regexp":{color:"#bf79db"},"hljs-link":{color:"#bf79db"},"hljs-string":{color:"#a6e22e"},"hljs-bullet":{color:"#a6e22e"},"hljs-subst":{color:"#a6e22e"},"hljs-title":{color:"#a6e22e",fontWeight:"bold"},"hljs-section":{color:"#a6e22e",fontWeight:"bold"},"hljs-emphasis":{color:"#a6e22e"},"hljs-type":{color:"#a6e22e",fontWeight:"bold"},"hljs-built_in":{color:"#a6e22e"},"hljs-builtin-name":{color:"#a6e22e"},"hljs-selector-attr":{color:"#a6e22e"},"hljs-selector-pseudo":{color:"#a6e22e"},"hljs-addition":{color:"#a6e22e"},"hljs-variable":{color:"#a6e22e"},"hljs-template-tag":{color:"#a6e22e"},"hljs-template-variable":{color:"#a6e22e"},"hljs-comment":{color:"#75715e"},"hljs-quote":{color:"#75715e"},"hljs-deletion":{color:"#75715e"},"hljs-meta":{color:"#75715e"},"hljs-doctag":{fontWeight:"bold"},"hljs-selector-id":{fontWeight:"bold"}},nord:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#2E3440",color:"#D8DEE9"},"hljs-subst":{color:"#D8DEE9"},"hljs-selector-tag":{color:"#81A1C1"},"hljs-selector-id":{color:"#8FBCBB",fontWeight:"bold"},"hljs-selector-class":{color:"#8FBCBB"},"hljs-selector-attr":{color:"#8FBCBB"},"hljs-selector-pseudo":{color:"#88C0D0"},"hljs-addition":{backgroundColor:"rgba(163, 190, 140, 0.5)"},"hljs-deletion":{backgroundColor:"rgba(191, 97, 106, 0.5)"},"hljs-built_in":{color:"#8FBCBB"},"hljs-type":{color:"#8FBCBB"},"hljs-class":{color:"#8FBCBB"},"hljs-function":{color:"#88C0D0"},"hljs-function > .hljs-title":{color:"#88C0D0"},"hljs-keyword":{color:"#81A1C1"},"hljs-literal":{color:"#81A1C1"},"hljs-symbol":{color:"#81A1C1"},"hljs-number":{color:"#B48EAD"},"hljs-regexp":{color:"#EBCB8B"},"hljs-string":{color:"#A3BE8C"},"hljs-title":{color:"#8FBCBB"},"hljs-params":{color:"#D8DEE9"},"hljs-bullet":{color:"#81A1C1"},"hljs-code":{color:"#8FBCBB"},"hljs-emphasis":{fontStyle:"italic"},"hljs-formula":{color:"#8FBCBB"},"hljs-strong":{fontWeight:"bold"},"hljs-link:hover":{textDecoration:"underline"},"hljs-quote":{color:"#4C566A"},"hljs-comment":{color:"#4C566A"},"hljs-doctag":{color:"#8FBCBB"},"hljs-meta":{color:"#5E81AC"},"hljs-meta-keyword":{color:"#5E81AC"},"hljs-meta-string":{color:"#A3BE8C"},"hljs-attr":{color:"#8FBCBB"},"hljs-attribute":{color:"#D8DEE9"},"hljs-builtin-name":{color:"#81A1C1"},"hljs-name":{color:"#81A1C1"},"hljs-section":{color:"#88C0D0"},"hljs-tag":{color:"#81A1C1"},"hljs-variable":{color:"#D8DEE9"},"hljs-template-variable":{color:"#D8DEE9"},"hljs-template-tag":{color:"#5E81AC"},"abnf .hljs-attribute":{color:"#88C0D0"},"abnf .hljs-symbol":{color:"#EBCB8B"},"apache .hljs-attribute":{color:"#88C0D0"},"apache .hljs-section":{color:"#81A1C1"},"arduino .hljs-built_in":{color:"#88C0D0"},"aspectj .hljs-meta":{color:"#D08770"},"aspectj > .hljs-title":{color:"#88C0D0"},"bnf .hljs-attribute":{color:"#8FBCBB"},"clojure .hljs-name":{color:"#88C0D0"},"clojure .hljs-symbol":{color:"#EBCB8B"},"coq .hljs-built_in":{color:"#88C0D0"},"cpp .hljs-meta-string":{color:"#8FBCBB"},"css .hljs-built_in":{color:"#88C0D0"},"css .hljs-keyword":{color:"#D08770"},"diff .hljs-meta":{color:"#8FBCBB"},"ebnf .hljs-attribute":{color:"#8FBCBB"},"glsl .hljs-built_in":{color:"#88C0D0"},"groovy .hljs-meta:not(:first-child)":{color:"#D08770"},"haxe .hljs-meta":{color:"#D08770"},"java .hljs-meta":{color:"#D08770"},"ldif .hljs-attribute":{color:"#8FBCBB"},"lisp .hljs-name":{color:"#88C0D0"},"lua .hljs-built_in":{color:"#88C0D0"},"moonscript .hljs-built_in":{color:"#88C0D0"},"nginx .hljs-attribute":{color:"#88C0D0"},"nginx .hljs-section":{color:"#5E81AC"},"pf .hljs-built_in":{color:"#88C0D0"},"processing .hljs-built_in":{color:"#88C0D0"},"scss .hljs-keyword":{color:"#81A1C1"},"stylus .hljs-keyword":{color:"#81A1C1"},"swift .hljs-meta":{color:"#D08770"},"vim .hljs-built_in":{color:"#88C0D0",fontStyle:"italic"},"yaml .hljs-meta":{color:"#D08770"}},obsidian:{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"#282b2e",color:"#e0e2e4"},"hljs-keyword":{color:"#93c763",fontWeight:"bold"},"hljs-selector-tag":{color:"#93c763",fontWeight:"bold"},"hljs-literal":{color:"#93c763",fontWeight:"bold"},"hljs-selector-id":{color:"#93c763"},"hljs-number":{color:"#ffcd22"},"hljs-attribute":{color:"#668bb0"},"hljs-code":{color:"white"},"hljs-class .hljs-title":{color:"white"},"hljs-section":{color:"white",fontWeight:"bold"},"hljs-regexp":{color:"#d39745"},"hljs-link":{color:"#d39745"},"hljs-meta":{color:"#557182"},"hljs-tag":{color:"#8cbbad"},"hljs-name":{color:"#8cbbad",fontWeight:"bold"},"hljs-bullet":{color:"#8cbbad"},"hljs-subst":{color:"#8cbbad"},"hljs-emphasis":{color:"#8cbbad"},"hljs-type":{color:"#8cbbad",fontWeight:"bold"},"hljs-built_in":{color:"#8cbbad"},"hljs-selector-attr":{color:"#8cbbad"},"hljs-selector-pseudo":{color:"#8cbbad"},"hljs-addition":{color:"#8cbbad"},"hljs-variable":{color:"#8cbbad"},"hljs-template-tag":{color:"#8cbbad"},"hljs-template-variable":{color:"#8cbbad"},"hljs-string":{color:"#ec7600"},"hljs-symbol":{color:"#ec7600"},"hljs-comment":{color:"#818e96"},"hljs-quote":{color:"#818e96"},"hljs-deletion":{color:"#818e96"},"hljs-selector-class":{color:"#A082BD"},"hljs-doctag":{fontWeight:"bold"},"hljs-title":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"}},"tomorrow-night":{"hljs-comment":{color:"#969896"},"hljs-quote":{color:"#969896"},"hljs-variable":{color:"#cc6666"},"hljs-template-variable":{color:"#cc6666"},"hljs-tag":{color:"#cc6666"},"hljs-name":{color:"#cc6666"},"hljs-selector-id":{color:"#cc6666"},"hljs-selector-class":{color:"#cc6666"},"hljs-regexp":{color:"#cc6666"},"hljs-deletion":{color:"#cc6666"},"hljs-number":{color:"#de935f"},"hljs-built_in":{color:"#de935f"},"hljs-builtin-name":{color:"#de935f"},"hljs-literal":{color:"#de935f"},"hljs-type":{color:"#de935f"},"hljs-params":{color:"#de935f"},"hljs-meta":{color:"#de935f"},"hljs-link":{color:"#de935f"},"hljs-attribute":{color:"#f0c674"},"hljs-string":{color:"#b5bd68"},"hljs-symbol":{color:"#b5bd68"},"hljs-bullet":{color:"#b5bd68"},"hljs-addition":{color:"#b5bd68"},"hljs-title":{color:"#81a2be"},"hljs-section":{color:"#81a2be"},"hljs-keyword":{color:"#b294bb"},"hljs-selector-tag":{color:"#b294bb"},hljs:{display:"block",overflowX:"auto",background:"#1d1f21",color:"#c5c8c6",padding:"0.5em"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}}},Mt=f()(Nt),Dt=function(e){return He()(Mt).call(Mt,e)?Nt[e]:(console.warn("Request style '".concat(e,"' is not available, returning default instead")),Rt)},qt=n(41),Bt=n.n(qt),Lt=n(405),Ut=n.n(Lt),Vt=n(171),zt=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"downloadText",(function(){Ut()(r.props.value,r.props.fileName||"response.txt")})),y()(ve()(r),"preventYScrollingBeyondElement",(function(e){var t=e.target,n=e.nativeEvent.deltaY,r=t.scrollHeight,a=t.offsetHeight,o=t.scrollTop;r>a&&(0===o&&n<0||a+o>=r&&n>0)&&e.preventDefault()})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.value,n=e.className,r=e.downloadable,a=e.getConfigs,o=e.canCopy,i=e.language,s=a?a():{syntaxHighlight:{activated:!0,theme:"agate"}};n=n||"";var c=Bt()(s,"syntaxHighlight.activated")?D.a.createElement(Et.Light,{language:i,className:n+" microlight",onWheel:this.preventYScrollingBeyondElement,style:Dt(Bt()(s,"syntaxHighlight.theme"))},t):D.a.createElement("pre",{onWheel:this.preventYScrollingBeyondElement,className:n+" microlight"},t);return D.a.createElement("div",{className:"highlight-code"},r?D.a.createElement("div",{className:"download-contents",onClick:this.downloadText},"Download"):null,o?D.a.createElement("div",{className:"copy-to-clipboard"},D.a.createElement(Vt.CopyToClipboard,{text:t},D.a.createElement("button",null))):null,c)}}]),n}(M.Component),Ft=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onChangeProducesWrapper",(function(e){return r.props.specActions.changeProducesValue([r.props.path,r.props.method],e)})),y()(ve()(r),"onResponseContentTypeChange",(function(e){var t=e.controlsAcceptHeader,n=e.value,a=r.props,o=a.oas3Actions,i=a.path,s=a.method;t&&o.setResponseContentType({value:n,path:i,method:s})})),r}return S()(n,[{key:"render",value:function(){var e,t=this,r=this.props,a=r.responses,o=r.tryItOutResponse,i=r.getComponent,s=r.getConfigs,c=r.specSelectors,u=r.fn,l=r.producesValue,p=r.displayRequestDuration,f=r.specPath,d=r.path,h=r.method,m=r.oas3Selectors,v=r.oas3Actions,g=Object($.f)(a),y=i("contentType"),b=i("liveResponse"),E=i("response"),x=this.props.produces&&this.props.produces.size?this.props.produces:n.defaultProps.produces,S=c.isOAS3()?Object($.k)(a):null;return D.a.createElement("div",{className:"responses-wrapper"},D.a.createElement("div",{className:"opblock-section-header"},D.a.createElement("h4",null,"Responses"),c.isOAS3()?null:D.a.createElement("label",null,D.a.createElement("span",null,"Response content type"),D.a.createElement(y,{value:l,onChange:this.onChangeProducesWrapper,contentTypes:x,className:"execute-content-type"}))),D.a.createElement("div",{className:"responses-inner"},o?D.a.createElement("div",null,D.a.createElement(b,{response:o,getComponent:i,getConfigs:s,specSelectors:c,path:this.props.path,method:this.props.method,displayRequestDuration:p}),D.a.createElement("h4",null,"Responses")):null,D.a.createElement("table",{className:"responses-table"},D.a.createElement("thead",null,D.a.createElement("tr",{className:"responses-header"},D.a.createElement("td",{className:"col_header response-col_status"},"Code"),D.a.createElement("td",{className:"col_header response-col_description"},"Description"),c.isOAS3()?D.a.createElement("td",{className:"col col_header response-col_links"},"Links"):null)),D.a.createElement("tbody",null,N()(e=a.entrySeq()).call(e,(function(e){var n=gt()(e,2),r=n[0],a=n[1],p=o&&o.get("status")==r?"response_current":"";return D.a.createElement(E,{key:r,path:d,method:h,specPath:f.push(r),isDefault:g===r,fn:u,className:p,code:r,response:a,specSelectors:c,controlsAcceptHeader:a===S,onContentTypeChange:t.onResponseContentTypeChange,contentType:l,getConfigs:s,activeExamplesKey:m.activeExamplesMember(d,h,"responses",r),oas3Actions:v,getComponent:i})})).toArray()))))}}]),n}(D.a.Component);y()(Ft,"defaultProps",{tryItOutResponse:null,produces:Object(B.fromJS)(["application/json"]),displayRequestDuration:!1});var Jt=n(25),Wt=n.n(Jt),Ht=n(406),$t=n.n(Ht),Yt=n(54),Kt=n.n(Yt),Gt=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"_onContentTypeChange",(function(e){var t=a.props,n=t.onContentTypeChange,r=t.controlsAcceptHeader;a.setState({responseContentType:e}),n({value:e,controlsAcceptHeader:r})})),y()(ve()(a),"getTargetExamplesKey",(function(){var e=a.props,t=e.response,n=e.contentType,r=e.activeExamplesKey,o=a.state.responseContentType||n,i=t.getIn(["content",o],Object(B.Map)({})).get("examples",null).keySeq().first();return r||i})),a.state={responseContentType:""},a}return S()(n,[{key:"render",value:function(){var e,t,n,r,a,o=this.props,i=o.path,s=o.method,u=o.code,l=o.response,p=o.className,f=o.specPath,d=o.fn,h=o.getComponent,m=o.getConfigs,v=o.specSelectors,g=o.contentType,y=o.controlsAcceptHeader,b=o.oas3Actions,E=d.inferSchema,x=v.isOAS3(),S=m().showExtensions,w=S?Object($.m)(l):null,j=l.get("headers"),O=l.get("links"),C=h("ResponseExtension"),_=h("headers"),A=h("highlightCode"),k=h("modelExample"),I=h("Markdown",!0),P=h("operationLink"),T=h("contentType"),R=h("ExamplesSelect"),M=h("Example"),q=this.state.responseContentType||g,L=l.getIn(["content",q],Object(B.Map)({})),U=L.get("examples",null);if(x){var V=L.get("schema");n=V?E(V.toJS()):null,r=V?Object(B.List)(["content",this.state.responseContentType,"schema"]):f}else n=l.get("schema"),r=l.has("schema")?f.push("schema"):f;var z,F=!1,J={includeReadOnly:!0};if(x)if(z=L.get("schema",Object(B.Map)({})).toJS(),U){var W=this.getTargetExamplesKey();void 0===(a=U.get(W,Object(B.Map)({})).get("value"))&&(a=$t()(U).call(U).next().value),F=!0}else void 0!==L.get("example")&&(a=L.get("example"),F=!0);else{z=n,J=Wt()(Wt()({},J),{},{includeWriteOnly:!0});var H=l.getIn(["examples",q]);H&&(a=H,F=!0)}var Y=function(e,t,n){return null!=e?D.a.createElement("div",null,D.a.createElement(t,{className:"example",getConfigs:n,value:Object($.J)(e)})):null}(Object($.o)(z,q,J,F?a:void 0),A,m);return D.a.createElement("tr",{className:"response "+(p||""),"data-code":u},D.a.createElement("td",{className:"response-col_status"},u),D.a.createElement("td",{className:"response-col_description"},D.a.createElement("div",{className:"response-col_description__inner"},D.a.createElement(I,{source:l.get("description")})),S&&w.size?N()(e=w.entrySeq()).call(e,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(C,{key:c()(t="".concat(r,"-")).call(t,a),xKey:r,xVal:a})})):null,x&&l.get("content")?D.a.createElement("section",{className:"response-controls"},D.a.createElement("div",{className:Kt()("response-control-media-type",{"response-control-media-type--accept-controller":y})},D.a.createElement("small",{className:"response-control-media-type__title"},"Media type"),D.a.createElement(T,{value:this.state.responseContentType,contentTypes:l.get("content")?l.get("content").keySeq():Object(B.Seq)(),onChange:this._onContentTypeChange}),y?D.a.createElement("small",{className:"response-control-media-type__accept-message"},"Controls ",D.a.createElement("code",null,"Accept")," header."):null),U?D.a.createElement("div",{className:"response-control-examples"},D.a.createElement("small",{className:"response-control-examples__title"},"Examples"),D.a.createElement(R,{examples:U,currentExampleKey:this.getTargetExamplesKey(),onSelect:function(e){return b.setActiveExamplesMember({name:e,pathMethod:[i,s],contextType:"responses",contextName:u})},showLabels:!1})):null):null,Y||n?D.a.createElement(k,{specPath:r,getComponent:h,getConfigs:m,specSelectors:v,schema:Object($.i)(n),example:Y,includeReadOnly:!0}):null,x&&U?D.a.createElement(M,{example:U.get(this.getTargetExamplesKey(),Object(B.Map)({})),getComponent:h,getConfigs:m,omitValue:!0}):null,j?D.a.createElement(_,{headers:j,getComponent:h}):null),x?D.a.createElement("td",{className:"response-col_links"},O?N()(t=O.toSeq().entrySeq()).call(t,(function(e){var t=gt()(e,2),n=t[0],r=t[1];return D.a.createElement(P,{key:n,name:n,link:r,getComponent:h})})):D.a.createElement("i",null,"No links")):null)}}]),n}(D.a.Component);y()(Gt,"defaultProps",{response:Object(B.fromJS)({}),onContentTypeChange:function(){}});var Zt=function(e){var t=e.xKey,n=e.xVal;return D.a.createElement("div",{className:"response__extension"},t,": ",String(n))},Xt=n(407),Qt=n.n(Xt),en=n(408),tn=n.n(en),nn=n(409),rn=n.n(nn),an=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"state",{parsedContent:null}),y()(ve()(r),"updateParsedContent",(function(e){var t=r.props.content;if(e!==t)if(t&&t instanceof Blob){var n=new FileReader;n.onload=function(){r.setState({parsedContent:n.result})},n.readAsText(t)}else r.setState({parsedContent:t.toString()})})),r}return S()(n,[{key:"componentDidMount",value:function(){this.updateParsedContent(null)}},{key:"componentDidUpdate",value:function(e){this.updateParsedContent(e.content)}},{key:"render",value:function(){var e,t,n=this.props,r=n.content,a=n.contentType,o=n.url,i=n.headers,s=void 0===i?{}:i,c=n.getConfigs,u=n.getComponent,l=this.state.parsedContent,p=u("highlightCode"),f="response_"+(new Date).getTime();if(o=o||"",/^application\/octet-stream/i.test(a)||s["Content-Disposition"]&&/attachment/i.test(s["Content-Disposition"])||s["content-disposition"]&&/attachment/i.test(s["content-disposition"])||s["Content-Description"]&&/File Transfer/i.test(s["Content-Description"])||s["content-description"]&&/File Transfer/i.test(s["content-description"]))if("Blob"in window){var d=a||"text/html",m=r instanceof Blob?r:new Blob([r],{type:d}),v=ot.a.createObjectURL(m),g=[d,o.substr(Qt()(o).call(o,"/")+1),v].join(":"),y=s["content-disposition"]||s["Content-Disposition"];if(void 0!==y){var b=Object($.h)(y);null!==b&&(g=b)}t=H.a.navigator&&H.a.navigator.msSaveOrOpenBlob?D.a.createElement("div",null,D.a.createElement("a",{href:v,onClick:function(){return H.a.navigator.msSaveOrOpenBlob(m,g)}},"Download file")):D.a.createElement("div",null,D.a.createElement("a",{href:v,download:g},"Download file"))}else t=D.a.createElement("pre",{className:"microlight"},"Download headers detected but your browser does not support downloading binary via XHR (Blob).");else if(/json/i.test(a)){var E=null;try{e=h()(JSON.parse(r),null," "),E="json"}catch(t){e="can't parse JSON. Raw result:\n\n"+r}t=D.a.createElement(p,{language:E,downloadable:!0,fileName:"".concat(f,".json"),value:e,getConfigs:c,canCopy:!0})}else/xml/i.test(a)?(e=tn()(r,{textNodesOnSameLine:!0,indentor:" "}),t=D.a.createElement(p,{downloadable:!0,fileName:"".concat(f,".xml"),value:e,getConfigs:c,canCopy:!0})):t="text/html"===rn()(a)||/text\/plain/.test(a)?D.a.createElement(p,{downloadable:!0,fileName:"".concat(f,".html"),value:r,getConfigs:c,canCopy:!0}):/^image\//i.test(a)?He()(a).call(a,"svg")?D.a.createElement("div",null," ",r," "):D.a.createElement("img",{className:"full-width",src:ot.a.createObjectURL(r)}):/^audio\//i.test(a)?D.a.createElement("pre",{className:"microlight"},D.a.createElement("audio",{controls:!0},D.a.createElement("source",{src:o,type:a}))):"string"==typeof r?D.a.createElement(p,{downloadable:!0,fileName:"".concat(f,".txt"),value:r,getConfigs:c,canCopy:!0}):r.size>0?l?D.a.createElement("div",null,D.a.createElement("p",{className:"i"},"Unrecognized response type; displaying content as text."),D.a.createElement(p,{downloadable:!0,fileName:"".concat(f,".txt"),value:l,getConfigs:c,canCopy:!0})):D.a.createElement("p",{className:"i"},"Unrecognized response type; unable to display."):null;return t?D.a.createElement("div",null,D.a.createElement("h5",null,"Response body"),t):null}}]),n}(D.a.PureComponent),on=n(15),sn=n.n(on),cn=n(162),un=n.n(cn),ln=function(e){ye()(n,e);var t=Ee()(n);function n(e){var r;return E()(this,n),r=t.call(this,e),y()(ve()(r),"onChange",(function(e,t,n){var a=r.props;(0,a.specActions.changeParamByIdentity)(a.onChangeKey,e,t,n)})),y()(ve()(r),"onChangeConsumesWrapper",(function(e){var t=r.props;(0,t.specActions.changeConsumesValue)(t.onChangeKey,e)})),y()(ve()(r),"toggleTab",(function(e){return"parameters"===e?r.setState({parametersVisible:!0,callbackVisible:!1}):"callbacks"===e?r.setState({callbackVisible:!0,parametersVisible:!1}):void 0})),y()(ve()(r),"onChangeMediaType",(function(e){var t=e.value,n=e.pathMethod,a=r.props,o=a.specActions,i=a.oas3Selectors,s=a.oas3Actions,c=i.hasUserEditedBody.apply(i,sn()(n)),u=i.shouldRetainRequestBodyValue.apply(i,sn()(n));s.setRequestContentType({value:t,pathMethod:n}),s.initRequestBodyValidateError({pathMethod:n}),c||(u||s.setRequestBodyValue({value:void 0,pathMethod:n}),o.clearResponse.apply(o,sn()(n)),o.clearRequest.apply(o,sn()(n)),o.clearValidateParams(n))})),r.state={callbackVisible:!1,parametersVisible:!0},r}return S()(n,[{key:"render",value:function(){var e,t,n=this,r=this.props,a=r.onTryoutClick,o=r.parameters,i=r.allowTryItOut,s=r.tryItOutEnabled,u=r.specPath,l=r.fn,p=r.getComponent,f=r.getConfigs,d=r.specSelectors,h=r.specActions,m=r.pathMethod,v=r.oas3Actions,g=r.oas3Selectors,y=r.operation,b=p("parameterRow"),E=p("TryItOutButton"),x=p("contentType"),S=p("Callbacks",!0),w=p("RequestBody",!0),j=s&&i,O=d.isOAS3(),C=y.get("requestBody"),_=T()(e=un()(T()(o).call(o,(function(e,t){var n,r=t.get("in");return null!==(n=e[r])&&void 0!==n||(e[r]=[]),e[r].push(t),e}),{}))).call(e,(function(e,t){return c()(e).call(e,t)}),[]);return D.a.createElement("div",{className:"opblock-section"},D.a.createElement("div",{className:"opblock-section-header"},O?D.a.createElement("div",{className:"tab-header"},D.a.createElement("div",{onClick:function(){return n.toggleTab("parameters")},className:"tab-item ".concat(this.state.parametersVisible&&"active")},D.a.createElement("h4",{className:"opblock-title"},D.a.createElement("span",null,"Parameters"))),y.get("callbacks")?D.a.createElement("div",{onClick:function(){return n.toggleTab("callbacks")},className:"tab-item ".concat(this.state.callbackVisible&&"active")},D.a.createElement("h4",{className:"opblock-title"},D.a.createElement("span",null,"Callbacks"))):null):D.a.createElement("div",{className:"tab-header"},D.a.createElement("h4",{className:"opblock-title"},"Parameters")),i?D.a.createElement(E,{isOAS3:d.isOAS3(),hasUserEditedBody:g.hasUserEditedBody.apply(g,sn()(m)),enabled:s,onCancelClick:this.props.onCancelClick,onTryoutClick:a,onResetClick:function(){return v.setRequestBodyValue({value:void 0,pathMethod:m})}}):null),this.state.parametersVisible?D.a.createElement("div",{className:"parameters-container"},_.length?D.a.createElement("div",{className:"table-container"},D.a.createElement("table",{className:"parameters"},D.a.createElement("thead",null,D.a.createElement("tr",null,D.a.createElement("th",{className:"col_header parameters-col_name"},"Name"),D.a.createElement("th",{className:"col_header parameters-col_description"},"Description"))),D.a.createElement("tbody",null,N()(_).call(_,(function(e,t){var r;return D.a.createElement(b,{fn:l,specPath:u.push(t.toString()),getComponent:p,getConfigs:f,rawParam:e,param:d.parameterWithMetaByIdentity(m,e),key:c()(r="".concat(e.get("in"),".")).call(r,e.get("name")),onChange:n.onChange,onChangeConsumes:n.onChangeConsumesWrapper,specSelectors:d,specActions:h,oas3Actions:v,oas3Selectors:g,pathMethod:m,isExecute:j})}))))):D.a.createElement("div",{className:"opblock-description-wrapper"},D.a.createElement("p",null,"No parameters"))):null,this.state.callbackVisible?D.a.createElement("div",{className:"callbacks-container opblock-description-wrapper"},D.a.createElement(S,{callbacks:Object(B.Map)(y.get("callbacks")),specPath:A()(u).call(u,0,-1).push("callbacks")})):null,O&&C&&this.state.parametersVisible&&D.a.createElement("div",{className:"opblock-section opblock-section-request-body"},D.a.createElement("div",{className:"opblock-section-header"},D.a.createElement("h4",{className:"opblock-title parameter__name ".concat(C.get("required")&&"required")},"Request body"),D.a.createElement("label",null,D.a.createElement(x,{value:g.requestContentType.apply(g,sn()(m)),contentTypes:C.get("content",Object(B.List)()).keySeq(),onChange:function(e){n.onChangeMediaType({value:e,pathMethod:m})},className:"body-param-content-type"}))),D.a.createElement("div",{className:"opblock-description-wrapper"},D.a.createElement(w,{setRetainRequestBodyValueFlag:function(e){return v.setRetainRequestBodyValueFlag({value:e,pathMethod:m})},userHasEditedBody:g.hasUserEditedBody.apply(g,sn()(m)),specPath:A()(u).call(u,0,-1).push("requestBody"),requestBody:C,requestBodyValue:g.requestBodyValue.apply(g,sn()(m)),requestBodyInclusionSetting:g.requestBodyInclusionSetting.apply(g,sn()(m)),requestBodyErrors:g.requestBodyErrors.apply(g,sn()(m)),isExecute:j,getConfigs:f,activeExamplesKey:g.activeExamplesMember.apply(g,c()(t=sn()(m)).call(t,["requestBody","requestBody"])),updateActiveExamplesKey:function(e){n.props.oas3Actions.setActiveExamplesMember({name:e,pathMethod:n.props.pathMethod,contextType:"requestBody",contextName:"requestBody"})},onChange:function(e,t){if(t){var n=g.requestBodyValue.apply(g,sn()(m)),r=B.Map.isMap(n)?n:Object(B.Map)();return v.setRequestBodyValue({pathMethod:m,value:r.setIn(t,e)})}v.setRequestBodyValue({value:e,pathMethod:m})},onChangeIncludeEmpty:function(e,t){v.setRequestBodyInclusion({pathMethod:m,value:t,name:e})},contentType:g.requestContentType.apply(g,sn()(m))}))))}}]),n}(M.Component);y()(ln,"defaultProps",{onTryoutClick:Function.prototype,onCancelClick:Function.prototype,tryItOutEnabled:!1,allowTryItOut:!0,onChangeKey:[],specPath:[]});var pn=function(e){var t=e.xKey,n=e.xVal;return D.a.createElement("div",{className:"parameter__extension"},t,": ",String(n))},fn={onChange:function(){},isIncludedOptions:{}},dn=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onCheckboxChange",(function(e){(0,r.props.onChange)(e.target.checked)})),r}return S()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.isIncludedOptions,n=e.onChange,r=t.shouldDispatchInit,a=t.defaultValue;r&&n(a)}},{key:"render",value:function(){var e=this.props,t=e.isIncluded,n=e.isDisabled;return D.a.createElement("div",null,D.a.createElement("label",{className:Kt()("parameter__empty_value_toggle",{disabled:n})},D.a.createElement("input",{type:"checkbox",disabled:n,checked:!n&&t,onChange:this.onCheckboxChange}),"Send empty value"))}}]),n}(M.Component);y()(dn,"defaultProps",fn);var hn=n(113),mn=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onChangeWrapper",(function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=a.props,r=n.onChange,o=n.rawParam;return r(o,""===e||e&&0===e.size?null:e,t)})),y()(ve()(a),"_onExampleSelect",(function(e){a.props.oas3Actions.setActiveExamplesMember({name:e,pathMethod:a.props.pathMethod,contextType:"parameters",contextName:a.getParamKey()})})),y()(ve()(a),"onChangeIncludeEmpty",(function(e){var t=a.props,n=t.specActions,r=t.param,o=t.pathMethod,i=r.get("name"),s=r.get("in");return n.updateEmptyParamInclusion(o,i,s,e)})),y()(ve()(a),"setDefaultValue",(function(){var e=a.props,t=e.specSelectors,n=e.pathMethod,r=e.rawParam,o=e.oas3Selectors,i=t.parameterWithMetaByIdentity(n,r)||Object(B.Map)(),s=Object(hn.a)(i,{isOAS3:t.isOAS3()}).schema,u=i.get("content",Object(B.Map)()).keySeq().first(),l=s?Object($.o)(s.toJS(),u,{includeWriteOnly:!0}):null;if(i&&void 0===i.get("value")&&"body"!==i.get("in")){var p;if(t.isSwagger2())p=void 0!==i.get("x-example")?i.get("x-example"):void 0!==i.getIn(["schema","example"])?i.getIn(["schema","example"]):s&&s.getIn(["default"]);else if(t.isOAS3()){var f,d=o.activeExamplesMember.apply(o,c()(f=sn()(n)).call(f,["parameters",a.getParamKey()]));p=void 0!==i.getIn(["examples",d,"value"])?i.getIn(["examples",d,"value"]):void 0!==i.getIn(["content",u,"example"])?i.getIn(["content",u,"example"]):void 0!==i.get("example")?i.get("example"):void 0!==(s&&s.get("example"))?s&&s.get("example"):void 0!==(s&&s.get("default"))?s&&s.get("default"):i.get("default")}void 0===p||B.List.isList(p)||(p=Object($.J)(p)),void 0!==p?a.onChangeWrapper(p):s&&"object"===s.get("type")&&l&&!i.get("examples")&&a.onChangeWrapper(B.List.isList(l)?l:Object($.J)(l))}})),a.setDefaultValue(),a}return S()(n,[{key:"componentWillReceiveProps",value:function(e){var t,n=e.specSelectors,r=e.pathMethod,a=e.rawParam,o=n.isOAS3(),i=n.parameterWithMetaByIdentity(r,a)||new B.Map;if(i=i.isEmpty()?a:i,o){var s=Object(hn.a)(i,{isOAS3:o}).schema;t=s?s.get("enum"):void 0}else t=i?i.get("enum"):void 0;var c,u=i?i.get("value"):void 0;void 0!==u?c=u:a.get("required")&&t&&t.size&&(c=t.first()),void 0!==c&&c!==u&&this.onChangeWrapper(Object($.x)(c)),this.setDefaultValue()}},{key:"getParamKey",value:function(){var e,t=this.props.param;return t?c()(e="".concat(t.get("name"),"-")).call(e,t.get("in")):null}},{key:"render",value:function(){var e,t,n,r,a,o=this.props,i=o.param,s=o.rawParam,u=o.getComponent,l=o.getConfigs,p=o.isExecute,f=o.fn,d=o.onChangeConsumes,h=o.specSelectors,m=o.pathMethod,v=o.specPath,g=o.oas3Selectors,y=h.isOAS3(),b=l(),E=b.showExtensions,x=b.showCommonExtensions;if(i||(i=s),!s)return null;var S,w,j,O,C=u("JsonSchemaForm"),_=u("ParamBody"),A=i.get("in"),k="body"!==A?null:D.a.createElement(_,{getComponent:u,getConfigs:l,fn:f,param:i,consumes:h.consumesOptionsFor(m),consumesValue:h.contentTypeValues(m).get("requestContentType"),onChange:this.onChangeWrapper,onChangeConsumes:d,isExecute:p,specSelectors:h,pathMethod:m}),I=u("modelExample"),P=u("Markdown",!0),T=u("ParameterExt"),R=u("ParameterIncludeEmpty"),M=u("ExamplesSelectValueRetainer"),q=u("Example"),L=Object(hn.a)(i,{isOAS3:y}).schema,U=h.parameterWithMetaByIdentity(m,s)||Object(B.Map)(),V=L?L.get("format"):null,z=L?L.get("type"):null,F=L?L.getIn(["items","type"]):null,J="formData"===A,W="FormData"in H.a,Y=i.get("required"),K=U?U.get("value"):"",G=x?Object($.l)(L):null,Z=E?Object($.m)(i):null,X=!1;return void 0!==i&&L&&(S=L.get("items")),void 0!==S?(w=S.get("enum"),j=S.get("default")):L&&(w=L.get("enum")),w&&w.size&&w.size>0&&(X=!0),void 0!==i&&(L&&(j=L.get("default")),void 0===j&&(j=i.get("default")),void 0===(O=i.get("example"))&&(O=i.get("x-example"))),D.a.createElement("tr",{"data-param-name":i.get("name"),"data-param-in":i.get("in")},D.a.createElement("td",{className:"parameters-col_name"},D.a.createElement("div",{className:Y?"parameter__name required":"parameter__name"},i.get("name"),Y?D.a.createElement("span",null," *"):null),D.a.createElement("div",{className:"parameter__type"},z,F&&"[".concat(F,"]"),V&&D.a.createElement("span",{className:"prop-format"},"($",V,")")),D.a.createElement("div",{className:"parameter__deprecated"},y&&i.get("deprecated")?"deprecated":null),D.a.createElement("div",{className:"parameter__in"},"(",i.get("in"),")"),x&&G.size?N()(e=G.entrySeq()).call(e,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(T,{key:c()(t="".concat(r,"-")).call(t,a),xKey:r,xVal:a})})):null,E&&Z.size?N()(t=Z.entrySeq()).call(t,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(T,{key:c()(t="".concat(r,"-")).call(t,a),xKey:r,xVal:a})})):null),D.a.createElement("td",{className:"parameters-col_description"},i.get("description")?D.a.createElement(P,{source:i.get("description")}):null,!k&&p||!X?null:D.a.createElement(P,{className:"parameter__enum",source:"<i>Available values</i> : "+N()(w).call(w,(function(e){return e})).toArray().join(", ")}),!k&&p||void 0===j?null:D.a.createElement(P,{className:"parameter__default",source:"<i>Default value</i> : "+j}),!k&&p||void 0===O?null:D.a.createElement(P,{source:"<i>Example</i> : "+O}),J&&!W&&D.a.createElement("div",null,"Error: your browser does not support FormData"),y&&i.get("examples")?D.a.createElement("section",{className:"parameter-controls"},D.a.createElement(M,{examples:i.get("examples"),onSelect:this._onExampleSelect,updateValue:this.onChangeWrapper,getComponent:u,defaultToFirstExample:!0,currentKey:g.activeExamplesMember.apply(g,c()(n=sn()(m)).call(n,["parameters",this.getParamKey()])),currentUserInputValue:K})):null,k?null:D.a.createElement(C,{fn:f,getComponent:u,value:K,required:Y,disabled:!p,description:i.get("description")?c()(r="".concat(i.get("name")," - ")).call(r,i.get("description")):"".concat(i.get("name")),onChange:this.onChangeWrapper,errors:U.get("errors"),schema:L}),k&&L?D.a.createElement(I,{getComponent:u,specPath:v.push("schema"),getConfigs:l,isExecute:p,specSelectors:h,schema:L,example:k,includeWriteOnly:!0}):null,!k&&p&&i.get("allowEmptyValue")?D.a.createElement(R,{onChange:this.onChangeIncludeEmpty,isIncluded:h.parameterInclusionSettingFor(m,i.get("name"),i.get("in")),isDisabled:!Object($.q)(K)}):null,y&&i.get("examples")?D.a.createElement(q,{example:i.getIn(["examples",g.activeExamplesMember.apply(g,c()(a=sn()(m)).call(a,["parameters",this.getParamKey()]))]),getComponent:u,getConfigs:l}):null))}}]),n}(M.Component),vn=n(18),gn=n.n(vn),yn=n(169),bn=n.n(yn),En=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"handleValidateParameters",(function(){var e=r.props,t=e.specSelectors,n=e.specActions,a=e.path,o=e.method;return n.validateParams([a,o]),t.validateBeforeExecute([a,o])})),y()(ve()(r),"handleValidateRequestBody",(function(){var e=r.props,t=e.path,n=e.method,a=e.specSelectors,o=e.oas3Selectors,i=e.oas3Actions,s={missingBodyValue:!1,missingRequiredKeys:[]};i.clearRequestBodyValidateError({path:t,method:n});var c=a.getOAS3RequiredRequestBodyContentType([t,n]),u=o.requestBodyValue(t,n),l=o.validateBeforeExecute([t,n]),p=o.requestContentType(t,n);if(!l)return s.missingBodyValue=!0,i.setRequestBodyValidateError({path:t,method:n,validationErrors:s}),!1;if(!c)return!0;var f=o.validateShallowRequired({oas3RequiredRequestBodyContentType:c,oas3RequestContentType:p,oas3RequestBodyValue:u});return!f||f.length<1||(gn()(f).call(f,(function(e){s.missingRequiredKeys.push(e)})),i.setRequestBodyValidateError({path:t,method:n,validationErrors:s}),!1)})),y()(ve()(r),"handleValidationResultPass",(function(){var e=r.props,t=e.specActions,n=e.operation,a=e.path,o=e.method;r.props.onExecute&&r.props.onExecute(),t.execute({operation:n,path:a,method:o})})),y()(ve()(r),"handleValidationResultFail",(function(){var e=r.props,t=e.specActions,n=e.path,a=e.method;t.clearValidateParams([n,a]),bn()((function(){t.validateParams([n,a])}),40)})),y()(ve()(r),"handleValidationResult",(function(e){e?r.handleValidationResultPass():r.handleValidationResultFail()})),y()(ve()(r),"onClick",(function(){var e=r.handleValidateParameters(),t=r.handleValidateRequestBody(),n=e&&t;r.handleValidationResult(n)})),y()(ve()(r),"onChangeProducesWrapper",(function(e){return r.props.specActions.changeProducesValue([r.props.path,r.props.method],e)})),r}return S()(n,[{key:"render",value:function(){var e=this.props.disabled;return D.a.createElement("button",{className:"btn execute opblock-control__btn",onClick:this.onClick,disabled:e},"Execute")}}]),n}(M.Component),xn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.headers,r=t.getComponent,a=r("Property"),o=r("Markdown",!0);return n&&n.size?D.a.createElement("div",{className:"headers-wrapper"},D.a.createElement("h4",{className:"headers__title"},"Headers:"),D.a.createElement("table",{className:"headers"},D.a.createElement("thead",null,D.a.createElement("tr",{className:"header-row"},D.a.createElement("th",{className:"header-col"},"Name"),D.a.createElement("th",{className:"header-col"},"Description"),D.a.createElement("th",{className:"header-col"},"Type"))),D.a.createElement("tbody",null,N()(e=n.entrySeq()).call(e,(function(e){var t=gt()(e,2),n=t[0],r=t[1];if(!L.a.Map.isMap(r))return null;var i=r.get("description"),s=r.getIn(["schema"])?r.getIn(["schema","type"]):r.getIn(["type"]),c=r.getIn(["schema","example"]);return D.a.createElement("tr",{key:n},D.a.createElement("td",{className:"header-col"},n),D.a.createElement("td",{className:"header-col"},i?D.a.createElement(o,{source:i}):null),D.a.createElement("td",{className:"header-col"},s," ",c?D.a.createElement(a,{propKey:"Example",propVal:c,propClass:"header-example"}):null))})).toArray()))):null}}]),n}(D.a.Component),Sn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.editorActions,n=e.errSelectors,r=e.layoutSelectors,a=e.layoutActions,o=(0,e.getComponent)("Collapse");if(t&&t.jumpToLine)var i=t.jumpToLine;var s=n.allErrors(),c=l()(s).call(s,(function(e){return"thrown"===e.get("type")||"error"===e.get("level")}));if(!c||c.count()<1)return null;var u=r.isShown(["errorPane"],!0),p=c.sortBy((function(e){return e.get("line")}));return D.a.createElement("pre",{className:"errors-wrapper"},D.a.createElement("hgroup",{className:"error"},D.a.createElement("h4",{className:"errors__title"},"Errors"),D.a.createElement("button",{className:"btn errors__clear-btn",onClick:function(){return a.show(["errorPane"],!u)}},u?"Hide":"Show")),D.a.createElement(o,{isOpened:u,animated:!0},D.a.createElement("div",{className:"errors"},N()(p).call(p,(function(e,t){var n=e.get("type");return"thrown"===n||"auth"===n?D.a.createElement(wn,{key:t,error:e.get("error")||e,jumpToLine:i}):"spec"===n?D.a.createElement(jn,{key:t,error:e,jumpToLine:i}):void 0})))))}}]),n}(D.a.Component),wn=function(e){var t=e.error,n=e.jumpToLine;if(!t)return null;var r=t.get("line");return D.a.createElement("div",{className:"error-wrapper"},t?D.a.createElement("div",null,D.a.createElement("h4",null,t.get("source")&&t.get("level")?On(t.get("source"))+" "+t.get("level"):"",t.get("path")?D.a.createElement("small",null," at ",t.get("path")):null),D.a.createElement("span",{className:"message thrown"},t.get("message")),D.a.createElement("div",{className:"error-line"},r&&n?D.a.createElement("a",{onClick:j()(n).call(n,null,r)},"Jump to line ",r):null)):null)},jn=function(e){var t=e.error,n=e.jumpToLine,r=null;return t.get("path")?r=B.List.isList(t.get("path"))?D.a.createElement("small",null,"at ",t.get("path").join(".")):D.a.createElement("small",null,"at ",t.get("path")):t.get("line")&&!n&&(r=D.a.createElement("small",null,"on line ",t.get("line"))),D.a.createElement("div",{className:"error-wrapper"},t?D.a.createElement("div",null,D.a.createElement("h4",null,On(t.get("source"))+" "+t.get("level")," ",r),D.a.createElement("span",{className:"message"},t.get("message")),D.a.createElement("div",{className:"error-line"},n?D.a.createElement("a",{onClick:j()(n).call(n,null,t.get("line"))},"Jump to line ",t.get("line")):null)):null)};function On(e){var t;return N()(t=(e||"").split(" ")).call(t,(function(e){return e[0].toUpperCase()+A()(e).call(e,1)})).join(" ")}wn.defaultProps={jumpToLine:null};var Cn=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onChangeWrapper",(function(e){return r.props.onChange(e.target.value)})),r}return S()(n,[{key:"componentDidMount",value:function(){this.props.contentTypes&&this.props.onChange(this.props.contentTypes.first())}},{key:"componentWillReceiveProps",value:function(e){var t;e.contentTypes&&e.contentTypes.size&&(He()(t=e.contentTypes).call(t,e.value)||e.onChange(e.contentTypes.first()))}},{key:"render",value:function(){var e=this.props,t=e.contentTypes,n=e.className,r=e.value;return t&&t.size?D.a.createElement("div",{className:"content-type-wrapper "+(n||"")},D.a.createElement("select",{className:"content-type",value:r||"",onChange:this.onChangeWrapper},N()(t).call(t,(function(e){return D.a.createElement("option",{key:e,value:e},e)})).toArray())):null}}]),n}(D.a.Component);y()(Cn,"defaultProps",{onChange:function(){},value:null,contentTypes:Object(B.fromJS)(["application/json"])});var _n=n(28),An=n.n(_n),kn=n(49),In=n.n(kn),Pn=n(84),Tn=n.n(Pn);function Rn(){for(var e,t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Tn()(e=l()(n).call(n,(function(e){return!!e})).join(" ")).call(e)}var Nn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.fullscreen,n=e.full,r=In()(e,["fullscreen","full"]);if(t)return D.a.createElement("section",r);var a="swagger-container"+(n?"-full":"");return D.a.createElement("section",An()({},r,{className:Rn(r.className,a)}))}}]),n}(D.a.Component),Mn={mobile:"",tablet:"-tablet",desktop:"-desktop",large:"-hd"},Dn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.hide,r=t.keepContents,a=(t.mobile,t.tablet,t.desktop,t.large,In()(t,["hide","keepContents","mobile","tablet","desktop","large"]));if(n&&!r)return D.a.createElement("span",null);var o=[];for(var i in Mn)if(Mn.hasOwnProperty(i)){var s=Mn[i];if(i in this.props){var u=this.props[i];if(u<1){o.push("none"+s);continue}o.push("block"+s),o.push("col-"+u+s)}}n&&o.push("hidden");var l=Rn.apply(void 0,c()(e=[a.className]).call(e,o));return D.a.createElement("section",An()({},a,{className:l}))}}]),n}(D.a.Component),qn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){return D.a.createElement("div",An()({},this.props,{className:Rn(this.props.className,"wrapper")}))}}]),n}(D.a.Component),Bn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){return D.a.createElement("button",An()({},this.props,{className:Rn(this.props.className,"button")}))}}]),n}(D.a.Component);y()(Bn,"defaultProps",{className:""});var Ln=function(e){return D.a.createElement("textarea",e)},Un=function(e){return D.a.createElement("input",e)},Vn=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a,o;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onChange",(function(e){var t,n,r=a.props,o=r.onChange,i=r.multiple,s=A()([]).call(e.target.options);i?t=N()(n=l()(s).call(s,(function(e){return e.selected}))).call(n,(function(e){return e.value})):t=e.target.value;a.setState({value:t}),o&&o(t)})),o=e.value?e.value:e.multiple?[""]:"",a.state={value:o},a}return S()(n,[{key:"componentWillReceiveProps",value:function(e){e.value!==this.props.value&&this.setState({value:e.value})}},{key:"render",value:function(){var e,t,n=this.props,r=n.allowedValues,a=n.multiple,o=n.allowEmptyValue,i=n.disabled,s=(null===(e=this.state.value)||void 0===e||null===(t=e.toJS)||void 0===t?void 0:t.call(e))||this.state.value;return D.a.createElement("select",{className:this.props.className,multiple:a,value:s,onChange:this.onChange,disabled:i},o?D.a.createElement("option",{value:""},"--"):null,N()(r).call(r,(function(e,t){return D.a.createElement("option",{key:t,value:String(e)},String(e))})))}}]),n}(D.a.Component);y()(Vn,"defaultProps",{multiple:!1,allowEmptyValue:!0});var zn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){return D.a.createElement("a",An()({},this.props,{rel:"noopener noreferrer",className:Rn(this.props.className,"link")}))}}]),n}(D.a.Component),Fn=function(e){var t=e.children;return D.a.createElement("div",{className:"no-margin"}," ",t," ")},Jn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"renderNotAnimated",value:function(){return this.props.isOpened?D.a.createElement(Fn,null,this.props.children):D.a.createElement("noscript",null)}},{key:"render",value:function(){var e=this.props,t=e.animated,n=e.isOpened,r=e.children;return t?(r=n?r:null,D.a.createElement(Fn,null,r)):this.renderNotAnimated()}}]),n}(D.a.Component);y()(Jn,"defaultProps",{isOpened:!1,animated:!1});var Wn=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r,a;E()(this,n);for(var o=arguments.length,i=new Array(o),s=0;s<o;s++)i[s]=arguments[s];return(a=t.call.apply(t,c()(e=[this]).call(e,i))).setTagShown=j()(r=a._setTagShown).call(r,ve()(a)),a}return S()(n,[{key:"_setTagShown",value:function(e,t){this.props.layoutActions.show(e,t)}},{key:"showOp",value:function(e,t){this.props.layoutActions.show(e,t)}},{key:"render",value:function(){var e=this.props,t=e.specSelectors,n=e.layoutSelectors,r=e.layoutActions,a=e.getComponent,o=t.taggedOperations(),i=a("Collapse");return D.a.createElement("div",null,D.a.createElement("h4",{className:"overview-title"},"Overview"),N()(o).call(o,(function(e,t){var a=e.get("operations"),o=["overview-tags",t],s=n.isShown(o,!0);return D.a.createElement("div",{key:"overview-"+t},D.a.createElement("h4",{onClick:function(){return r.show(o,!s)},className:"link overview-tag"}," ",s?"-":"+",t),D.a.createElement(i,{isOpened:s,animated:!0},N()(a).call(a,(function(e){var t=e.toObject(),a=t.path,o=t.method,i=t.id,s="operations",c=i,u=n.isShown([s,c]);return D.a.createElement(Hn,{key:i,path:a,method:o,id:a+"-"+o,shown:u,showOpId:c,showOpIdPrefix:s,href:"#operation-".concat(c),onClick:r.show})})).toArray()))})).toArray(),o.size<1&&D.a.createElement("h3",null," No operations defined in spec! "))}}]),n}(D.a.Component),Hn=function(e){ye()(n,e);var t=Ee()(n);function n(e){var r,a;return E()(this,n),(a=t.call(this,e)).onClick=j()(r=a._onClick).call(r,ve()(a)),a}return S()(n,[{key:"_onClick",value:function(){var e=this.props,t=e.showOpId,n=e.showOpIdPrefix;(0,e.onClick)([n,t],!e.shown)}},{key:"render",value:function(){var e=this.props,t=e.id,n=e.method,r=e.shown,a=e.href;return D.a.createElement(zn,{href:a,onClick:this.onClick,className:"block opblock-link ".concat(r?"shown":"")},D.a.createElement("div",null,D.a.createElement("small",{className:"bold-label-".concat(n)},n.toUpperCase()),D.a.createElement("span",{className:"bold-label"},t)))}}]),n}(D.a.Component),$n=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"componentDidMount",value:function(){this.props.initialValue&&(this.inputRef.value=this.props.initialValue)}},{key:"render",value:function(){var e=this,t=this.props,n=(t.value,t.defaultValue,t.initialValue,In()(t,["value","defaultValue","initialValue"]));return D.a.createElement("input",An()({},n,{ref:function(t){return e.inputRef=t}}))}}]),n}(D.a.Component),Yn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.host,n=e.basePath;return D.a.createElement("pre",{className:"base-url"},"[ Base URL: ",t,n," ]")}}]),n}(D.a.Component),Kn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.data,n=e.getComponent,r=e.selectedServer,a=e.url,o=t.get("name")||"the developer",i=ct(t.get("url"),a,{selectedServer:r}),s=t.get("email"),c=n("Link");return D.a.createElement("div",{className:"info__contact"},i&&D.a.createElement("div",null,D.a.createElement(c,{href:Object($.G)(i),target:"_blank"},o," - Website")),s&&D.a.createElement(c,{href:Object($.G)("mailto:".concat(s))},i?"Send email to ".concat(o):"Contact ".concat(o)))}}]),n}(D.a.Component),Gn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.license,n=e.getComponent,r=e.selectedServer,a=e.url,o=n("Link"),i=t.get("name")||"License",s=ct(t.get("url"),a,{selectedServer:r});return D.a.createElement("div",{className:"info__license"},s?D.a.createElement(o,{target:"_blank",href:Object($.G)(s)},i):D.a.createElement("span",null,i))}}]),n}(D.a.Component),Zn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.url,n=(0,e.getComponent)("Link");return D.a.createElement(n,{target:"_blank",href:Object($.G)(t)},D.a.createElement("span",{className:"url"}," ",t))}}]),n}(D.a.PureComponent),Xn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.info,n=e.url,r=e.host,a=e.basePath,o=e.getComponent,i=e.externalDocs,s=e.selectedServer,c=e.url,u=t.get("version"),l=t.get("description"),p=t.get("title"),f=ct(t.get("termsOfService"),c,{selectedServer:s}),d=t.get("contact"),h=t.get("license"),m=ct(i&&i.get("url"),c,{selectedServer:s}),v=i&&i.get("description"),g=o("Markdown",!0),y=o("Link"),b=o("VersionStamp"),E=o("InfoUrl"),x=o("InfoBasePath");return D.a.createElement("div",{className:"info"},D.a.createElement("hgroup",{className:"main"},D.a.createElement("h2",{className:"title"},p,u&&D.a.createElement(b,{version:u})),r||a?D.a.createElement(x,{host:r,basePath:a}):null,n&&D.a.createElement(E,{getComponent:o,url:n})),D.a.createElement("div",{className:"description"},D.a.createElement(g,{source:l})),f&&D.a.createElement("div",{className:"info__tos"},D.a.createElement(y,{target:"_blank",href:Object($.G)(f)},"Terms of service")),d&&d.size?D.a.createElement(Kn,{getComponent:o,data:d,selectedServer:s,url:n}):null,h&&h.size?D.a.createElement(Gn,{getComponent:o,license:h,selectedServer:s,url:n}):null,m?D.a.createElement(y,{className:"info__extdocs",target:"_blank",href:Object($.G)(m)},v||m):null)}}]),n}(D.a.Component),Qn=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,n=e.getComponent,r=e.oas3Selectors,a=t.info(),o=t.url(),i=t.basePath(),s=t.host(),c=t.externalDocs(),u=r.selectedServer(),l=n("info");return D.a.createElement("div",null,a&&a.count()?D.a.createElement(l,{info:a,url:o,host:s,basePath:i,externalDocs:c,getComponent:n,selectedServer:u}):null)}}]),n}(D.a.Component),er=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){return null}}]),n}(D.a.Component),tr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){return D.a.createElement("div",{className:"footer"})}}]),n}(D.a.Component),nr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onFilterChange",(function(e){var t=e.target.value;r.props.layoutActions.updateFilter(t)})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,n=e.layoutSelectors,r=(0,e.getComponent)("Col"),a="loading"===t.loadingStatus(),o="failed"===t.loadingStatus(),i=n.currentFilter(),s=["operation-filter-input"];return o&&s.push("failed"),a&&s.push("loading"),D.a.createElement("div",null,null===i||!1===i||"false"===i?null:D.a.createElement("div",{className:"filter-container"},D.a.createElement(r,{className:"filter wrapper",mobile:12},D.a.createElement("input",{className:s.join(" "),placeholder:"Filter by tag",type:"text",onChange:this.onFilterChange,value:!0===i||"true"===i?"":i,disabled:a}))))}}]),n}(D.a.Component),rr=Function.prototype,ar=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"updateValues",(function(e){var t=e.param,n=e.isExecute,r=e.consumesValue,o=void 0===r?"":r,i=/xml/i.test(o),s=/json/i.test(o),c=i?t.get("value_xml"):t.get("value");if(void 0!==c){var u=!c&&s?"{}":c;a.setState({value:u}),a.onChange(u,{isXml:i,isEditBox:n})}else i?a.onChange(a.sample("xml"),{isXml:i,isEditBox:n}):a.onChange(a.sample(),{isEditBox:n})})),y()(ve()(a),"sample",(function(e){var t=a.props,n=t.param,r=(0,t.fn.inferSchema)(n.toJS());return Object($.o)(r,e,{includeWriteOnly:!0})})),y()(ve()(a),"onChange",(function(e,t){var n=t.isEditBox,r=t.isXml;a.setState({value:e,isEditBox:n}),a._onChange(e,r)})),y()(ve()(a),"_onChange",(function(e,t){(a.props.onChange||rr)(e,t)})),y()(ve()(a),"handleOnChange",(function(e){var t=a.props.consumesValue,n=/xml/i.test(t),r=e.target.value;a.onChange(r,{isXml:n})})),y()(ve()(a),"toggleIsEditBox",(function(){return a.setState((function(e){return{isEditBox:!e.isEditBox}}))})),a.state={isEditBox:!1,value:""},a}return S()(n,[{key:"componentDidMount",value:function(){this.updateValues.call(this,this.props)}},{key:"componentWillReceiveProps",value:function(e){this.updateValues.call(this,e)}},{key:"render",value:function(){var e=this.props,t=e.onChangeConsumes,r=e.param,a=e.isExecute,o=e.specSelectors,i=e.pathMethod,s=e.getConfigs,c=e.getComponent,u=c("Button"),l=c("TextArea"),p=c("highlightCode"),f=c("contentType"),d=(o?o.parameterWithMetaByIdentity(i,r):r).get("errors",Object(B.List)()),h=o.contentTypeValues(i).get("requestContentType"),m=this.props.consumes&&this.props.consumes.size?this.props.consumes:n.defaultProp.consumes,v=this.state,g=v.value,y=v.isEditBox;return D.a.createElement("div",{className:"body-param","data-param-name":r.get("name"),"data-param-in":r.get("in")},y&&a?D.a.createElement(l,{className:"body-param__text"+(d.count()?" invalid":""),value:g,onChange:this.handleOnChange}):g&&D.a.createElement(p,{className:"body-param__example",getConfigs:s,value:g}),D.a.createElement("div",{className:"body-param-options"},a?D.a.createElement("div",{className:"body-param-edit"},D.a.createElement(u,{className:y?"btn cancel body-param__example-edit":"btn edit body-param__example-edit",onClick:this.toggleIsEditBox},y?"Cancel":"Edit")):null,D.a.createElement("label",{htmlFor:""},D.a.createElement("span",null,"Parameter content type"),D.a.createElement(f,{value:h,contentTypes:m,onChange:t,className:"body-param-content-type"}))))}}]),n}(M.PureComponent);y()(ar,"defaultProp",{consumes:Object(B.fromJS)(["application/json"]),param:Object(B.fromJS)({}),onChange:rr,onChangeConsumes:rr});var or=n(45),ir=n.n(or),sr=n(71),cr=n.n(sr),ur=function(e){var t,n="_**[]";return Se()(e).call(e,n)<0?e:Tn()(t=e.split(n)[0]).call(t)};var lr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.request,n=e.getConfigs,r=function(e){var t,n=[],r=!1,a=e.get("headers");if(n.push("curl"),e.get("curlOptions")&&n.push.apply(n,sn()(e.get("curlOptions"))),n.push("-X",e.get("method")),n.push('"'.concat(e.get("url"),'"')),a&&a.size){var o,i,s=ir()(cr()(o=e.get("headers")).call(o));try{for(s.s();!(i=s.n()).done;){var u,l=i.value,p=gt()(l,2),f=p[0],d=p[1];n.push("-H "),n.push(c()(u='"'.concat(f,": ")).call(u,d.replace(/\$/g,"\\$"),'"')),r=r||/^content-type$/i.test(f)&&/^multipart\/form-data$/i.test(d)}}catch(e){s.e(e)}finally{s.f()}}if(e.get("body"))if(r&&He()(t=["POST","PUT","PATCH"]).call(t,e.get("method"))){var m,v=ir()(e.get("body").entrySeq());try{for(v.s();!(m=v.n()).done;){var g,y,b,E=gt()(m.value,2),x=E[0],S=E[1],w=ur(x);n.push("-F"),S instanceof H.a.File?n.push(c()(g=c()(y='"'.concat(w,"=@")).call(y,S.name)).call(g,S.type?";type=".concat(S.type):"",'"')):n.push(c()(b='"'.concat(w,"=")).call(b,S,'"'))}}catch(e){v.e(e)}finally{v.f()}}else{n.push("-d");var j=e.get("body");if(B.Map.isMap(j)){var O,C=[],_=ir()(e.get("body").entrySeq());try{for(_.s();!(O=_.n()).done;){var A,k,I,P=gt()(O.value,2),T=P[0],R=P[1],N=ur(T);R instanceof H.a.File?C.push(c()(A=c()(k='"'.concat(N,'":{"name":"')).call(k,R.name,'"')).call(A,R.type?',"type":"'.concat(R.type,'"'):"","}")):C.push(c()(I='"'.concat(N,'":')).call(I,h()(R).replace(/\\n/g,"").replace("$","\\$")))}}catch(e){_.e(e)}finally{_.f()}n.push("{".concat(C.join(),"}"))}else n.push(h()(e.get("body")).replace(/\\n/g,"").replace(/\$/g,"\\$"))}else e.get("body")||"POST"!==e.get("method")||(n.push("-d"),n.push('""'));return n.join(" ")}(t),a=n(),o=Bt()(a,"syntaxHighlight.activated")?D.a.createElement(Et.Light,{language:"bash",className:"curl microlight",onWheel:this.preventYScrollingBeyondElement,style:Dt(Bt()(a,"syntaxHighlight.theme"))},r):D.a.createElement("textarea",{readOnly:!0,className:"curl",value:r});return D.a.createElement("div",{className:"curl-command"},D.a.createElement("h4",null,"Curl"),D.a.createElement("div",{className:"copy-to-clipboard"},D.a.createElement(Vt.CopyToClipboard,{text:r},D.a.createElement("button",null))),D.a.createElement("div",null,o))}}]),n}(D.a.Component),pr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onChange",(function(e){r.setScheme(e.target.value)})),y()(ve()(r),"setScheme",(function(e){var t=r.props,n=t.path,a=t.method;t.specActions.setScheme(e,n,a)})),r}return S()(n,[{key:"componentWillMount",value:function(){var e=this.props.schemes;this.setScheme(e.first())}},{key:"componentWillReceiveProps",value:function(e){var t;this.props.currentScheme&&He()(t=e.schemes).call(t,this.props.currentScheme)||this.setScheme(e.schemes.first())}},{key:"render",value:function(){var e,t=this.props,n=t.schemes,r=t.currentScheme;return D.a.createElement("label",{htmlFor:"schemes"},D.a.createElement("span",{className:"schemes-title"},"Schemes"),D.a.createElement("select",{onChange:this.onChange,value:r},N()(e=n.valueSeq()).call(e,(function(e){return D.a.createElement("option",{value:e,key:e},e)})).toArray()))}}]),n}(D.a.Component),fr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.specActions,n=e.specSelectors,r=e.getComponent,a=n.operationScheme(),o=n.schemes(),i=r("schemes");return o&&o.size?D.a.createElement(i,{currentScheme:a,schemes:o,specActions:t}):null}}]),n}(D.a.Component),dr=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"toggleCollapsed",(function(){a.props.onToggle&&a.props.onToggle(a.props.modelName,!a.state.expanded),a.setState({expanded:!a.state.expanded})})),y()(ve()(a),"onLoad",(function(e){if(e&&a.props.layoutSelectors){var t=a.props.layoutSelectors.getScrollToKey();L.a.is(t,a.props.specPath)&&a.toggleCollapsed(),a.props.layoutActions.readyToScroll(a.props.specPath,e.parentElement)}}));var o=a.props,i=o.expanded,s=o.collapsedContent;return a.state={expanded:i,collapsedContent:s||n.defaultProps.collapsedContent},a}return S()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.hideSelfOnExpand,n=e.expanded,r=e.modelName;t&&n&&this.props.onToggle(r,n)}},{key:"componentWillReceiveProps",value:function(e){this.props.expanded!==e.expanded&&this.setState({expanded:e.expanded})}},{key:"render",value:function(){var e=this.props,t=e.title,n=e.classes;return this.state.expanded&&this.props.hideSelfOnExpand?D.a.createElement("span",{className:n||""},this.props.children):D.a.createElement("span",{className:n||"",ref:this.onLoad},t&&D.a.createElement("span",{onClick:this.toggleCollapsed,className:"pointer"},t),D.a.createElement("span",{onClick:this.toggleCollapsed,className:"pointer"},D.a.createElement("span",{className:"model-toggle"+(this.state.expanded?"":" collapsed")})),this.state.expanded?this.props.children:D.a.createElement("span",{onClick:this.toggleCollapsed,className:"pointer"},this.state.collapsedContent))}}]),n}(M.Component);y()(dr,"defaultProps",{collapsedContent:"{...}",expanded:!1,title:null,onToggle:function(){},hideSelfOnExpand:!1,specPath:L.a.List([])});var hr=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;E()(this,n),a=t.call(this,e,r),y()(ve()(a),"activeTab",(function(e){var t=e.target.dataset.name;a.setState({activeTab:t})}));var o=a.props,i=o.getConfigs,s=o.isExecute,c=i().defaultModelRendering,u=c;return"example"!==c&&"model"!==c&&(u="example"),s&&(u="example"),a.state={activeTab:u},a}return S()(n,[{key:"componentWillReceiveProps",value:function(e){e.isExecute&&!this.props.isExecute&&this.props.example&&this.setState({activeTab:"example"})}},{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.specSelectors,r=e.schema,a=e.example,o=e.isExecute,i=e.getConfigs,s=e.specPath,c=e.includeReadOnly,u=e.includeWriteOnly,l=i().defaultModelExpandDepth,p=t("ModelWrapper"),f=t("highlightCode"),d=n.isOAS3();return D.a.createElement("div",{className:"model-example"},D.a.createElement("ul",{className:"tab"},D.a.createElement("li",{className:"tabitem"+("example"===this.state.activeTab?" active":"")},D.a.createElement("a",{className:"tablinks","data-name":"example",onClick:this.activeTab},o?"Edit Value":"Example Value")),r?D.a.createElement("li",{className:"tabitem"+("model"===this.state.activeTab?" active":"")},D.a.createElement("a",{className:"tablinks"+(o?" inactive":""),"data-name":"model",onClick:this.activeTab},d?"Schema":"Model")):null),D.a.createElement("div",null,"example"===this.state.activeTab?a||D.a.createElement(f,{value:"(no example available)",getConfigs:i}):null,"model"===this.state.activeTab&&D.a.createElement(p,{schema:r,getComponent:t,getConfigs:i,specSelectors:n,expandDepth:l,specPath:s,includeReadOnly:c,includeWriteOnly:u})))}}]),n}(D.a.Component),mr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onToggle",(function(e,t){r.props.layoutActions&&r.props.layoutActions.show(r.props.fullPath,t)})),r}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.getComponent,r=t.getConfigs,a=n("Model");return this.props.layoutSelectors&&(e=this.props.layoutSelectors.isShown(this.props.fullPath)),D.a.createElement("div",{className:"model-box"},D.a.createElement(a,An()({},this.props,{getConfigs:r,expanded:e,depth:1,onToggle:this.onToggle,expandDepth:this.props.expandDepth||0})))}}]),n}(M.Component),vr=n(172),gr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"getSchemaBasePath",(function(){return r.props.specSelectors.isOAS3()?["components","schemas"]:["definitions"]})),y()(ve()(r),"getCollapsedContent",(function(){return" "})),y()(ve()(r),"handleToggle",(function(e,t){var n,a;(r.props.layoutActions.show(c()(n=[]).call(n,sn()(r.getSchemaBasePath()),[e]),t),t)&&r.props.specActions.requestResolvedSubtree(c()(a=[]).call(a,sn()(r.getSchemaBasePath()),[e]))})),y()(ve()(r),"onLoadModels",(function(e){e&&r.props.layoutActions.readyToScroll(r.getSchemaBasePath(),e)})),y()(ve()(r),"onLoadModel",(function(e){if(e){var t,n=e.getAttribute("data-name");r.props.layoutActions.readyToScroll(c()(t=[]).call(t,sn()(r.getSchemaBasePath()),[n]),e)}})),r}return S()(n,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.specSelectors,a=n.getComponent,o=n.layoutSelectors,i=n.layoutActions,s=n.getConfigs,u=r.definitions(),l=s(),p=l.docExpansion,f=l.defaultModelsExpandDepth;if(!u.size||f<0)return null;var d=this.getSchemaBasePath(),h=o.isShown(d,f>0&&"none"!==p),m=r.isOAS3(),v=a("ModelWrapper"),g=a("Collapse"),y=a("ModelCollapse"),b=a("JumpToPath");return D.a.createElement("section",{className:h?"models is-open":"models",ref:this.onLoadModels},D.a.createElement("h4",{onClick:function(){return i.show(d,!h)}},D.a.createElement("span",null,m?"Schemas":"Models"),D.a.createElement("svg",{width:"20",height:"20"},D.a.createElement("use",{xlinkHref:h?"#large-arrow-down":"#large-arrow"}))),D.a.createElement(g,{isOpened:h},N()(e=u.entrySeq()).call(e,(function(e){var n,u=gt()(e,1)[0],l=c()(n=[]).call(n,sn()(d),[u]),p=L.a.List(l),h=r.specResolvedSubtree(l),m=r.specJson().getIn(l),g=B.Map.isMap(h)?h:L.a.Map(),E=B.Map.isMap(m)?m:L.a.Map(),x=g.get("title")||E.get("title")||u,S=o.isShown(l,!1);S&&0===g.size&&E.size>0&&t.props.specActions.requestResolvedSubtree(l);var w=D.a.createElement(v,{name:u,expandDepth:f,schema:g||L.a.Map(),displayName:x,fullPath:l,specPath:p,getComponent:a,specSelectors:r,getConfigs:s,layoutSelectors:o,layoutActions:i,includeReadOnly:!0,includeWriteOnly:!0}),j=D.a.createElement("span",{className:"model-box"},D.a.createElement("span",{className:"model model-title"},x));return D.a.createElement("div",{id:"model-".concat(u),className:"model-container",key:"models-section-".concat(u),"data-name":u,ref:t.onLoadModel},D.a.createElement("span",{className:"models-jump-to-path"},D.a.createElement(b,{specPath:p})),D.a.createElement(y,{classes:"model-box",collapsedContent:t.getCollapsedContent(u),onToggle:t.handleToggle,title:j,displayName:x,modelName:u,specPath:p,layoutSelectors:o,layoutActions:i,hideSelfOnExpand:!0,expanded:f>0&&S},w))})).toArray()))}}]),n}(M.Component),yr=function(e){var t=e.value,n=(0,e.getComponent)("ModelCollapse"),r=D.a.createElement("span",null,"Array [ ",t.count()," ]");return D.a.createElement("span",{className:"prop-enum"},"Enum:",D.a.createElement("br",null),D.a.createElement(n,{collapsedContent:r},"[ ",t.join(", ")," ]"))},br=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t,n,r,a=this.props,o=a.schema,i=a.name,s=a.displayName,u=a.isRef,p=a.getComponent,f=a.getConfigs,d=a.depth,m=a.onToggle,v=a.expanded,g=a.specPath,y=In()(a,["schema","name","displayName","isRef","getComponent","getConfigs","depth","onToggle","expanded","specPath"]),b=y.specSelectors,E=y.expandDepth,x=y.includeReadOnly,S=y.includeWriteOnly,w=b.isOAS3;if(!o)return null;var j=f().showExtensions,O=o.get("description"),C=o.get("properties"),_=o.get("additionalProperties"),k=o.get("title")||s||i,I=o.get("required"),P=l()(o).call(o,(function(e,t){var n;return-1!==Se()(n=["maxProperties","minProperties","nullable","example"]).call(n,t)})),T=o.get("deprecated"),R=p("JumpToPath",!0),M=p("Markdown",!0),q=p("Model"),L=p("ModelCollapse"),U=p("Property"),V=function(){return D.a.createElement("span",{className:"model-jump-to-path"},D.a.createElement(R,{specPath:g}))},z=D.a.createElement("span",null,D.a.createElement("span",null,"{"),"...",D.a.createElement("span",null,"}"),u?D.a.createElement(V,null):""),F=b.isOAS3()?o.get("anyOf"):null,J=b.isOAS3()?o.get("oneOf"):null,W=b.isOAS3()?o.get("not"):null,H=k&&D.a.createElement("span",{className:"model-title"},u&&o.get("$$ref")&&D.a.createElement("span",{className:"model-hint"},o.get("$$ref")),D.a.createElement("span",{className:"model-title__text"},k));return D.a.createElement("span",{className:"model"},D.a.createElement(L,{modelName:i,title:H,onToggle:m,expanded:!!v||d<=E,collapsedContent:z},D.a.createElement("span",{className:"brace-open object"},"{"),u?D.a.createElement(V,null):null,D.a.createElement("span",{className:"inner-object"},D.a.createElement("table",{className:"model"},D.a.createElement("tbody",null,O?D.a.createElement("tr",{className:"description"},D.a.createElement("td",null,"description:"),D.a.createElement("td",null,D.a.createElement(M,{source:O}))):null,T?D.a.createElement("tr",{className:"property"},D.a.createElement("td",null,"deprecated:"),D.a.createElement("td",null,"true")):null,C&&C.size?N()(e=l()(t=C.entrySeq()).call(t,(function(e){var t=gt()(e,2)[1];return(!t.get("readOnly")||x)&&(!t.get("writeOnly")||S)}))).call(e,(function(e){var t,n,r=gt()(e,2),a=r[0],o=r[1],s=w()&&o.get("deprecated"),u=B.List.isList(I)&&I.contains(a),l=["property-row"];return s&&l.push("deprecated"),u&&l.push("required"),D.a.createElement("tr",{key:a,className:l.join(" ")},D.a.createElement("td",null,a,u&&D.a.createElement("span",{className:"star"},"*")),D.a.createElement("td",null,D.a.createElement(q,An()({key:c()(t=c()(n="object-".concat(i,"-")).call(n,a,"_")).call(t,o)},y,{required:u,getComponent:p,specPath:g.push("properties",a),getConfigs:f,schema:o,depth:d+1}))))})).toArray():null,j?D.a.createElement("tr",null,D.a.createElement("td",null," ")):null,j?N()(n=o.entrySeq()).call(n,(function(e){var t=gt()(e,2),n=t[0],r=t[1];if("x-"===A()(n).call(n,0,2)){var a=r?r.toJS?r.toJS():r:null;return D.a.createElement("tr",{key:n,className:"extension"},D.a.createElement("td",null,n),D.a.createElement("td",null,h()(a)))}})).toArray():null,_&&_.size?D.a.createElement("tr",null,D.a.createElement("td",null,"< * >:"),D.a.createElement("td",null,D.a.createElement(q,An()({},y,{required:!1,getComponent:p,specPath:g.push("additionalProperties"),getConfigs:f,schema:_,depth:d+1})))):null,F?D.a.createElement("tr",null,D.a.createElement("td",null,"anyOf ->"),D.a.createElement("td",null,N()(F).call(F,(function(e,t){return D.a.createElement("div",{key:t},D.a.createElement(q,An()({},y,{required:!1,getComponent:p,specPath:g.push("anyOf",t),getConfigs:f,schema:e,depth:d+1})))})))):null,J?D.a.createElement("tr",null,D.a.createElement("td",null,"oneOf ->"),D.a.createElement("td",null,N()(J).call(J,(function(e,t){return D.a.createElement("div",{key:t},D.a.createElement(q,An()({},y,{required:!1,getComponent:p,specPath:g.push("oneOf",t),getConfigs:f,schema:e,depth:d+1})))})))):null,W?D.a.createElement("tr",null,D.a.createElement("td",null,"not ->"),D.a.createElement("td",null,D.a.createElement("div",null,D.a.createElement(q,An()({},y,{required:!1,getComponent:p,specPath:g.push("not"),getConfigs:f,schema:W,depth:d+1}))))):null))),D.a.createElement("span",{className:"brace-close"},"}")),P.size?N()(r=P.entrySeq()).call(r,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(U,{key:c()(t="".concat(r,"-")).call(t,a),propKey:r,propVal:a,propClass:"property"})})):null)}}]),n}(M.Component),Er=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t=this.props,n=t.getComponent,r=t.getConfigs,a=t.schema,o=t.depth,i=t.expandDepth,s=t.name,u=t.displayName,p=t.specPath,f=a.get("description"),d=a.get("items"),h=a.get("title")||u||s,m=l()(a).call(a,(function(e,t){var n;return-1===Se()(n=["type","items","description","$$ref"]).call(n,t)})),v=n("Markdown",!0),g=n("ModelCollapse"),y=n("Model"),b=n("Property"),E=h&&D.a.createElement("span",{className:"model-title"},D.a.createElement("span",{className:"model-title__text"},h));return D.a.createElement("span",{className:"model"},D.a.createElement(g,{title:E,expanded:o<=i,collapsedContent:"[...]"},"[",m.size?N()(e=m.entrySeq()).call(e,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(b,{key:c()(t="".concat(r,"-")).call(t,a),propKey:r,propVal:a,propClass:"property"})})):null,f?D.a.createElement(v,{source:f}):m.size?D.a.createElement("div",{className:"markdown"}):null,D.a.createElement("span",null,D.a.createElement(y,An()({},this.props,{getConfigs:r,specPath:p.push("items"),name:null,schema:d,required:!1,depth:o+1}))),"]"))}}]),n}(M.Component),xr="property primitive",Sr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e,t,n,r=this.props,a=r.schema,o=r.getComponent,i=r.getConfigs,s=r.name,u=r.displayName,p=r.depth,f=i().showExtensions;if(!a||!a.get)return D.a.createElement("div",null);var d=a.get("type"),h=a.get("format"),m=a.get("xml"),v=a.get("enum"),g=a.get("title")||u||s,y=a.get("description"),b=Object($.m)(a),E=l()(a).call(a,(function(e,t){var n;return-1===Se()(n=["enum","type","format","description","$$ref"]).call(n,t)})).filterNot((function(e,t){return b.has(t)})),x=o("Markdown",!0),S=o("EnumModel"),w=o("Property");return D.a.createElement("span",{className:"model"},D.a.createElement("span",{className:"prop"},s&&D.a.createElement("span",{className:"".concat(1===p&&"model-title"," prop-name")},g),D.a.createElement("span",{className:"prop-type"},d),h&&D.a.createElement("span",{className:"prop-format"},"($",h,")"),E.size?N()(e=E.entrySeq()).call(e,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(w,{key:c()(t="".concat(r,"-")).call(t,a),propKey:r,propVal:a,propClass:xr})})):null,f&&b.size?N()(t=b.entrySeq()).call(t,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement(w,{key:c()(t="".concat(r,"-")).call(t,a),propKey:r,propVal:a,propClass:xr})})):null,y?D.a.createElement(x,{source:y}):null,m&&m.size?D.a.createElement("span",null,D.a.createElement("br",null),D.a.createElement("span",{className:xr},"xml:"),N()(n=m.entrySeq()).call(n,(function(e){var t,n=gt()(e,2),r=n[0],a=n[1];return D.a.createElement("span",{key:c()(t="".concat(r,"-")).call(t,a),className:xr},D.a.createElement("br",null)," ",r,": ",String(a))})).toArray()):null,v&&D.a.createElement(S,{value:v,getComponent:o})))}}]),n}(M.Component),wr=function(e){var t=e.propKey,n=e.propVal,r=e.propClass;return D.a.createElement("span",{className:r},D.a.createElement("br",null),t,": ",String(n))},jr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.onTryoutClick,n=e.onCancelClick,r=e.onResetClick,a=e.enabled,o=e.hasUserEditedBody,i=e.isOAS3&&o;return D.a.createElement("div",{className:i?"try-out btn-group":"try-out"},a?D.a.createElement("button",{className:"btn try-out__btn cancel",onClick:n},"Cancel"):D.a.createElement("button",{className:"btn try-out__btn",onClick:t},"Try it out "),i&&D.a.createElement("button",{className:"btn try-out__btn reset",onClick:r},"Reset"))}}]),n}(D.a.Component);y()(jr,"defaultProps",{onTryoutClick:Function.prototype,onCancelClick:Function.prototype,onResetClick:Function.prototype,enabled:!1,hasUserEditedBody:!1,isOAS3:!1});var Or=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.bypass,n=e.isSwagger2,r=e.isOAS3,a=e.alsoShow;return t?D.a.createElement("div",null,this.props.children):n&&r?D.a.createElement("div",{className:"version-pragma"},a,D.a.createElement("div",{className:"version-pragma__message version-pragma__message--ambiguous"},D.a.createElement("div",null,D.a.createElement("h3",null,"Unable to render this definition"),D.a.createElement("p",null,D.a.createElement("code",null,"swagger")," and ",D.a.createElement("code",null,"openapi")," fields cannot be present in the same Swagger or OpenAPI definition. Please remove one of the fields."),D.a.createElement("p",null,"Supported version fields are ",D.a.createElement("code",null,"swagger: ",'"2.0"')," and those that match ",D.a.createElement("code",null,"openapi: 3.0.n")," (for example, ",D.a.createElement("code",null,"openapi: 3.0.0"),").")))):n||r?D.a.createElement("div",null,this.props.children):D.a.createElement("div",{className:"version-pragma"},a,D.a.createElement("div",{className:"version-pragma__message version-pragma__message--missing"},D.a.createElement("div",null,D.a.createElement("h3",null,"Unable to render this definition"),D.a.createElement("p",null,"The provided definition does not specify a valid version field."),D.a.createElement("p",null,"Please indicate a valid Swagger or OpenAPI version field. Supported version fields are ",D.a.createElement("code",null,"swagger: ",'"2.0"')," and those that match ",D.a.createElement("code",null,"openapi: 3.0.n")," (for example, ",D.a.createElement("code",null,"openapi: 3.0.0"),")."))))}}]),n}(D.a.PureComponent);y()(Or,"defaultProps",{alsoShow:null,children:null,bypass:!1});var Cr=function(e){var t=e.version;return D.a.createElement("small",null,D.a.createElement("pre",{className:"version"}," ",t," "))},_r=function(e){var t=e.enabled,n=e.path,r=e.text;return D.a.createElement("a",{className:"nostyle",onClick:t?function(e){return e.preventDefault()}:null,href:t?"#/".concat(n):null},D.a.createElement("span",null,r))},Ar=function(){return D.a.createElement("div",null,D.a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",className:"svg-assets"},D.a.createElement("defs",null,D.a.createElement("symbol",{viewBox:"0 0 20 20",id:"unlocked"},D.a.createElement("path",{d:"M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V6h2v-.801C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8z"})),D.a.createElement("symbol",{viewBox:"0 0 20 20",id:"locked"},D.a.createElement("path",{d:"M15.8 8H14V5.6C14 2.703 12.665 1 10 1 7.334 1 6 2.703 6 5.6V8H4c-.553 0-1 .646-1 1.199V17c0 .549.428 1.139.951 1.307l1.197.387C5.672 18.861 6.55 19 7.1 19h5.8c.549 0 1.428-.139 1.951-.307l1.196-.387c.524-.167.953-.757.953-1.306V9.199C17 8.646 16.352 8 15.8 8zM12 8H8V5.199C8 3.754 8.797 3 10 3c1.203 0 2 .754 2 2.199V8z"})),D.a.createElement("symbol",{viewBox:"0 0 20 20",id:"close"},D.a.createElement("path",{d:"M14.348 14.849c-.469.469-1.229.469-1.697 0L10 11.819l-2.651 3.029c-.469.469-1.229.469-1.697 0-.469-.469-.469-1.229 0-1.697l2.758-3.15-2.759-3.152c-.469-.469-.469-1.228 0-1.697.469-.469 1.228-.469 1.697 0L10 8.183l2.651-3.031c.469-.469 1.228-.469 1.697 0 .469.469.469 1.229 0 1.697l-2.758 3.152 2.758 3.15c.469.469.469 1.229 0 1.698z"})),D.a.createElement("symbol",{viewBox:"0 0 20 20",id:"large-arrow"},D.a.createElement("path",{d:"M13.25 10L6.109 2.58c-.268-.27-.268-.707 0-.979.268-.27.701-.27.969 0l7.83 7.908c.268.271.268.709 0 .979l-7.83 7.908c-.268.271-.701.27-.969 0-.268-.269-.268-.707 0-.979L13.25 10z"})),D.a.createElement("symbol",{viewBox:"0 0 20 20",id:"large-arrow-down"},D.a.createElement("path",{d:"M17.418 6.109c.272-.268.709-.268.979 0s.271.701 0 .969l-7.908 7.83c-.27.268-.707.268-.979 0l-7.908-7.83c-.27-.268-.27-.701 0-.969.271-.268.709-.268.979 0L10 13.25l7.418-7.141z"})),D.a.createElement("symbol",{viewBox:"0 0 24 24",id:"jump-to"},D.a.createElement("path",{d:"M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"})),D.a.createElement("symbol",{viewBox:"0 0 24 24",id:"expand"},D.a.createElement("path",{d:"M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"})))))},kr=n(174),Ir=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.errSelectors,n=e.specSelectors,r=e.getComponent,a=r("SvgAssets"),o=r("InfoContainer",!0),i=r("VersionPragmaFilter"),s=r("operations",!0),c=r("Models",!0),u=r("Row"),l=r("Col"),p=r("errors",!0),f=r("ServersContainer",!0),d=r("SchemesContainer",!0),h=r("AuthorizeBtnContainer",!0),m=r("FilterContainer",!0),v=n.isSwagger2(),g=n.isOAS3(),y=!n.specStr(),b=n.loadingStatus(),E=null;if("loading"===b&&(E=D.a.createElement("div",{className:"info"},D.a.createElement("div",{className:"loading-container"},D.a.createElement("div",{className:"loading"})))),"failed"===b&&(E=D.a.createElement("div",{className:"info"},D.a.createElement("div",{className:"loading-container"},D.a.createElement("h4",{className:"title"},"Failed to load API definition."),D.a.createElement(p,null)))),"failedConfig"===b){var x=t.lastError(),S=x?x.get("message"):"";E=D.a.createElement("div",{className:"info failed-config"},D.a.createElement("div",{className:"loading-container"},D.a.createElement("h4",{className:"title"},"Failed to load remote configuration."),D.a.createElement("p",null,S)))}if(!E&&y&&(E=D.a.createElement("h4",null,"No API definition provided.")),E)return D.a.createElement("div",{className:"swagger-ui"},D.a.createElement("div",{className:"loading-container"},E));var w=n.servers(),j=n.schemes(),O=w&&w.size,C=j&&j.size,_=!!n.securityDefinitions();return D.a.createElement("div",{className:"swagger-ui"},D.a.createElement(a,null),D.a.createElement(i,{isSwagger2:v,isOAS3:g,alsoShow:D.a.createElement(p,null)},D.a.createElement(p,null),D.a.createElement(u,{className:"information-container"},D.a.createElement(l,{mobile:12},D.a.createElement(o,null))),O||C||_?D.a.createElement("div",{className:"scheme-container"},D.a.createElement(l,{className:"schemes wrapper",mobile:12},O?D.a.createElement(f,null):null,C?D.a.createElement(d,null):null,_?D.a.createElement(h,null):null)):null,D.a.createElement(m,null),D.a.createElement(u,null,D.a.createElement(l,{mobile:12,desktop:12},D.a.createElement(s,null))),D.a.createElement(u,null,D.a.createElement(l,{mobile:12,desktop:12},D.a.createElement(c,null)))))}}]),n}(D.a.Component),Pr=n(279),Tr=n.n(Pr),Rr={value:"",onChange:function(){},schema:{},keyName:"",required:!1,errors:Object(B.List)()},Nr=function(e){ye()(n,e);var t=Ee()(n);function n(){return E()(this,n),t.apply(this,arguments)}return S()(n,[{key:"componentDidMount",value:function(){var e=this.props,t=e.dispatchInitialValue,n=e.value,r=e.onChange;t&&r(n)}},{key:"render",value:function(){var e,t=this.props,n=t.schema,r=t.errors,a=t.value,o=t.onChange,i=t.getComponent,s=t.fn,u=t.disabled,l=n&&n.get?n.get("format"):null,p=n&&n.get?n.get("type"):null,f=function(e){return i(e,!1,{failSilently:!0})},d=p?f(l?c()(e="JsonSchema_".concat(p,"_")).call(e,l):"JsonSchema_".concat(p)):i("JsonSchema_string");return d||(d=i("JsonSchema_string")),D.a.createElement(d,An()({},this.props,{errors:r,fn:s,getComponent:i,value:a,onChange:o,schema:n,disabled:u}))}}]),n}(M.Component);y()(Nr,"defaultProps",Rr);var Mr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onChange",(function(e){var t=r.props.schema&&"file"===r.props.schema.get("type")?e.target.files[0]:e.target.value;r.props.onChange(t,r.props.keyName)})),y()(ve()(r),"onEnumChange",(function(e){return r.props.onChange(e)})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.value,r=e.schema,a=e.errors,o=e.required,i=e.description,s=e.disabled,c=r&&r.get?r.get("enum"):null,u=r&&r.get?r.get("format"):null,l=r&&r.get?r.get("type"):null,p=r&&r.get?r.get("in"):null;if(n||(n=""),a=a.toJS?a.toJS():[],c){var f=t("Select");return D.a.createElement(f,{className:a.length?"invalid":"",title:a.length?a:"",allowedValues:c,value:n,allowEmptyValue:!o,disabled:s,onChange:this.onEnumChange})}var d=s||p&&"formData"===p&&!("FormData"in window),h=t("Input");return l&&"file"===l?D.a.createElement(h,{type:"file",className:a.length?"invalid":"",title:a.length?a:"",onChange:this.onChange,disabled:d}):D.a.createElement(Tr.a,{type:u&&"password"===u?"password":"text",className:a.length?"invalid":"",title:a.length?a:"",value:n,minLength:0,debounceTimeout:350,placeholder:i,onChange:this.onChange,disabled:d})}}]),n}(M.Component);y()(Mr,"defaultProps",Rr);var Dr=function(e){ye()(n,e);var t=Ee()(n);function n(e,r){var a;return E()(this,n),a=t.call(this,e,r),y()(ve()(a),"onChange",(function(){a.props.onChange(a.state.value)})),y()(ve()(a),"onItemChange",(function(e,t){a.setState((function(n){return{value:n.value.set(t,e)}}),a.onChange)})),y()(ve()(a),"removeItem",(function(e){a.setState((function(t){return{value:t.value.delete(e)}}),a.onChange)})),y()(ve()(a),"addItem",(function(){var e=zr(a.state.value);a.setState((function(){return{value:e.push(Object($.o)(a.state.schema.get("items"),!1,{includeWriteOnly:!0}))}}),a.onChange)})),y()(ve()(a),"onEnumChange",(function(e){a.setState((function(){return{value:e}}),a.onChange)})),a.state={value:zr(e.value),schema:e.schema},a}return S()(n,[{key:"componentWillReceiveProps",value:function(e){var t=zr(e.value);t!==this.state.value&&this.setState({value:t}),e.schema!==this.state.schema&&this.setState({schema:e.schema})}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.getComponent,a=n.required,o=n.schema,i=n.errors,s=n.fn,u=n.disabled;i=i.toJS?i.toJS():I()(i)?i:[];var p,f,d=l()(i).call(i,(function(e){return"string"==typeof e})),h=N()(e=l()(i).call(i,(function(e){return void 0!==e.needRemove}))).call(e,(function(e){return e.error})),m=this.state.value,v=!!(m&&m.count&&m.count()>0),g=o.getIn(["items","enum"]),y=o.getIn(["items","type"]),b=o.getIn(["items","format"]),E=o.get("items"),x=!1,S="file"===y||"string"===y&&"binary"===b;y&&b?p=r(c()(f="JsonSchema_".concat(y,"_")).call(f,b)):"boolean"!==y&&"array"!==y&&"object"!==y||(p=r("JsonSchema_".concat(y)));if(p||S||(x=!0),g){var w=r("Select");return D.a.createElement(w,{className:i.length?"invalid":"",title:i.length?i:"",multiple:!0,value:m,disabled:u,allowedValues:g,allowEmptyValue:!a,onChange:this.onEnumChange})}var j=r("Button");return D.a.createElement("div",{className:"json-schema-array"},v?N()(m).call(m,(function(e,n){var a,o=Object(B.fromJS)(sn()(N()(a=l()(i).call(i,(function(e){return e.index===n}))).call(a,(function(e){return e.error}))));return D.a.createElement("div",{key:n,className:"json-schema-form-item"},S?D.a.createElement(Br,{value:e,onChange:function(e){return t.onItemChange(e,n)},disabled:u,errors:o,getComponent:r}):x?D.a.createElement(qr,{value:e,onChange:function(e){return t.onItemChange(e,n)},disabled:u,errors:o}):D.a.createElement(p,An()({},t.props,{value:e,onChange:function(e){return t.onItemChange(e,n)},disabled:u,errors:o,schema:E,getComponent:r,fn:s})),u?null:D.a.createElement(j,{className:"btn btn-sm json-schema-form-item-remove ".concat(h.length?"invalid":null),title:h.length?h:"",onClick:function(){return t.removeItem(n)}}," - "))})):null,u?null:D.a.createElement(j,{className:"btn btn-sm json-schema-form-item-add ".concat(d.length?"invalid":null),title:d.length?d:"",onClick:this.addItem},"Add ",y?"".concat(y," "):"","item"))}}]),n}(M.PureComponent);y()(Dr,"defaultProps",Rr);var qr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onChange",(function(e){var t=e.target.value;r.props.onChange(t,r.props.keyName)})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.value,n=e.errors,r=e.description,a=e.disabled;return t||(t=""),n=n.toJS?n.toJS():[],D.a.createElement(Tr.a,{type:"text",className:n.length?"invalid":"",title:n.length?n:"",value:t,minLength:0,debounceTimeout:350,placeholder:r,onChange:this.onChange,disabled:a})}}]),n}(M.Component);y()(qr,"defaultProps",Rr);var Br=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onFileChange",(function(e){var t=e.target.files[0];r.props.onChange(t,r.props.keyName)})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.errors,r=e.disabled,a=t("Input"),o=r||!("FormData"in window);return D.a.createElement(a,{type:"file",className:n.length?"invalid":"",title:n.length?n:"",onChange:this.onFileChange,disabled:o})}}]),n}(M.Component);y()(Br,"defaultProps",Rr);var Lr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e,r;E()(this,n);for(var a=arguments.length,o=new Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=t.call.apply(t,c()(e=[this]).call(e,o)),y()(ve()(r),"onEnumChange",(function(e){return r.props.onChange(e)})),r}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.value,r=e.errors,a=e.schema,o=e.required,i=e.disabled;r=r.toJS?r.toJS():[];var s=a&&a.get?a.get("enum"):null,c=!s||!o,u=!s&&Object(B.fromJS)(["true","false"]),l=t("Select");return D.a.createElement(l,{className:r.length?"invalid":"",title:r.length?r:"",value:String(n),disabled:i,allowedValues:s||u,allowEmptyValue:c,onChange:this.onEnumChange})}}]),n}(M.Component);y()(Lr,"defaultProps",Rr);var Ur=function(e){return N()(e).call(e,(function(e){var t,n=void 0!==e.propKey?e.propKey:e.index,r="string"==typeof e?e:"string"==typeof e.error?e.error:null;if(!n&&r)return r;for(var a=e.error,o="/".concat(e.propKey);"object"===i()(a);){var s=void 0!==a.propKey?a.propKey:a.index;if(void 0===s)break;if(o+="/".concat(s),!a.error)break;a=a.error}return c()(t="".concat(o,": ")).call(t,a)}))},Vr=function(e){ye()(n,e);var t=Ee()(n);function n(){var e;return E()(this,n),e=t.call(this),y()(ve()(e),"onChange",(function(t){e.props.onChange(t)})),y()(ve()(e),"handleOnChange",(function(t){var n=t.target.value;e.onChange(n)})),e}return S()(n,[{key:"render",value:function(){var e=this.props,t=e.getComponent,n=e.value,r=e.errors,a=e.disabled,o=t("TextArea");return r=r.toJS?r.toJS():I()(r)?r:[],D.a.createElement("div",null,D.a.createElement(o,{className:Kt()({invalid:r.length}),title:r.length?Ur(r).join(", "):"",value:Object($.J)(n),disabled:a,onChange:this.handleOnChange}))}}]),n}(M.PureComponent);function zr(e){return B.List.isList(e)?e:I()(e)?Object(B.fromJS)(e):Object(B.List)()}y()(Vr,"defaultProps",Rr);var Fr=function(){var e={components:{App:Oe,authorizationPopup:Ce,authorizeBtn:_e,AuthorizeBtnContainer:Ae,authorizeOperationBtn:ke,auths:Ie,AuthItem:Pe,authError:Te,oauth2:Ke,apiKeyAuth:Re,basicAuth:Ne,clear:Ge,liveResponse:Qe,InitializedInput:$n,info:Xn,InfoContainer:Qn,JumpToPath:er,onlineValidatorBadge:et.a,operations:rt,operation:lt,OperationSummary:dt,OperationSummaryMethod:ht,OperationSummaryPath:mt,highlightCode:zt,responses:Ft,response:Gt,ResponseExtension:Zt,responseBody:an,parameters:ln,parameterRow:mn,execute:En,headers:xn,errors:Sn,contentType:Cn,overview:Wn,footer:tr,FilterContainer:nr,ParamBody:ar,curl:lr,schemes:pr,SchemesContainer:fr,modelExample:hr,ModelWrapper:mr,ModelCollapse:dr,Model:vr.a,Models:gr,EnumModel:yr,ObjectModel:br,ArrayModel:Er,PrimitiveModel:Sr,Property:wr,TryItOutButton:jr,Markdown:kr.a,BaseLayout:Ir,VersionPragmaFilter:Or,VersionStamp:Cr,OperationExt:yt,OperationExtRow:bt,ParameterExt:pn,ParameterIncludeEmpty:dn,OperationTag:ut,OperationContainer:je,DeepLink:_r,InfoUrl:Zn,InfoBasePath:Yn,SvgAssets:Ar,Example:Me,ExamplesSelect:Be,ExamplesSelectValueRetainer:Ue}},t={components:r},n={components:a};return[pe.default,ue.default,ie.default,ae.default,re.default,te.default,ne.default,oe.default,e,t,se.default,n,ce.default,le.default,fe.default,de.default,he.default]},Jr=n(245);function Wr(){return[Fr,Jr.default]}var Hr=n(266);var $r=!0,Yr="g49172eb",Kr="3.44.1",Gr="ip-172-31-21-173",Zr="Thu, 04 Mar 2021 18:12:15 GMT";function Xr(e){var t;H.a.versions=H.a.versions||{},H.a.versions.swaggerUi={version:Kr,gitRevision:Yr,gitDirty:$r,buildTimestamp:Zr,machine:Gr};var n={dom_id:null,domNode:null,spec:{},url:"",urls:null,layout:"BaseLayout",docExpansion:"list",maxDisplayedTags:null,filter:null,validatorUrl:"https://validator.swagger.io/validator",oauth2RedirectUrl:c()(t="".concat(window.location.protocol,"//")).call(t,window.location.host,"/oauth2-redirect.html"),persistAuthorization:!1,configs:{},custom:{},displayOperationId:!1,displayRequestDuration:!1,deepLinking:!1,tryItOutEnabled:!1,requestInterceptor:function(e){return e},responseInterceptor:function(e){return e},showMutatedRequest:!0,defaultModelRendering:"example",defaultModelExpandDepth:1,defaultModelsExpandDepth:1,showExtensions:!1,showCommonExtensions:!1,withCredentials:void 0,supportedSubmitMethods:["get","put","post","delete","options","head","patch","trace"],presets:[Wr],plugins:[],initialState:{},fn:{},components:{},syntaxHighlight:{activated:!0,theme:"agate"}},r=Object($.D)(),a=e.domNode;delete e.domNode;var o=v()({},n,e,r),s={system:{configs:o.configs},plugins:o.presets,state:v()({layout:{layout:o.layout,filter:l()(o)},spec:{spec:"",url:o.url}},o.initialState)};if(o.initialState)for(var u in o.initialState)o.initialState.hasOwnProperty(u)&&void 0===o.initialState[u]&&delete s.state[u];var p=new K(s);p.register([o.plugins,function(){return{fn:o.fn,components:o.components,state:o.state}}]);var d=p.getSystem(),m=function(e){var t=d.specSelectors.getLocalConfig?d.specSelectors.getLocalConfig():{},n=v()({},t,o,e||{},r);if(a&&(n.domNode=a),p.setConfigs(n),d.configsActions.loaded(),null!==e&&(!r.url&&"object"===i()(n.spec)&&f()(n.spec).length?(d.specActions.updateUrl(""),d.specActions.updateLoadingStatus("success"),d.specActions.updateSpec(h()(n.spec))):d.specActions.download&&n.url&&!n.urls&&(d.specActions.updateUrl(n.url),d.specActions.download(n.url))),n.domNode)d.render(n.domNode,"App");else if(n.dom_id){var s=document.querySelector(n.dom_id);d.render(s,"App")}else null===n.dom_id||null===n.domNode||console.error("Skipped rendering: no `dom_id` or `domNode` was specified");return d},g=r.config||o.configUrl;return g&&d.specActions&&d.specActions.getConfigByUrl?(d.specActions.getConfigByUrl({url:g,loadRemoteConfig:!0,requestInterceptor:o.requestInterceptor,responseInterceptor:o.responseInterceptor},m),d):m()}Xr.presets={apis:Wr},Xr.plugins=Hr.default;t.default=Xr}]).default;
//# sourceMappingURL=swagger-ui-es-bundle-core.js.map |
src/parser/shared/modules/items/bfa/dungeons/ConchofDarkWhispers.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import UptimeIcon from 'interface/icons/Uptime';
import CriticalStrikeIcon from 'interface/icons/CriticalStrike';
import ItemStatistic from 'interface/statistics/ItemStatistic';
import BoringItemValueText from 'interface/statistics/components/BoringItemValueText';
import Analyzer from 'parser/core/Analyzer';
import { formatPercentage, formatNumber } from 'common/format';
import { calculateSecondaryStatDefault } from 'common/stats';
/**
* Conch of Dark Whispers -
* Equip: Your spells have a chance to grant you 455 Critical Strike for 15 sec. (Approximately 1 procs per minute)
*
* Test Log: https://www.warcraftlogs.com/reports/aPkxWyCg9Q4q81Xw#fight=4&type=damage-done
*/
class ConchofDarkWhispers extends Analyzer {
statBuff = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrinket(ITEMS.CONCH_OF_DARK_WHISPERS.id);
if(this.active) {
this.statBuff = calculateSecondaryStatDefault(300, 455, this.selectedCombatant.getItem(ITEMS.CONCH_OF_DARK_WHISPERS.id).itemLevel);
}
}
get totalBuffUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.CONCH_OF_DARK_WHISPERS_BUFF.id) / this.owner.fightDuration;
}
statistic() {
return (
<ItemStatistic
size="flexible"
>
<BoringItemValueText item={ITEMS.CONCH_OF_DARK_WHISPERS}>
<UptimeIcon /> {formatPercentage(this.totalBuffUptime)}% <small>uptime</small><br />
<CriticalStrikeIcon /> {formatNumber(this.totalBuffUptime * this.statBuff)} <small>average Critical Strike gained</small>
</BoringItemValueText>
</ItemStatistic>
);
}
}
export default ConchofDarkWhispers;
|
src/index.js | lewiscowper/react-blessed-hot-motion | import React from 'react';
import { render } from 'react-blessed';
import App from './components/App';
// Render app
const screen = render(<App />, {
autoPadding: true,
smartCSR: true,
title: 'React Blessed Hot Motion'
});
// Let user quit the app
screen.key(['escape', 'q', 'C-c'], function(ch, key) {
return process.exit(0);
});
// Listen to SIGUSR2 indicating hot updates:
import './signal';
// This is dumb but I don't understand how else to prevent process from exiting.
// If it exits, it will get restarted by nodemon, but then hot reloading won't work.
setInterval(() => {}, 1000);
|
ajax/libs/yui/3.0.0pr2/loader/loader-debug.js | freak3dot/cdnjs | /**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
*
* @module yui
* @submodule loader
*/
/**
* Loader dynamically loads script and css files. It includes the dependency
* info for the version of the library in use, and will automatically pull in
* dependencies for the modules requested. It supports rollup files and will
* automatically use these when appropriate in order to minimize the number of
* http connections required to load all of the dependencies. It can load the
* files from the Yahoo! CDN, and it can utilize the combo service provided on
* this network to reduce the number of http connections required to download
* YUI files.
* @class Loader
* @constructor
* @param o an optional set of configuration options. Valid options:
* <ul>
* <li>base:
* The base dir</li>
* <li>secureBase:
* The secure base dir (not implemented)</li>
* <li>comboBase:
* The YUI combo service base dir. Ex: http://yui.yahooapis.com/combo?</li>
* <li>root:
* The root path to prepend to module names for the combo service. Ex: 2.5.2/build/</li>
* <li>filter:
*
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
*
* </li>
* <li>combine:
* Use the YUI combo service to reduce the number of http connections required to load your dependencies</li>
* <li>ignore:
* A list of modules that should never be dynamically loaded</li>
* <li>force:
* A list of modules that should always be loaded when required, even if already present on the page</li>
* <li>insertBefore:
* Node or id for a node that should be used as the insertion point for new nodes</li>
* <li>charset:
* charset for dynamic nodes</li>
* <li>timeout:
* number of milliseconds before a timeout occurs when dynamically loading nodes. in not set, there is no timeout</li>
* <li>context:
* execution context for all callbacks</li>
* <li>onSuccess:
* callback for the 'success' event</li>
* <li>onFailure:
* callback for the 'failure' event</li>
* <li>onTimeout:
* callback for the 'timeout' event</li>
* <li>onProgress:
* callback executed each time a script or css file is loaded</li>
* <li>modules:
* A list of module definitions. See Loader.addModule for the supported module metadata</li>
* </ul>
*/
// @TODO backed out the custom event changes so that the event system
// isn't required in the seed build. If needed, we may want to
// add them back if the event system is detected.
/*
* Executed when the loader successfully completes an insert operation
* This can be subscribed to normally, or a listener can be passed
* as an onSuccess config option.
* @event success
*/
/*
* Executed when the loader fails to complete an insert operation.
* This can be subscribed to normally, or a listener can be passed
* as an onFailure config option.
*
* @event failure
*/
/*
* Executed when a Get operation times out.
* This can be subscribed to normally, or a listener can be passed
* as an onTimeout config option.
*
* @event timeout
*/
// http://yui.yahooapis.com/combo?2.5.2/build/yahoo/yahoo-min.js&2.5.2/build/dom/dom-min.js&2.5.2/build/event/event-min.js&2.5.2/build/autocomplete/autocomplete-min.js"
YUI.add("loader", function(Y) {
var BASE = 'base',
CSS = 'css',
JS = 'js',
CSSRESET = 'cssreset',
CSSFONTS = 'cssfonts',
CSSGRIDS = 'cssgrids',
CSSBASE = 'cssbase',
CSS_AFTER = [CSSRESET, CSSFONTS, CSSGRIDS, 'cssreset-context', 'cssfonts-context', 'cssgrids-context'],
YUI_CSS = ['reset', 'fonts', 'grids', 'base'],
VERSION = '@VERSION@',
ROOT = VERSION + '/build/',
CONTEXT = '-context',
META = {
version: VERSION,
root: ROOT,
base: 'http://yui.yahooapis.com/' + ROOT,
comboBase: 'http://yui.yahooapis.com/combo?',
skin: {
defaultSkin: 'sam',
base: 'assets/skins/',
path: 'skin.css',
after: ['reset', 'fonts', 'grids', 'base']
//rollup: 3
},
modules: {
dom: {
requires: ['event'],
submodules: {
'dom-base': {
requires: ['event']
},
'dom-style': {
requires: ['dom-base']
},
'dom-screen': {
requires: ['dom-base', 'dom-style']
},
selector: {
requires: ['dom-base']
}
}
},
node: {
requires: ['dom'],
submodules: {
'node-base': {
requires: ['dom-base', 'selector']
},
'node-style': {
requires: ['dom-style', 'node-base']
},
'node-screen': {
requires: ['dom-screen', 'node-base']
},
'node-event-simulate': {
requires: ['node-base']
}
}
},
anim: {
requires: [BASE, 'node'],
submodules: {
'anim-base': {
requires: ['base', 'node-style']
},
'anim-color': {
requires: ['anim-base']
},
'anim-curve': {
requires: ['anim-xy']
},
'anim-easing': {
},
'anim-scroll': {
requires: ['anim-base']
},
'anim-xy': {
requires: ['anim-base', 'node-screen']
},
'anim-node-plugin': {
requires: ['node', 'anim-base']
}
}
},
attribute: {
requires: ['event']
},
base: {
requires: ['attribute']
},
compat: {
requires: ['node', 'dump', 'substitute']
},
classnamemanager: { },
console: {
requires: ['widget', 'substitute'],
skinnable: true
},
cookie: { },
// Note: CSS attributes are modified programmatically to reduce metadata size
// cssbase: {
// after: CSS_AFTER
// },
// cssgrids: {
// requires: [CSSFONTS],
// optional: [CSSRESET]
// },
dd:{
submodules: {
'dd-ddm-base': {
requires: ['node', BASE]
},
'dd-ddm':{
requires: ['dd-ddm-base']
},
'dd-ddm-drop':{
requires: ['dd-ddm']
},
'dd-drag':{
requires: ['dd-ddm-base']
},
'dd-drop':{
requires: ['dd-ddm-drop']
},
'dd-proxy':{
requires: ['dd-drag']
},
'dd-constrain':{
requires: ['dd-drag', 'dd-proxy']
},
'dd-plugin':{
requires: ['dd-drag'],
optional: ['dd-constrain', 'dd-proxy']
},
'dd-drop-plugin':{
requires: ['dd-drop']
}
}
},
dump: { },
event: {
requires: ['oop']
},
get: {
requires: ['yui-base']
},
io:{
submodules: {
'io-base': {
requires: ['node']
},
'io-xdr': {
requires: ['io-base']
},
'io-form': {
requires: ['io-base']
},
'io-upload-iframe': {
requires: ['io-base']
},
'io-queue': {
requires: ['io-base']
}
}
},
json: {
submodules: {
'json-parse': {
},
'json-stringify': {
}
}
},
loader: {
requires: ['get']
},
'node-menunav': {
requires: ['node', 'classnamemanager'],
skinnable: true
},
oop: {
requires: ['yui-base']
},
overlay: {
requires: ['widget', 'widget-position', 'widget-position-ext', 'widget-stack', 'widget-stdmod'],
skinnable: true
},
plugin: {
requires: ['base']
},
profiler: { },
queue: {
requires: ['node']
},
slider: {
requires: ['widget', 'dd-constrain'],
skinnable: true
},
stylesheet: { },
substitute: {
optional: ['dump']
},
widget: {
requires: ['base', 'node', 'classnamemanager'],
plugins: {
'widget-position': { },
'widget-position-ext': {
requires: ['widget-position']
},
'widget-stack': {
skinnable: true
},
'widget-stdmod': { }
},
skinnable: true
},
// Since YUI is required for everything else, it should not be specified as
// a dependency.
yui: {
supersedes: ['yui-base', 'get', 'loader']
},
'yui-base': { },
yuitest: {
requires: ['substitute', 'node', 'json']
}
}
};
var _path = function(dir, file, type) {
return dir + '/' + file + '-min.' + (type || CSS);
};
var _cssmeta = function() {
var mods = META.modules;
// modify the meta info for YUI CSS
for (var i=0; i<YUI_CSS.length; i=i+1) {
var bname = YUI_CSS[i],
mname = CSS + bname;
mods[mname] = {
type: CSS,
path: _path(mname, bname)
};
// define -context module
var contextname = mname + CONTEXT;
bname = bname + CONTEXT;
mods[contextname] = {
type: CSS,
path: _path(mname, bname)
};
if (mname == CSSGRIDS) {
mods[mname].requires = [CSSFONTS];
mods[mname].optional = [CSSRESET];
mods[contextname].requires = [CSSFONTS + CONTEXT];
mods[contextname].optional = [CSSRESET + CONTEXT];
} else if (mname == CSSBASE) {
mods[mname].after = CSS_AFTER;
mods[contextname].after = CSS_AFTER;
}
}
}();
Y.Env.meta = META;
var L=Y.Lang, env=Y.Env,
PROV = "_provides", SUPER = "_supersedes",
REQ = "expanded";
Y.Loader = function(o) {
/**
* Internal callback to handle multiple internal insert() calls
* so that css is inserted prior to js
* @property _internalCallback
* @private
*/
this._internalCallback = null;
/**
* Use the YUI environment listener to detect script load. This
* is only switched on for Safari 2.x and below.
* @property _useYahooListener
* @private
*/
this._useYahooListener = false;
/**
* Callback that will be executed when the loader is finished
* with an insert
* @method onSuccess
* @type function
*/
this.onSuccess = null;
/**
* Callback that will be executed if there is a failure
* @method onFailure
* @type function
*/
this.onFailure = null;
/**
* Callback executed each time a script or css file is loaded
* @method onProgress
* @type function
*/
this.onProgress = null;
/**
* Callback that will be executed if a timeout occurs
* @method onTimeout
* @type function
*/
this.onTimeout = null;
/**
* The execution context for all callbacks
* @property context
* @default {YUI} the YUI instance
*/
this.context = Y;
/**
* Data that is passed to all callbacks
* @property data
*/
this.data = null;
/**
* Node reference or id where new nodes should be inserted before
* @property insertBefore
* @type string|HTMLElement
*/
this.insertBefore = null;
/**
* The charset attribute for inserted nodes
* @property charset
* @type string
* @default utf-8
*/
this.charset = null;
/**
* The base directory.
* @property base
* @type string
* @default http://yui.yahooapis.com/[YUI VERSION]/build/
*/
this.base = Y.Env.meta.base;
/**
* Base path for the combo service
* @property comboBase
* @type string
* @default http://yui.yahooapis.com/combo?
*/
this.comboBase = Y.Env.meta.comboBase;
/**
* If configured, YUI JS resources will use the combo
* handler
* @property combine
* @type boolean
* @default true if a base dir isn't in the config
*/
this.combine = (!(BASE in o));
/**
* Ignore modules registered on the YUI global
* @property ignoreRegistered
* @default false
*/
this.ignoreRegistered = false;
/**
* Root path to prepend to module path for the combo
* service
* @property root
* @type string
* @default [YUI VERSION]/build/
*/
this.root = Y.Env.meta.root;
/**
* Timeout value in milliseconds. If set, this value will be used by
* the get utility. the timeout event will fire if
* a timeout occurs.
* @property timeout
* @type int
*/
this.timeout = 0;
/**
* A list of modules that should not be loaded, even if
* they turn up in the dependency tree
* @property ignore
* @type string[]
*/
this.ignore = null;
/**
* A list of modules that should always be loaded, even
* if they have already been inserted into the page.
* @property force
* @type string[]
*/
this.force = null;
/**
* Should we allow rollups
* @property allowRollup
* @type boolean
* @default true
*/
this.allowRollup = true;
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
* <pre>
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
* </pre>
* @property filter
* @type string|{searchExp: string, replaceStr: string}
*/
this.filter = null;
/**
* The list of requested modules
* @property required
* @type {string: boolean}
*/
this.required = {};
/**
* The library metadata
* @property moduleInfo
*/
// this.moduleInfo = Y.merge(Y.Env.meta.moduleInfo);
this.moduleInfo = {};
/**
* Provides the information used to skin the skinnable components.
* The following skin definition would result in 'skin1' and 'skin2'
* being loaded for calendar (if calendar was requested), and
* 'sam' for all other skinnable components:
*
* <code>
* skin: {
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin. ex:
* // http://yui.yahooapis.com/2.3.0/build/assets/skins/sam/
* base: 'assets/skins/',
*
* // The name of the rollup css file for the skin
* path: 'skin.css',
*
* // The number of skinnable components requested that are
* // required before using the rollup file rather than the
* // individual component css files
* rollup: 3,
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* calendar: ['skin1', 'skin2']
* }
* }
* </code>
* @property skin
*/
this.skin = Y.merge(Y.Env.meta.skin);
var defaults = Y.Env.meta.modules;
for (var i in defaults) {
if (defaults.hasOwnProperty(i)) {
this._internal = true;
this.addModule(defaults[i], i);
this._internal = false;
}
}
/**
* List of rollup files found in the library metadata
* @property rollups
*/
this.rollups = null;
/**
* Whether or not to load optional dependencies for
* the requested modules
* @property loadOptional
* @type boolean
* @default false
*/
this.loadOptional = false;
/**
* All of the derived dependencies in sorted order, which
* will be populated when either calculate() or insert()
* is called
* @property sorted
* @type string[]
*/
this.sorted = [];
/**
* Set when beginning to compute the dependency tree.
* Composed of what YUI reports to be loaded combined
* with what has been loaded by the tool
* @propery loaded
* @type {string: boolean}
*/
this.loaded = {};
/**
* A list of modules to attach to the YUI instance when complete.
* If not supplied, the sorted list of dependencies are applied.
* @property attaching
*/
this.attaching = null;
/**
* Flag to indicate the dependency tree needs to be recomputed
* if insert is called again.
* @property dirty
* @type boolean
* @default true
*/
this.dirty = true;
/**
* List of modules inserted by the utility
* @property inserted
* @type {string: boolean}
*/
this.inserted = {};
this.skipped = {};
// Y.on('yui:load', this.loadNext, this);
this._config(o);
};
Y.Loader.prototype = {
FILTERS: {
RAW: {
'searchExp': "-min\\.js",
'replaceStr': ".js"
},
DEBUG: {
'searchExp': "-min\\.js",
'replaceStr': "-debug.js"
}
},
SKIN_PREFIX: "skin-",
_config: function(o) {
// apply config values
if (o) {
for (var i in o) {
if (o.hasOwnProperty(i)) {
var val = o[i];
if (i == 'require') {
this.require(val);
} else if (i == 'modules') {
// add a hash of module definitions
for (var j in val) {
if (val.hasOwnProperty(j)) {
this.addModule(val[j], j);
}
}
} else {
this[i] = val;
}
}
}
}
// fix filter
var f = this.filter;
if (L.isString(f)) {
f = f.toUpperCase();
this.filterName = f;
this.filter = this.FILTERS[f];
}
},
/**
* Returns the skin module name for the specified skin name. If a
* module name is supplied, the returned skin module name is
* specific to the module passed in.
* @method formatSkin
* @param skin {string} the name of the skin
* @param mod {string} optional: the name of a module to skin
* @return {string} the full skin module name
*/
formatSkin: function(skin, mod) {
var s = this.SKIN_PREFIX + skin;
if (mod) {
s = s + "-" + mod;
}
return s;
},
/**
* Reverses <code>formatSkin</code>, providing the skin name and
* module name if the string matches the pattern for skins.
* @method parseSkin
* @param mod {string} the module name to parse
* @return {skin: string, module: string} the parsed skin name
* and module name, or null if the supplied string does not match
* the skin pattern
*/
parseSkin: function(mod) {
if (mod.indexOf(this.SKIN_PREFIX) === 0) {
var a = mod.split("-");
return {skin: a[1], module: a[2]};
}
return null;
},
/**
* Adds the skin def to the module info
* @method _addSkin
* @param skin {string} the name of the skin
* @param mod {string} the name of the module
* @param parent {string} parent module if this is a skin of a
* submodule or plugin
* @return {string} the module name for the skin
* @private
*/
_addSkin: function(skin, mod, parent) {
var name = this.formatSkin(skin), info = this.moduleInfo,
sinf = this.skin, ext = info[mod] && info[mod].ext;
/*
// Add a module definition for the skin rollup css
// Y.log('ext? ' + mod + ": " + ext);
if (!info[name]) {
// Y.log('adding skin ' + name);
this.addModule({
'name': name,
'type': 'css',
'path': sinf.base + skin + '/' + sinf.path,
//'supersedes': '*',
'after': sinf.after,
'rollup': sinf.rollup,
'ext': ext
});
}
*/
// Add a module definition for the module-specific skin css
if (mod) {
name = this.formatSkin(skin, mod);
if (!info[name]) {
var mdef = info[mod], pkg = mdef.pkg || mod;
// Y.log('adding skin ' + name);
this.addModule({
'name': name,
'type': 'css',
'after': sinf.after,
'path': (parent || pkg) + '/' + sinf.base + skin + '/' + mod + '.css',
'ext': ext
});
}
}
return name;
},
/** Add a new module to the component metadata.
* <dl>
* <dt>name:</dt> <dd>required, the component name</dd>
* <dt>type:</dt> <dd>required, the component type (js or css)</dd>
* <dt>path:</dt> <dd>required, the path to the script from "base"</dd>
* <dt>requires:</dt> <dd>array of modules required by this component</dd>
* <dt>optional:</dt> <dd>array of optional modules for this component</dd>
* <dt>supersedes:</dt> <dd>array of the modules this component replaces</dd>
* <dt>after:</dt> <dd>array of modules the components which, if present, should be sorted above this one</dd>
* <dt>rollup:</dt> <dd>the number of superseded modules required for automatic rollup</dd>
* <dt>fullpath:</dt> <dd>If fullpath is specified, this is used instead of the configured base + path</dd>
* <dt>skinnable:</dt> <dd>flag to determine if skin assets should automatically be pulled in</dd>
* <dt>submodules:</dt> <dd>a has of submodules</dd>
* </dl>
* @method addModule
* @param o An object containing the module data
* @param name the module name (optional), required if not in the module data
* @return {boolean} true if the module was added, false if
* the object passed in did not provide all required attributes
*/
addModule: function(o, name) {
name = name || o.name;
o.name = name;
if (!o || !o.name) {
return false;
}
if (!o.type) {
o.type = JS;
}
if (!o.path && !o.fullpath) {
// o.path = name + "/" + name + "-min." + o.type;
o.path = _path(name, name, o.type);
}
o.ext = ('ext' in o) ? o.ext : (this._internal) ? false : true;
o.requires = o.requires || [];
// Y.log('New module ' + name);
this.moduleInfo[name] = o;
// Handle submodule logic
var subs = o.submodules, i;
if (subs) {
var sup = [], l=0;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
var s = subs[i];
s.path = _path(name, i, o.type);
this.addModule(s, i);
sup.push(i);
if (o.skinnable) {
var smod = this._addSkin(this.skin.defaultSkin, i, name);
sup.push(smod.name);
}
l++;
}
}
o.supersedes = sup;
o.rollup = Math.min(l-1, 4);
}
var plugins = o.plugins;
if (plugins) {
for (i in plugins) {
if (plugins.hasOwnProperty(i)) {
var plug = plugins[i];
plug.path = _path(name, i, o.type);
plug.requires = plug.requires || [];
plug.requires.push(name);
this.addModule(plug, i);
if (o.skinnable) {
this._addSkin(this.skin.defaultSkin, i, name);
}
}
}
}
this.dirty = true;
return o;
},
/**
* Add a requirement for one or more module
* @method require
* @param what {string[] | string*} the modules to load
*/
require: function(what) {
var a = (typeof what === "string") ? arguments : what;
this.dirty = true;
Y.mix(this.required, Y.Array.hash(a));
},
/**
* Returns an object containing properties for all modules required
* in order to load the requested module
* @method getRequires
* @param mod The module definition from moduleInfo
*/
getRequires: function(mod) {
if (!mod) {
// Y.log('getRequires, no module');
return [];
}
if (!this.dirty && mod.expanded) {
// Y.log('already expanded');
return mod.expanded;
}
var i, d=[], r=mod.requires, o=mod.optional,
info=this.moduleInfo, m, j, add;
for (i=0; i<r.length; i=i+1) {
// Y.log(mod.name + ' requiring ' + r[i]);
d.push(r[i]);
m = this.getModule(r[i]);
add = this.getRequires(m);
for (j=0;j<add.length;j=j+1) {
d.push(add[j]);
}
}
// get the requirements from superseded modules, if any
r=mod.supersedes;
if (r) {
for (i=0; i<r.length; i=i+1) {
// Y.log(mod.name + ' requiring ' + r[i]);
d.push(r[i]);
m = this.getModule(r[i]);
add = this.getRequires(m);
for (j=0;j<add.length;j=j+1) {
d.push(add[j]);
}
}
}
if (o && this.loadOptional) {
for (i=0; i<o.length; i=i+1) {
d.push(o[i]);
add = this.getRequires(info[o[i]]);
for (j=0;j<add.length;j=j+1) {
d.push(add[j]);
}
}
}
mod.expanded = Y.Object.keys(Y.Array.hash(d));
// Y.log(mod.expanded);
return mod.expanded;
},
/**
* Returns an object literal of the modules the supplied module satisfies
* @method getProvides
* @param name{string} The name of the module
* @param notMe {string} don't add this module name, only include superseded modules
* @return what this module provides
*/
getProvides: function(name, notMe) {
var addMe = !(notMe), ckey = (addMe) ? PROV : SUPER,
m = this.getModule(name), o = {};
if (!m) {
return o;
}
if (m[ckey]) {
// Y.log('cached: ' + name + ' ' + ckey + ' ' + L.dump(this.moduleInfo[name][ckey], 0));
return m[ckey];
}
var s = m.supersedes, done={}, me = this;
// use worker to break cycles
var add = function(mm) {
if (!done[mm]) {
// Y.log(name + ' provides worker trying: ' + mm);
done[mm] = true;
// we always want the return value normal behavior
// (provides) for superseded modules.
Y.mix(o, me.getProvides(mm));
}
// else {
// Y.log(name + ' provides worker skipping done: ' + mm);
// }
};
// calculate superseded modules
if (s) {
for (var i=0; i<s.length; i=i+1) {
add(s[i]);
}
}
// supersedes cache
m[SUPER] = o;
// provides cache
m[PROV] = Y.merge(o);
m[PROV][name] = true;
// Y.log(name + " supersedes " + L.dump(m[SUPER], 0));
// Y.log(name + " provides " + L.dump(m[PROV], 0));
return m[ckey];
},
/**
* Calculates the dependency tree, the result is stored in the sorted
* property
* @method calculate
* @param o optional options object
*/
calculate: function(o) {
if (o || this.dirty) {
this._config(o);
this._setup();
this._explode();
if (this.allowRollup) {
this._rollup();
}
this._reduce();
this._sort();
// Y.log("after calculate: " + this.sorted);
this.dirty = false;
}
},
/**
* Investigates the current YUI configuration on the page. By default,
* modules already detected will not be loaded again unless a force
* option is encountered. Called by calculate()
* @method _setup
* @private
*/
_setup: function() {
var info = this.moduleInfo, name, i, j;
// Create skin modules
for (name in info) {
if (info.hasOwnProperty(name)) {
var m = info[name];
if (m && m.skinnable) {
// Y.log("skinning: " + name);
var o=this.skin.overrides, smod;
if (o && o[name]) {
for (i=0; i<o[name].length; i=i+1) {
smod = this._addSkin(o[name][i], name);
}
} else {
smod = this._addSkin(this.skin.defaultSkin, name);
}
m.requires.push(smod);
}
}
}
var l = Y.merge(this.inserted); // shallow clone
// available modules
if (!this.ignoreRegistered) {
Y.mix(l, YUI.Env.mods);
}
// Y.log("Already loaded stuff: " + L.dump(l, 0));
// add the ignore list to the list of loaded packages
if (this.ignore) {
// OU.appendArray(l, this.ignore);
Y.mix(l, Y.Array.hash(this.ignore));
}
// expand the list to include superseded modules
for (j in l) {
// Y.log("expanding: " + j);
if (l.hasOwnProperty(j)) {
Y.mix(l, this.getProvides(j));
}
}
// remove modules on the force list from the loaded list
if (this.force) {
for (i=0; i<this.force.length; i=i+1) {
if (this.force[i] in l) {
delete l[this.force[i]];
}
}
}
// Y.log("loaded expanded: " + L.dump(l, 0));
this.loaded = l;
},
/**
* Inspects the required modules list looking for additional
* dependencies. Expands the required list to include all
* required modules. Called by calculate()
* @method _explode
* @private
*/
_explode: function() {
var r=this.required, i, mod;
for (i in r) {
if (r.hasOwnProperty(i)) {
mod = this.getModule(i);
// Y.log('exploding ' + i);
var req = this.getRequires(mod);
if (req) {
// Y.log('via explode: ' + req);
Y.mix(r, Y.Array.hash(req));
}
}
}
},
getModule: function(name) {
var m = this.moduleInfo[name];
// create the default module
// if (!m) {
// Y.log('Module does not exist: ' + name + ', creating with defaults');
// m = this.addModule({ext: false}, name);
// }
return m;
},
/**
* Look for rollup packages to determine if all of the modules a
* rollup supersedes are required. If so, include the rollup to
* help reduce the total number of connections required. Called
* by calculate()
* @method _rollup
* @private
*/
_rollup: function() {
var i, j, m, s, rollups={}, r=this.required, roll,
info = this.moduleInfo;
// find and cache rollup modules
if (this.dirty || !this.rollups) {
for (i in info) {
if (info.hasOwnProperty(i)) {
m = this.getModule(i);
// if (m && m.rollup && m.supersedes) {
if (m && m.rollup) {
rollups[i] = m;
}
}
}
this.rollups = rollups;
}
// make as many passes as needed to pick up rollup rollups
for (;;) {
var rolled = false;
// go through the rollup candidates
for (i in rollups) {
if (rollups.hasOwnProperty(i)) {
// there can be only one
if (!r[i] && !this.loaded[i]) {
m =this.getModule(i); s = m.supersedes ||[]; roll=false;
if (!m.rollup) {
continue;
}
var c=0;
// check the threshold
for (j=0;j<s.length;j=j+1) {
// if the superseded module is loaded, we can't load the rollup
// if (this.loaded[s[j]] && (!_Y.dupsAllowed[s[j]])) {
if (this.loaded[s[j]]) {
roll = false;
break;
// increment the counter if this module is required. if we are
// beyond the rollup threshold, we will use the rollup module
} else if (r[s[j]]) {
c++;
roll = (c >= m.rollup);
if (roll) {
// Y.log("over thresh " + c + ", " + L.dump(r));
break;
}
}
}
if (roll) {
// Y.log("rollup: " + i + ", " + L.dump(this, 1));
// add the rollup
r[i] = true;
rolled = true;
// expand the rollup's dependencies
this.getRequires(m);
}
}
}
}
// if we made it here w/o rolling up something, we are done
if (!rolled) {
break;
}
}
},
/**
* Remove superceded modules and loaded modules. Called by
* calculate() after we have the mega list of all dependencies
* @method _reduce
* @private
*/
_reduce: function() {
var i, j, s, m, r=this.required;
for (i in r) {
if (r.hasOwnProperty(i)) {
// remove if already loaded
if (i in this.loaded) {
delete r[i];
// remove anything this module supersedes
} else {
m = this.getModule(i);
s = m && m.supersedes;
if (s) {
for (j=0; j<s.length; j=j+1) {
if (s[j] in r) {
delete r[s[j]];
}
}
}
}
}
}
},
_attach: function() {
// this is the full list of items the YUI needs attached,
// which is needed if some dependencies are already on
// the page without their dependencies.
if (this.attaching) {
Y.log('attaching Y supplied deps: ' + this.attaching, "info", "loader");
Y._attach(this.attaching);
} else {
Y.log('attaching sorted list: ' + this.sorted, "info", "loader");
Y._attach(this.sorted);
}
this._pushEvents();
},
_onSuccess: function() {
this._attach();
var skipped = this.skipped;
for (var i in skipped) {
if (skipped.hasOwnProperty(i)) {
delete this.inserted[i];
}
}
this.skipped = {};
// this.fire('success', {
// data: this.data
// });
var f = this.onSuccess;
if (f) {
f.call(this.context, {
msg: 'success',
data: this.data,
success: true
});
}
},
_onFailure: function(msg) {
this._attach();
// this.fire('failure', {
// msg: 'operation failed: ' + msg,
// data: this.data
// });
var f = this.onFailure;
if (f) {
f.call(this.context, {
msg: 'failure: ' + msg,
data: this.data,
success: false
});
}
},
_onTimeout: function() {
this._attach();
// this.fire('timeout', {
// data: this.data
// });
var f = this.onTimeout;
if (f) {
f.call(this.context, {
msg: 'timeout',
data: this.data,
success: false
});
}
},
/**
* Sorts the dependency tree. The last step of calculate()
* @method _sort
* @private
*/
_sort: function() {
// create an indexed list
var s=Y.Object.keys(this.required), info=this.moduleInfo, loaded=this.loaded,
me = this;
// returns true if b is not loaded, and is required
// directly or by means of modules it supersedes.
var requires = function(aa, bb) {
var mm=info[aa];
if (loaded[bb] || !mm) {
return false;
}
var ii, rr = mm.expanded,
after = mm.after, other=info[bb];
// check if this module requires the other directly
if (rr && Y.Array.indexOf(rr, bb) > -1) {
return true;
}
// check if this module should be sorted after the other
if (after && Y.Array.indexOf(after, bb) > -1) {
return true;
}
// check if this module requires one the other supersedes
var ss=info[bb] && info[bb].supersedes;
if (ss) {
for (ii=0; ii<ss.length; ii=ii+1) {
if (requires(aa, ss[ii])) {
return true;
}
}
}
// external css files should be sorted below yui css
if (mm.ext && mm.type == CSS && !other.ext && other.type == CSS) {
return true;
}
return false;
};
// pointer to the first unsorted item
var p=0;
// keep going until we make a pass without moving anything
for (;;) {
var l=s.length, a, b, j, k, moved=false;
// start the loop after items that are already sorted
for (j=p; j<l; j=j+1) {
// check the next module on the list to see if its
// dependencies have been met
a = s[j];
// check everything below current item and move if we
// find a requirement for the current item
for (k=j+1; k<l; k=k+1) {
if (requires(a, s[k])) {
// extract the dependency so we can move it up
b = s.splice(k, 1);
// insert the dependency above the item that
// requires it
s.splice(j, 0, b[0]);
moved = true;
break;
}
}
// jump out of loop if we moved something
if (moved) {
break;
// this item is sorted, move our pointer and keep going
} else {
p = p + 1;
}
}
// when we make it here and moved is false, we are
// finished sorting
if (!moved) {
break;
}
}
this.sorted = s;
},
/**
* inserts the requested modules and their dependencies.
* <code>type</code> can be "js" or "css". Both script and
* css are inserted if type is not provided.
* @method insert
* @param o optional options object
* @param type {string} the type of dependency to insert
*/
insert: function(o, type) {
Y.log('Insert() ' + (type || ''), "info", "loader");
// build the dependency list
this.calculate(o);
if (!type) {
// Y.log("trying to load css first");
var self = this;
this._internalCallback = function() {
self._internalCallback = null;
self.insert(null, JS);
};
this.insert(null, CSS);
return;
}
// set a flag to indicate the load has started
this._loading = true;
// flag to indicate we are done with the combo service
// and any additional files will need to be loaded
// individually
this._combineComplete = {};
// keep the loadType (js, css or undefined) cached
this.loadType = type;
// start the load
this.loadNext();
},
/**
* Executed every time a module is loaded, and if we are in a load
* cycle, we attempt to load the next script. Public so that it
* is possible to call this if using a method other than
* Y.register to determine when scripts are fully loaded
* @method loadNext
* @param mname {string} optional the name of the module that has
* been loaded (which is usually why it is time to load the next
* one)
*/
loadNext: function(mname) {
// It is possible that this function is executed due to something
// else one the page loading a YUI module. Only react when we
// are actively loading something
if (!this._loading) {
return;
}
var s, len, i, m, url, self=this, type=this.loadType, fn;
// @TODO this will need to handle the two phase insert when
// CSS support is added
if (this.combine && (!this._combineComplete[type])) {
this._combining = [];
s=this.sorted;
len=s.length;
url=this.comboBase;
for (i=0; i<len; i=i+1) {
m = this.getModule(s[i]);
// @TODO we can't combine CSS yet until we deliver files with absolute paths to the assets
// Do not try to combine non-yui JS
if (m && m.type === this.loadType && !m.ext) {
url += this.root + m.path;
if (i < len-1) {
url += '&';
}
this._combining.push(s[i]);
}
}
if (this._combining.length) {
Y.log('Attempting to combine: ' + this._combining, "info", "loader");
var callback=function(o) {
Y.log('Combo complete: ' + o.data, "info", "loader");
this._combineComplete[type] = true;
var c=this._combining, len=c.length, i, m;
for (i=0; i<len; i=i+1) {
this.inserted[c[i]] = true;
}
this.loadNext(o.data);
};
fn =(type === CSS) ? Y.Get.css : Y.Get.script;
// @TODO get rid of the redundant Get code
fn(this._filter(url), {
data: this._loading,
onSuccess: callback,
onFailure: this._onFailure,
onTimeout: this._onTimeout,
insertBefore: this.insertBefore,
charset: this.charset,
timeout: this.timeout,
context: self
});
return;
} else {
this._combineComplete[type] = true;
}
}
if (mname) {
// if the module that was just loaded isn't what we were expecting,
// continue to wait
if (mname !== this._loading) {
return;
}
Y.log("loadNext executing, just loaded " + mname || "", "info", "loader");
// The global handler that is called when each module is loaded
// will pass that module name to this function. Storing this
// data to avoid loading the same module multiple times
this.inserted[mname] = true;
// this.fire('progress', {
// name: mname,
// data: this.data
// });
if (this.onProgress) {
this.onProgress.call(this.context, {
name: mname,
data: this.data
});
}
}
s=this.sorted;
len=s.length;
for (i=0; i<len; i=i+1) {
// this.inserted keeps track of what the loader has loaded.
// move on if this item is done.
if (s[i] in this.inserted) {
// Y.log(s[i] + " alread loaded ");
continue;
}
// Because rollups will cause multiple load notifications
// from Y, loadNext may be called multiple times for
// the same module when loading a rollup. We can safely
// skip the subsequent requests
if (s[i] === this._loading) {
Y.log("still loading " + s[i] + ", waiting", "info", "loader");
return;
}
// log("inserting " + s[i]);
m = this.getModule(s[i]);
if (!m) {
var msg = "Undefined module " + s[i] + " skipped";
Y.log(msg, 'warn', 'loader');
this.inserted[s[i]] = true;
this.skipped[s[i]] = true;
continue;
// this.fire('failure', {
// msg: msg,
// data: this.data
// });
}
// The load type is stored to offer the possibility to load
// the css separately from the script.
if (!type || type === m.type) {
this._loading = s[i];
Y.log("attempting to load " + s[i] + ", " + this.base, "info", "loader");
fn = (m.type === CSS) ? Y.Get.css : Y.Get.script;
var onsuccess=function(o) {
// Y.log('loading next, just loaded' + o.data);
self.loadNext(o.data);
};
url = (m.fullpath) ? this._filter(m.fullpath) : this._url(m.path, s[i]);
self = this;
fn(url, {
data: s[i],
onSuccess: onsuccess,
insertBefore: this.insertBefore,
charset: this.charset,
onFailure: this._onFailure,
onTimeout: this._onTimeout,
timeout: this.timeout,
context: self
});
return;
}
}
// we are finished
this._loading = null;
fn = this._internalCallback;
// internal callback for loading css first
if (fn) {
// Y.log('loader internal');
this._internalCallback = null;
fn.call(this);
// } else if (this.onSuccess) {
} else {
// Y.log('loader complete');
// call Y.use passing this instance. Y will use the sorted
// dependency list.
this._onSuccess();
}
},
/**
* In IE, the onAvailable/onDOMReady events need help when Event is
* loaded dynamically
* @method _pushEvents
* @param {Function} optional function reference
* @private
*/
_pushEvents: function() {
if (Y.Event) {
Y.Event._load();
}
},
/**
* Apply filter defined for this instance to a url/path
* method _filter
* @param u {string} the string to filter
* @return {string} the filtered string
* @private
*/
_filter: function(u) {
Y.log('filter ' + u);
var f = this.filter;
if (u && f) {
var useFilter = true;
if (this.filterName == "DEBUG") {
var exc = this.logExclude,
inc = this.logInclude;
if (inc && !(name in inc)) {
useFilter = false;
} else if (exc && (name in exc)) {
useFilter = false;
}
}
if (useFilter) {
u = u.replace(new RegExp(f.searchExp, 'g'), f.replaceStr);
}
}
return u;
},
/**
* Generates the full url for a module
* method _url
* @param path {string} the path fragment
* @return {string} the full url
* @private
*/
_url: function(path, name) {
return this._filter((this.base || "") + path);
}
};
// Y.augment(Y.Loader, Y.Event.Target);
}, "@VERSION@");
|
ajax/libs/aui/7.5.0-beta-3/aui/js/aui-experimental.js | seogi1004/cdnjs | /*!
* @atlassian/aui - Atlassian User Interface Framework
* @version v7.5.0-beta-3
* @link https://docs.atlassian.com/aui/latest/
* @license SEE LICENSE IN LICENSE.md
* @author Atlassian Pty Ltd.
*/
// src/js/aui/polyfills/placeholder.js
(typeof window === 'undefined' ? global : window).__452d3f8e5d643ab60faf3f564b8276d8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(function () {
if ('placeholder' in document.createElement('input')) {
return;
}
function applyDefaultText(input) {
var value = String(input.value).trim();
if (!value.length) {
input.value = input.getAttribute('placeholder');
(0, _jquery2.default)(input).addClass('aui-placeholder-shown');
}
}
(0, _skate2.default)('placeholder', {
type: _skate2.default.type.ATTRIBUTE,
events: {
blur: applyDefaultText,
focus: function focus(input) {
if (input.value === input.getAttribute('placeholder')) {
input.value = '';
(0, _jquery2.default)(input).removeClass('aui-placeholder-shown');
}
}
},
created: applyDefaultText
});
})();
return module.exports;
}).call(this);
// src/js/aui/banner.js
(typeof window === 'undefined' ? global : window).__e7296db63088f504f190097510a8efb3 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _template = __916a0948cf0486bc703577fb47b747c1;
var _template2 = _interopRequireDefault(_template);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ID_BANNER_CONTAINER = 'header';
function banner(options) {
var $banner = renderBannerElement(options);
pruneBannerContainer();
insertBanner($banner);
return $banner[0];
}
function renderBannerElement(options) {
var html = '<div class="aui-banner aui-banner-{type}" role="banner">' + '{body}' + '</div>';
var $banner = (0, _jquery2.default)((0, _template2.default)(html).fill({
'type': 'error',
'body:html': options.body || ''
}).toString());
return $banner;
}
function pruneBannerContainer() {
var $container = findContainer();
var $allBanners = $container.find('.aui-banner');
$allBanners.get().forEach(function (banner) {
var isBannerAriaHidden = banner.getAttribute('aria-hidden') === 'true';
if (isBannerAriaHidden) {
(0, _jquery2.default)(banner).remove();
}
});
}
function findContainer() {
return (0, _jquery2.default)('#' + ID_BANNER_CONTAINER);
}
function insertBanner($banner) {
var $bannerContainer = findContainer();
if (!$bannerContainer.length) {
throw new Error('You must implement the application header');
}
$banner.prependTo($bannerContainer);
(0, _animation.recomputeStyle)($banner);
$banner.attr('aria-hidden', 'false');
}
(0, _amdify2.default)('aui/banner', banner);
(0, _globalize2.default)('banner', banner);
exports.default = banner;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/button.js
(typeof window === 'undefined' ? global : window).__133851082a1337b5710e5a2aa98258e9 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _isBusy(button) {
return button.hasAttribute('aria-busy') && button.getAttribute('aria-busy') === 'true';
}
function isInputNode(button) {
return button.nodeName === 'INPUT';
}
(0, _skate2.default)('aui-button', {
type: _skate2.default.type.CLASSNAME,
prototype: {
/**
* Adds a spinner to the button and hides the text
*
* @returns {HTMLElement}
*/
busy: function busy() {
if (isInputNode(this) || _isBusy(this)) {
logger.warn('It is not valid to call busy() on an input button.');
return this;
}
(0, _jquery2.default)(this).spin();
this.setAttribute('aria-busy', true);
this.setAttribute('busy', '');
return this;
},
/**
* Removes the spinner and shows the tick on the button
*
* @returns {HTMLElement}
*/
idle: function idle() {
if (isInputNode(this) || !_isBusy(this)) {
logger.warn('It is not valid to call idle() on an input button.');
return this;
}
(0, _jquery2.default)(this).spinStop();
this.removeAttribute('aria-busy');
this.removeAttribute('busy');
return this;
},
/**
* Removes the spinner and shows the tick on the button
*
* @returns {Boolean}
*/
isBusy: function isBusy() {
if (isInputNode(this)) {
logger.warn('It is not valid to call isBusy() on an input button.');
return false;
}
return _isBusy(this);
}
}
});
(0, _amdify2.default)('aui/button');
return module.exports;
}).call(this);
// src/js-vendor/jquery/jquery.tipsy.js
(typeof window === 'undefined' ? global : window).__dbb945ae8033589d400f8c63e7d01524 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [[email protected]]
// released under the MIT license
//
// Modified by Atlassian
// https://github.com/atlassian/tipsy/tree/9095e37c7570c14acf0dbf040bb2466a0e2f23d4
(function($) {
function maybeCall(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
};
function isElementInDOM(ele) {
while (ele = ele.parentNode) {
if (ele == document) return true;
}
return false;
};
var tipsyIDcounter = 0;
function tipsyID() {
var tipsyID = tipsyIDcounter++;
return "tipsyuid" + tipsyID;
};
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = true;
this.fixTitle();
};
Tipsy.prototype = {
show: function() {
// if element is not in the DOM then don't show the Tipsy and return early
if (!isElementInDOM(this.$element[0])) {
return;
}
var title = this.getTitle();
if (title && this.enabled) {
var $tip = this.tip();
$tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
$tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
$tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
var that = this;
function tipOver() {
that.hoverTooltip = true;
}
function tipOut() {
if (that.hoverState == 'in') return; // If field is still focused.
that.hoverTooltip = false;
if (that.options.trigger != 'manual') {
var eventOut = that.options.trigger == 'hover' ? 'mouseleave.tipsy' : 'blur.tipsy';
that.$element.trigger(eventOut);
}
}
if (this.options.hoverable) {
$tip.hover(tipOver, tipOut);
}
if (this.options.className) {
$tip.addClass(maybeCall(this.options.className, this.$element[0]));
}
var pos = $.extend({}, this.$element.offset(), {
width: this.$element[0].getBoundingClientRect().width,
height: this.$element[0].getBoundingClientRect().height
});
var tipCss = {};
var actualWidth = $tip[0].offsetWidth,
actualHeight = $tip[0].offsetHeight;
var gravity = maybeCall(this.options.gravity, this.$element[0]);
if (gravity.length === 2) {
if (gravity.charAt(1) === 'w') {
tipCss.left = pos.left + pos.width / 2 - 15;
} else {
tipCss.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
switch (gravity.charAt(0)) {
case 'n':
// left could already be set if gravity is 'nw' or 'ne'
if (typeof tipCss.left === 'undefined') {
tipCss.left = pos.left + pos.width / 2 - actualWidth / 2;
}
tipCss.top = pos.top + pos.height + this.options.offset;
break;
case 's':
// left could already be set if gravity is 'sw' or 'se'
if (typeof tipCss.left === 'undefined') {
tipCss.left = pos.left + pos.width / 2 - actualWidth / 2;
// We need to apply the left positioning and then recalculate the tooltip height
// If the tooltip is positioned close to the right edge of the window, it could cause
// the tooltip text to overflow and change height.
$tip.css(tipCss);
actualHeight = $tip[0].offsetHeight;
}
tipCss.top = pos.top - actualHeight - this.options.offset;
break;
case 'e':
tipCss.left = pos.left - actualWidth - this.options.offset;
tipCss.top = pos.top + pos.height / 2 - actualHeight / 2;
break;
case 'w':
tipCss.left = pos.left + pos.width + this.options.offset;
tipCss.top = pos.top + pos.height / 2 - actualHeight / 2;
break;
}
$tip.css(tipCss).addClass('tipsy-' + gravity);
$tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
if (this.options.fade) {
$tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
} else {
$tip.css({visibility: 'visible', opacity: this.options.opacity});
}
if (this.options.aria) {
var $tipID = tipsyID();
$tip.attr("id", $tipID);
this.$element.attr("aria-describedby", $tipID);
}
}
},
destroy: function(){
this.$element.removeData('tipsy');
this.unbindHandlers();
this.hide();
},
unbindHandlers: function() {
if(this.options.live){
$(this.$element.context).off('.tipsy');
} else {
this.$element.unbind('.tipsy');
}
},
hide: function() {
if (this.options.fade) {
this.tip().stop().fadeOut(function() { $(this).remove(); });
} else {
this.tip().remove();
}
if (this.options.aria) {
this.$element.removeAttr("aria-describedby");
}
},
fixTitle: function() {
var $e = this.$element;
if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
$e.attr('original-title', $e.attr('title') || '').removeAttr('title');
}
},
getTitle: function() {
var title, $e = this.$element, o = this.options;
this.fixTitle();
var title, o = this.options;
if (typeof o.title == 'string') {
title = $e.attr(o.title == 'title' ? 'original-title' : o.title);
} else if (typeof o.title == 'function') {
title = o.title.call($e[0]);
}
title = ('' + title).replace(/(^\s*|\s*$)/, "");
return title || o.fallback;
},
tip: function() {
if (!this.$tip) {
this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>').attr("role","tooltip");
this.$tip.data('tipsy-pointee', this.$element[0]);
}
return this.$tip;
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide();
this.$element = null;
this.options = null;
}
},
enable: function() { this.enabled = true; },
disable: function() { this.enabled = false; },
toggleEnabled: function() { this.enabled = !this.enabled; }
};
$.fn.tipsy = function(options) {
if (options === true) {
return this.data('tipsy');
} else if (typeof options == 'string') {
var tipsy = this.data('tipsy');
if (tipsy) tipsy[options]();
return this;
}
options = $.extend({}, $.fn.tipsy.defaults, options);
if (options.hoverable) {
options.delayOut = options.delayOut || 20;
}
function get(ele) {
var tipsy = $.data(ele, 'tipsy');
if (!tipsy) {
tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
$.data(ele, 'tipsy', tipsy);
}
return tipsy;
}
function enter() {
var tipsy = get(this);
tipsy.hoverState = 'in';
if (options.delayIn == 0) {
tipsy.show();
} else {
tipsy.fixTitle();
setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
}
};
function leave() {
var tipsy = get(this);
tipsy.hoverState = 'out';
if (options.delayOut == 0) {
tipsy.hide();
} else {
setTimeout(function() { if (tipsy.hoverState == 'out' && !tipsy.hoverTooltip) tipsy.hide(); }, options.delayOut);
}
};
if (!options.live) this.each(function() { get(this); });
if (options.trigger != 'manual') {
var eventIn = options.trigger == 'hover' ? 'mouseenter.tipsy focus.tipsy' : 'focus.tipsy',
eventOut = options.trigger == 'hover' ? 'mouseleave.tipsy blur.tipsy' : 'blur.tipsy';
if (options.live) {
$(this.context).on(eventIn, this.selector, enter).on(eventOut, this.selector, leave);
} else {
this.bind(eventIn, enter).bind(eventOut, leave);
}
}
return this;
};
$.fn.tipsy.defaults = {
aria: false,
className: null,
delayIn: 0,
delayOut: 0,
fade: false,
fallback: '',
gravity: 'n',
html: false,
live: false,
hoverable: false,
offset: 0,
opacity: 0.8,
title: 'title',
trigger: 'hover'
};
$.fn.tipsy.revalidate = function() {
$('.tipsy').each(function() {
var pointee = $.data(this, 'tipsy-pointee');
if (!pointee || !isElementInDOM(pointee)) {
$(this).remove();
}
});
};
// Overwrite this method to provide options on a per-element basis.
// For example, you could store the gravity in a 'tipsy-gravity' attribute:
// return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
// (remember - do not modify 'options' in place!)
$.fn.tipsy.elementOptions = function(ele, options) {
return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
};
$.fn.tipsy.autoNS = function() {
return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
};
$.fn.tipsy.autoWE = function() {
return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
};
/**
* yields a closure of the supplied parameters, producing a function that takes
* no arguments and is suitable for use as an autogravity function like so:
*
* @param margin (int) - distance from the viewable region edge that an
* element should be before setting its tooltip's gravity to be away
* from that edge.
* @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
* if there are no viewable region edges effecting the tooltip's
* gravity. It will try to vary from this minimally, for example,
* if 'sw' is preferred and an element is near the right viewable
* region edge, but not the top edge, it will set the gravity for
* that element's tooltip to be 'se', preserving the southern
* component.
*/
$.fn.tipsy.autoBounds = function(margin, prefer) {
return function() {
var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
boundTop = $(document).scrollTop() + margin,
boundLeft = $(document).scrollLeft() + margin,
$this = $(this);
if ($this.offset().top < boundTop) dir.ns = 'n';
if ($this.offset().left < boundLeft) dir.ew = 'w';
if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
return dir.ns + (dir.ew ? dir.ew : '');
}
};
})(jQuery);
return module.exports;
}).call(this);
// src/js/aui/tooltip.js
(typeof window === 'undefined' ? global : window).__6999efc8461cc8bcf32a985dbca81aa1 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function handleStringOption($self, options, stringOption) {
// Pass string values straight to tipsy
$self.tipsy(stringOption);
if (stringOption === 'destroy') {
if (options.live) {
(0, _jquery2.default)($self.context).off('.tipsy', $self.selector);
} else {
$self.unbind('.tipsy');
}
}
return $self;
}
function bindTooltip($self, options) {
$self.tipsy(options);
var hideOnClick = options && options.hideOnClick && (options.trigger === 'hover' || !options.trigger && $self.tipsy.defaults.trigger === 'hover');
if (hideOnClick) {
var onClick = function onClick() {
(0, _jquery2.default)(this).tipsy('hide');
};
if (options.live) {
(0, _jquery2.default)($self.context).on('click.tipsy', $self.selector, onClick);
} else {
$self.bind('click.tipsy', onClick);
}
}
return $self;
}
_jquery2.default.fn.tooltip = function (options) {
var allOptions = _jquery2.default.extend({}, _jquery2.default.fn.tooltip.defaults, options);
// Handle live option
if (allOptions.live) {
if (typeof options === 'string') {
handleStringOption(this, allOptions, options);
} else {
bindTooltip(this, allOptions);
}
return this;
}
// If not live, bind each object in the collection
return this.each(function () {
var $this = (0, _jquery2.default)(this);
if (typeof options === 'string') {
handleStringOption($this, allOptions, options);
} else {
bindTooltip($this, allOptions);
}
return $this;
});
};
_jquery2.default.fn.tooltip.defaults = {
opacity: 1.0,
offset: 1,
delayIn: 500,
hoverable: true,
hideOnClick: true,
aria: true
};
return module.exports;
}).call(this);
// src/js/aui/checkbox-multiselect.js
(typeof window === 'undefined' ? global : window).__bf3c38e4a0e7481b849a297fccf30258 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__66a09fadeaffb2f1300bfa557f5294cd;
__6999efc8461cc8bcf32a985dbca81aa1;
__be3e01199078cdf5ded88dda6a8fbec9;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var templates = {
dropdown: function dropdown(items) {
function createSection() {
return (0, _jquery2.default)('<div class="aui-dropdown2-section">');
}
// clear items section
var $clearItemsSection = createSection();
(0, _jquery2.default)('<button />').attr({
type: 'button',
'data-aui-checkbox-multiselect-clear': '',
class: 'aui-button aui-button-link'
}).text(AJS.I18n.getText('aui.checkboxmultiselect.clear.selected')).appendTo($clearItemsSection);
// list of items
var $section = createSection();
var $itemList = (0, _jquery2.default)('<ul />').appendTo($section);
_jquery2.default.each(items, function (idx, item) {
var $li = (0, _jquery2.default)('<li />').attr({
class: item.styleClass || ''
}).appendTo($itemList);
var $a = (0, _jquery2.default)('<a />').text(item.label).attr('data-value', item.value).addClass('aui-dropdown2-checkbox aui-dropdown2-interactive').appendTo($li);
if (item.icon) {
(0, _jquery2.default)('<span />').addClass('aui-icon').css('backgroundImage', 'url(' + item.icon + ')")').appendTo($a);
}
if (item.selected) {
$a.addClass('aui-dropdown2-checked');
}
});
return (0, _jquery2.default)('<div />').append($clearItemsSection).append($section).html();
},
furniture: function furniture(name, optionsHtml) {
var dropdownId = name + '-dropdown';
var $select = (0, _jquery2.default)('<select />').attr({
name: name,
multiple: 'multiple'
}).html(optionsHtml);
var $dropdown = (0, _jquery2.default)('<div>').attr({
id: dropdownId,
class: 'aui-checkbox-multiselect-dropdown aui-dropdown2 aui-style-default'
});
var $button = (0, _jquery2.default)('<button />').attr({
class: 'aui-checkbox-multiselect-btn aui-button aui-dropdown2-trigger',
type: 'button',
'aria-owns': dropdownId,
'aria-haspopup': true
});
return (0, _jquery2.default)('<div />').append($select).append($button).append($dropdown).html();
}
};
/**
* Handles when user clicks an item in the dropdown list. Either selects or unselects the corresponding
* option in the <select>.
* @private
*/
function handleDropdownSelection(e) {
var $a = (0, _jquery2.default)(e.target);
var value = $a.attr('data-value');
updateOption(this, value, $a.hasClass('aui-dropdown2-checked'));
}
/**
* Selects or unselects the <option> corresponding the given value.
* @private
* @param component - Checkbox MultiSelect web component
* @param value - value of option to update
* @param {Boolean} selected - select or unselect it.
*/
function updateOption(component, value, selected) {
var $toUpdate = component.$select.find('option').filter(function () {
var $this = (0, _jquery2.default)(this);
return $this.attr('value') === value && $this.prop('selected') !== selected;
});
if ($toUpdate.length) {
$toUpdate.prop('selected', selected);
component.$select.trigger('change');
}
}
/**
* Enables 'clear all' button if there are any selected <option>s, otherwise disables it.
* @private
*/
function updateClearAll(component) {
component.$dropdown.find('[data-aui-checkbox-multiselect-clear]').prop('disabled', function () {
return getSelectedDescriptors(component).length < 1;
});
}
/**
* Gets button title used for tipsy. Is blank when dropdown is open so we don't get tipsy hanging over options.
* @private
* @param component
* @returns {string}
*/
function getButtonTitle(component) {
return component.$dropdown.is('[aria-hidden=false]') ? '' : getSelectedLabels(component).join(', ');
}
/**
* Converts a jQuery collection of <option> elements into an object that describes them.
* @param {jQuery} $options
* @returns {Array<Object>}
* @private
*/
function mapOptionDescriptors($options) {
return $options.map(function () {
var $option = (0, _jquery2.default)(this);
return {
value: $option.val(),
label: $option.text(),
icon: $option.data('icon'),
styleClass: $option.data('styleClass'),
title: $option.attr('title'),
disabled: $option.attr('disabled'),
selected: $option.prop('selected')
};
});
}
/**
* Gets label for when nothing is selected
* @returns {string}
* @private
*/
function getImplicitAllLabel(component) {
return (0, _jquery2.default)(component).data('allLabel') || 'All';
}
/**
* Renders dropdown with list of items representing the selected or unselect state of the <option>s in <select>
* @private
*/
function renderDropdown(component) {
component.$dropdown.html(templates.dropdown(getDescriptors(component)));
updateClearAll(component);
}
/**
* Renders button with the selected <option>'s innerText in a comma seperated list. If nothing is selected 'All'
* is displayed.
* @private
*/
function renderButton(component) {
var selectedLabels = getSelectedLabels(component);
var label = isImplicitAll(component) ? getImplicitAllLabel(component) : selectedLabels.join(', ');
component.$btn.text(label);
}
/**
* Gets descriptor for selected options, the descriptor is an object that contains meta information about
* the option, such as value, label, icon etc.
* @private
* @returns Array<Object>
*/
function getDescriptors(component) {
return mapOptionDescriptors(component.getOptions());
}
/**
* Gets descriptor for selected options, the descriptor is an object that contains meta information about
* the option, such as value, label, icon etc.
* @private
* @returns Array<Object>
*/
function getSelectedDescriptors(component) {
return mapOptionDescriptors(component.getSelectedOptions());
}
/**
* Gets the innerText of the selected options
* @private
* @returns Array<String>
*/
function getSelectedLabels(component) {
return _jquery2.default.map(getSelectedDescriptors(component), function (descriptor) {
return descriptor.label;
});
}
/**
* If nothing is selected, we take this to mean that everything is selected.
* @returns Boolean
*/
function isImplicitAll(component) {
return getSelectedDescriptors(component).length === 0;
}
var checkboxMultiselect = (0, _skate2.default)('aui-checkbox-multiselect', {
attached: function attached(component) {
// This used to be template logic, however, it breaks tests if we
// keep it there after starting to use native custom elements. This
// should be refactored.
//
// Ideally we should be templating the element within the "template"
// hook which will ensure it's templated prior to calling the
// "attached" callback.
var name = component.getAttribute('name') || (0, _uniqueId2.default)('aui-checkbox-multiselect-');
component.innerHTML = templates.furniture(name, component.innerHTML);
component.$select = (0, _jquery2.default)('select', component).change(function () {
renderButton(component);
updateClearAll(component);
});
component.$dropdown = (0, _jquery2.default)('.aui-checkbox-multiselect-dropdown', component).on('aui-dropdown2-item-check', handleDropdownSelection.bind(component)).on('aui-dropdown2-item-uncheck', handleDropdownSelection.bind(component)).on('click', 'button[data-aui-checkbox-multiselect-clear]', component.deselectAllOptions.bind(component));
component.$btn = (0, _jquery2.default)('.aui-checkbox-multiselect-btn', component).tooltip({
title: function title() {
return getButtonTitle(component);
}
});
renderButton(component);
renderDropdown(component);
},
prototype: {
/**
* Gets all options regardless of selected or unselected
* @returns {jQuery}
*/
getOptions: function getOptions() {
return this.$select.find('option');
},
/**
* Gets all selected options
* @returns {jQuery}
*/
getSelectedOptions: function getSelectedOptions() {
return this.$select.find('option:selected');
},
/**
* Sets <option> elements matching given value to selected
*/
selectOption: function selectOption(value) {
updateOption(this, value, true);
},
/**
* Sets <option> elements matching given value to unselected
*/
unselectOption: function unselectOption(value) {
updateOption(this, value, false);
},
/**
* Gets value of <select>
* @returns Array
*/
getValue: function getValue() {
return this.$select.val();
},
/**
* Unchecks all items in the dropdown and in the <select>
*/
deselectAllOptions: function deselectAllOptions() {
this.$select.val([]).trigger('change');
this.$dropdown.find('.aui-dropdown2-checked,.checked').removeClass('aui-dropdown2-checked checked');
},
/**
* Adds an option to the <select>
* @param descriptor
*/
addOption: function addOption(descriptor) {
(0, _jquery2.default)('<option />').attr({
value: descriptor.value,
icon: descriptor.icon,
disabled: descriptor.disabled,
selected: descriptor.selected,
title: descriptor.title
}).text(descriptor.label).appendTo(this.$select);
renderButton(this);
renderDropdown(this);
},
/**
* Removes options matching value from <select>
* @param value
*/
removeOption: function removeOption(value) {
this.$select.find("[value='" + value + "']").remove();
renderButton(this);
renderDropdown(this);
}
}
});
(0, _amdify2.default)('aui/checkbox-multiselect');
exports.default = checkboxMultiselect;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/dialog2.js
(typeof window === 'undefined' ? global : window).__3ac567a4ab4b829d5c6e6c81df33cbe8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _layer = __06224e18e744dc8a44794ab29f247385;
var _layer2 = _interopRequireDefault(_layer);
var _widget = __2d1b5481970dd1547e294d829464e03f;
var _widget2 = _interopRequireDefault(_widget);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaults = {
'aui-focus': 'false', // do not focus by default as it's overridden below
'aui-blanketed': 'true'
};
function applyDefaults($el) {
_jquery2.default.each(defaults, function (key, value) {
var dataKey = 'data-' + key;
if (!$el[0].hasAttribute(dataKey)) {
$el.attr(dataKey, value);
}
});
}
function Dialog2(selector) {
if (selector) {
this.$el = (0, _jquery2.default)(selector);
} else {
this.$el = (0, _jquery2.default)(aui.dialog.dialog2({}));
}
applyDefaults(this.$el);
}
Dialog2.prototype.on = function (event, fn) {
(0, _layer2.default)(this.$el).on(event, fn);
return this;
};
Dialog2.prototype.off = function (event, fn) {
(0, _layer2.default)(this.$el).off(event, fn);
return this;
};
Dialog2.prototype.show = function () {
(0, _layer2.default)(this.$el).show();
return this;
};
Dialog2.prototype.hide = function () {
(0, _layer2.default)(this.$el).hide();
return this;
};
Dialog2.prototype.remove = function () {
(0, _layer2.default)(this.$el).remove();
return this;
};
Dialog2.prototype.isVisible = function () {
return (0, _layer2.default)(this.$el).isVisible();
};
var dialog2Widget = (0, _widget2.default)('dialog2', Dialog2);
dialog2Widget.on = function (eventName, fn) {
_layer2.default.on(eventName, '.aui-dialog2', fn);
return this;
};
dialog2Widget.off = function (eventName, fn) {
_layer2.default.off(eventName, '.aui-dialog2', fn);
return this;
};
/* Live events */
(0, _jquery2.default)(document).on('click', '.aui-dialog2-header-close', function (e) {
e.preventDefault();
dialog2Widget((0, _jquery2.default)(this).closest('.aui-dialog2')).hide();
});
dialog2Widget.on('show', function (e, $el) {
var selectors = ['.aui-dialog2-content', '.aui-dialog2-footer', '.aui-dialog2-header'];
var $selected;
selectors.some(function (selector) {
$selected = $el.find(selector + ' :aui-tabbable');
return $selected.length;
});
$selected && $selected.first().focus();
});
dialog2Widget.on('hide', function (e, $el) {
var layer = (0, _layer2.default)($el);
if ($el.data('aui-remove-on-hide')) {
layer.remove();
}
});
(0, _amdify2.default)('aui/dialog2', dialog2Widget);
(0, _globalize2.default)('dialog2', dialog2Widget);
exports.default = dialog2Widget;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/expander.js
(typeof window === 'undefined' ? global : window).__f165ad68f415362651d0d7f733fcdcea = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var $document = (0, _jquery2.default)(document);
//convenience function because this needs to be run for all the events.
var getExpanderProperties = function getExpanderProperties(event) {
var properties = {};
properties.$trigger = (0, _jquery2.default)(event.currentTarget);
properties.$content = $document.find('#' + properties.$trigger.attr('aria-controls'));
properties.triggerIsParent = properties.$content.parent().filter(properties.$trigger).length !== 0;
properties.$shortContent = properties.triggerIsParent ? properties.$trigger.find('.aui-expander-short-content') : null;
properties.height = properties.$content.css('min-height');
properties.isCollapsible = properties.$trigger.data('collapsible') !== false;
properties.replaceText = properties.$trigger.attr('data-replace-text'); //can't use .data here because it doesn't update after the first call
properties.replaceSelector = properties.$trigger.data('replace-selector');
return properties;
};
var replaceText = function replaceText(properties) {
if (properties.replaceText) {
var $replaceElement = properties.replaceSelector ? properties.$trigger.find(properties.replaceSelector) : properties.$trigger;
properties.$trigger.attr('data-replace-text', $replaceElement.text());
$replaceElement.text(properties.replaceText);
}
};
//events that the expander listens to
var EXPANDER_EVENTS = {
'aui-expander-invoke': function auiExpanderInvoke(event) {
var $trigger = (0, _jquery2.default)(event.currentTarget);
var $content = $document.find('#' + $trigger.attr('aria-controls'));
var isCollapsible = $trigger.data('collapsible') !== false;
//determine if content should be expanded or collapsed
if ($content.attr('aria-expanded') === 'true' && isCollapsible) {
$trigger.trigger('aui-expander-collapse');
} else {
$trigger.trigger('aui-expander-expand');
}
},
'aui-expander-expand': function auiExpanderExpand(event) {
var properties = getExpanderProperties(event);
// If the expander is already expanded, do nothing.
if (properties.$content.attr('aria-expanded') === 'true') {
return;
}
properties.$content.attr('aria-expanded', 'true');
properties.$trigger.attr('aria-expanded', 'true');
if (properties.$content.outerHeight() > 0) {
properties.$content.attr('aria-hidden', 'false');
}
//handle replace text
replaceText(properties);
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.hide();
}
properties.$trigger.trigger('aui-expander-expanded');
},
'aui-expander-collapse': function auiExpanderCollapse(event) {
var properties = getExpanderProperties(event);
// If the expander is already collapsed, do nothing.
if (properties.$content.attr('aria-expanded') !== 'true') {
return;
}
//handle replace text
replaceText(properties);
//collapse the expander
properties.$content.attr('aria-expanded', 'false');
properties.$trigger.attr('aria-expanded', 'false');
//if the trigger is the parent also hide the short-content (default)
if (properties.triggerIsParent) {
properties.$shortContent.show();
}
//handle the height option
if (properties.$content.outerHeight() === 0) {
properties.$content.attr('aria-hidden', 'true');
}
properties.$trigger.trigger('aui-expander-collapsed');
},
'click.aui-expander': function clickAuiExpander(event) {
var $target = (0, _jquery2.default)(event.currentTarget);
$target.trigger('aui-expander-invoke', event.currentTarget);
}
};
//delegate events to the triggers on the page
$document.on(EXPANDER_EVENTS, '.aui-expander-trigger');
return module.exports;
}).call(this);
// src/js/aui/flag.js
(typeof window === 'undefined' ? global : window).__7c68b94bd1e7e5a2f72d197f55d1d459 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _template = __916a0948cf0486bc703577fb47b747c1;
var _template2 = _interopRequireDefault(_template);
var _customEvent = __16bf5f1d761138a726209288b7afb338;
var _customEvent2 = _interopRequireDefault(_customEvent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var AUTO_CLOSE_TIME = 5000;
var ID_FLAG_CONTAINER = 'aui-flag-container';
var defaultOptions = {
body: '',
close: 'manual',
title: '',
type: 'info'
};
function flag(options) {
options = _jquery2.default.extend({}, defaultOptions, options);
var $flag = renderFlagElement(options);
extendFlagElement($flag);
if (options.close === 'auto') {
makeCloseable($flag);
makeAutoClosable($flag);
} else if (options.close === 'manual') {
makeCloseable($flag);
}
pruneFlagContainer();
return insertFlag($flag);
}
function extendFlagElement($flag) {
var flag = $flag[0];
flag.close = function () {
closeFlag($flag);
};
}
function renderFlagElement(options) {
var html = '<div class="aui-flag">' + '<div class="aui-message aui-message-{type} {type} {closeable} shadowed">' + '<p class="title">' + '<strong>{title}</strong>' + '</p>' + '{body}<!-- .aui-message -->' + '</div>' + '</div>';
var rendered = (0, _template2.default)(html).fill({
'body:html': options.body || '',
closeable: options.close === 'never' ? '' : 'closeable',
title: options.title || '',
type: options.type
}).toString();
return (0, _jquery2.default)(rendered);
}
function makeCloseable($flag) {
var $icon = (0, _jquery2.default)('<span class="aui-icon icon-close" role="button" tabindex="0"></span>');
$icon.click(function () {
closeFlag($flag);
});
$icon.keypress(function (e) {
if (e.which === _keyCode2.default.ENTER || e.which === _keyCode2.default.SPACE) {
closeFlag($flag);
e.preventDefault();
}
});
return $flag.find('.aui-message').append($icon)[0];
}
function makeAutoClosable($flag) {
$flag.find('.aui-message').addClass('aui-will-close');
setTimeout(function () {
$flag[0].close();
}, AUTO_CLOSE_TIME);
}
function closeFlag($flagToClose) {
var flag = $flagToClose.get(0);
flag.setAttribute('aria-hidden', 'true');
flag.dispatchEvent(new _customEvent2.default('aui-flag-close', { bubbles: true }));
return flag;
}
function pruneFlagContainer() {
var $container = findContainer();
var $allFlags = $container.find('.aui-flag');
$allFlags.get().forEach(function (flag) {
var isFlagAriaHidden = flag.getAttribute('aria-hidden') === 'true';
if (isFlagAriaHidden) {
(0, _jquery2.default)(flag).remove();
}
});
}
function findContainer() {
return (0, _jquery2.default)('#' + ID_FLAG_CONTAINER);
}
function insertFlag($flag) {
var $flagContainer = findContainer();
if (!$flagContainer.length) {
$flagContainer = (0, _jquery2.default)('<div id="' + ID_FLAG_CONTAINER + '"></div>');
(0, _jquery2.default)('body').prepend($flagContainer);
}
$flag.appendTo($flagContainer);
(0, _animation.recomputeStyle)($flag);
return $flag.attr('aria-hidden', 'false')[0];
}
(0, _amdify2.default)('aui/flag', flag);
(0, _globalize2.default)('flag', flag);
exports.default = flag;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/form-notification.js
(typeof window === 'undefined' ? global : window).__223d4ffbfb11c7b1196e30d8f0783cb8 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NOTIFICATION_NAMESPACE = 'aui-form-notification';
var CLASS_NOTIFICATION_INITIALISED = '_aui-form-notification-initialised';
var CLASS_NOTIFICATION_ICON = 'aui-icon-notification';
var CLASS_TOOLTIP = NOTIFICATION_NAMESPACE + '-tooltip';
var CLASS_TOOLTIP_ERROR = CLASS_TOOLTIP + '-error';
var CLASS_TOOLTIP_INFO = CLASS_TOOLTIP + '-info';
var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-';
var ATTRIBUTE_NOTIFICATION_WAIT = ATTRIBUTE_NOTIFICATION_PREFIX + 'wait';
var ATTRIBUTE_NOTIFICATION_INFO = ATTRIBUTE_NOTIFICATION_PREFIX + 'info';
var ATTRIBUTE_NOTIFICATION_ERROR = ATTRIBUTE_NOTIFICATION_PREFIX + 'error';
var ATTRIBUTE_NOTIFICATION_SUCCESS = ATTRIBUTE_NOTIFICATION_PREFIX + 'success';
var ATTRIBUTE_TOOLTIP_POSITION = NOTIFICATION_NAMESPACE + '-position';
var NOTIFICATION_PRIORITY = [ATTRIBUTE_NOTIFICATION_ERROR, ATTRIBUTE_NOTIFICATION_SUCCESS, ATTRIBUTE_NOTIFICATION_WAIT, ATTRIBUTE_NOTIFICATION_INFO];
var notificationFields = [];
/* --- Tipsy configuration --- */
var TIPSY_OPACITY = 1;
var TIPSY_OFFSET_INSIDE_FIELD = 9; //offset in px from the icon to the start of the tipsy
var TIPSY_OFFSET_OUTSIDE_FIELD = 3;
function initialiseNotification($field) {
if (!isFieldInitialised($field)) {
prepareFieldMarkup($field);
initialiseTooltip($field);
bindFieldEvents($field);
synchroniseNotificationDisplay($field);
}
notificationFields.push($field);
}
function isFieldInitialised($field) {
return $field.hasClass(CLASS_NOTIFICATION_INITIALISED);
}
function constructFieldIcon() {
return (0, _jquery2.default)('<span class="aui-icon aui-icon-small ' + CLASS_NOTIFICATION_ICON + '"/>');
}
function prepareFieldMarkup($field) {
$field.addClass(CLASS_NOTIFICATION_INITIALISED);
appendIconToField($field);
}
function appendIconToField($field) {
var $icon = constructFieldIcon();
$field.after($icon);
}
function initialiseTooltip($field) {
getTooltipAnchor($field).tipsy({
gravity: getTipsyGravity($field),
title: function title() {
return getNotificationMessage($field);
},
trigger: 'manual',
offset: canContainIcon($field) ? TIPSY_OFFSET_INSIDE_FIELD : TIPSY_OFFSET_OUTSIDE_FIELD,
opacity: TIPSY_OPACITY,
className: function className() {
return 'aui-form-notification-tooltip ' + getNotificationClass($field);
},
html: true
});
}
// A list of HTML5 input types that don't typically get augmented by the browser, so are safe to put icons inside of.
var unadornedInputFields = ['text', 'url', 'email', 'tel', 'password'];
function canContainIcon($field) {
return unadornedInputFields.indexOf($field.attr('type')) !== -1;
}
function getNotificationMessage($field) {
var notificationType = getFieldNotificationType($field);
var message = notificationType ? $field.attr(notificationType) : '';
return formatMessage(message);
}
function formatMessage(message) {
if (message === '') {
return message;
}
var messageArray = jsonToArray(message);
if (messageArray.length === 1) {
return messageArray[0];
} else {
return '<ul><li>' + messageArray.join('</li><li>') + '</li></ul>';
}
}
function jsonToArray(jsonOrString) {
var jsonArray;
try {
jsonArray = JSON.parse(jsonOrString);
} catch (exception) {
jsonArray = [jsonOrString];
}
return jsonArray;
}
function getNotificationClass($field) {
var notificationType = getFieldNotificationType($field);
if (notificationType === ATTRIBUTE_NOTIFICATION_ERROR) {
return CLASS_TOOLTIP_ERROR;
} else if (notificationType === ATTRIBUTE_NOTIFICATION_INFO) {
return CLASS_TOOLTIP_INFO;
}
}
function getFieldNotificationType($field) {
var fieldNotificationType;
NOTIFICATION_PRIORITY.some(function (prioritisedNotification) {
if ($field.is('[' + prioritisedNotification + ']')) {
fieldNotificationType = prioritisedNotification;
return true;
}
});
return fieldNotificationType;
}
function bindFieldEvents($field) {
if (focusTogglesTooltip($field)) {
bindFieldTabEvents($field);
}
}
function focusTogglesTooltip($field) {
return $field.is(':aui-focusable');
}
function fieldHasTooltip($field) {
return getNotificationMessage($field) !== '';
}
function showTooltip($field) {
getTooltipAnchor($field).tipsy('show');
if (focusTogglesTooltip($field)) {
bindTooltipTabEvents($field);
}
}
function hideTooltip($field) {
getTooltipAnchor($field).tipsy('hide');
}
function bindFocusTooltipInteractions() {
document.addEventListener('focus', function (e) {
notificationFields.forEach(function (field) {
var $field = (0, _jquery2.default)(field);
var $tooltip = getTooltip($field);
if (!focusTogglesTooltip($field)) {
return;
}
var isFocusInTooltip = $tooltip && _jquery2.default.contains($tooltip[0], e.target);
var isFocusTargetField = $field.is(e.target);
var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $field);
if (isFocusTargetField || isFocusTargetChildOfField) {
showTooltip($field);
} else if ($tooltip && !isFocusInTooltip) {
hideTooltip($field);
}
});
}, true);
}
bindFocusTooltipInteractions();
function isFocusEventTargetInElement(event, $element) {
return (0, _jquery2.default)(event.target).closest($element).length > 0;
}
function bindFieldTabEvents($field) {
$field.on('keydown', function (e) {
if (isNormalTab(e) && fieldHasTooltip($field)) {
var $firstTooltipLink = getFirstTooltipLink($field);
if ($firstTooltipLink.length) {
$firstTooltipLink.focus();
e.preventDefault();
}
}
});
}
function isNormalTab(e) {
return e.keyCode === _keyCode2.default.TAB && !e.shiftKey && !e.altKey;
}
function isShiftTab(e) {
return e.keyCode === _keyCode2.default.TAB && e.shiftKey;
}
function getFirstTooltipLink($field) {
return getTooltip($field).find(':aui-tabbable').first();
}
function getLastTooltipLink($field) {
return getTooltip($field).find(':aui-tabbable').last();
}
function getTooltip($field) {
var $anchor = getTooltipAnchor($field);
if ($anchor.data('tipsy')) {
return $anchor.data('tipsy').$tip;
}
}
function bindTooltipTabEvents($field) {
var $tooltip = getTooltip($field);
$tooltip.on('keydown', function (e) {
var leavingTooltipForwards = elementIsActive(getLastTooltipLink($field));
var leavingTooltipBackwards = elementIsActive(getFirstTooltipLink($field));
if (isNormalTab(e) && leavingTooltipForwards) {
if (leavingTooltipForwards) {
$field.focus();
}
}
if (isShiftTab(e) && leavingTooltipBackwards) {
if (leavingTooltipBackwards) {
$field.focus();
e.preventDefault();
}
}
});
}
function getTipsyGravity($field) {
var position = $field.data(ATTRIBUTE_TOOLTIP_POSITION) || 'side';
var gravityMap = {
side: 'w',
top: 'se',
bottom: 'ne'
};
var gravity = gravityMap[position];
if (!gravity) {
gravity = 'w';
logger.warn('Invalid notification position: "' + position + '". Valid options are "side", "bottom, "top"');
}
return gravity;
}
function getTooltipAnchor($field) {
return getFieldIcon($field);
}
function getFieldIcon($field) {
return $field.next('.' + CLASS_NOTIFICATION_ICON);
}
function elementIsActive($el) {
var el = $el instanceof _jquery2.default ? $el[0] : $el;
return el && el === document.activeElement;
}
function synchroniseNotificationDisplay(field) {
var $field = (0, _jquery2.default)(field);
if (!isFieldInitialised($field)) {
return;
}
var notificationType = getFieldNotificationType($field);
var showSpinner = notificationType === ATTRIBUTE_NOTIFICATION_WAIT;
setFieldSpinner($field, showSpinner);
var noNotificationOnField = !notificationType;
if (noNotificationOnField) {
hideTooltip($field);
return;
}
var message = getNotificationMessage($field);
var fieldContainsActiveElement = _jquery2.default.contains($field[0], document.activeElement);
var tooltipShouldBeVisible = fieldContainsActiveElement || elementIsActive($field) || !focusTogglesTooltip($field);
if (tooltipShouldBeVisible && message) {
showTooltip($field);
} else {
hideTooltip($field);
}
}
function setFieldSpinner($field, isSpinnerVisible) {
if (isSpinnerVisible) {
getFieldIcon($field).addClass('aui-icon-wait');
} else {
getFieldIcon($field).removeClass('aui-icon-wait');
}
}
document.addEventListener('mousedown', function (e) {
var isTargetLink = (0, _jquery2.default)(e.target).is('a');
if (isTargetLink) {
return;
}
var isTargetTooltip = (0, _jquery2.default)(e.target).closest('.aui-form-notification-tooltip').length > 0;
if (isTargetTooltip) {
return;
}
var $allNotificationFields = (0, _jquery2.default)('[data-aui-notification-field]');
$allNotificationFields.each(function () {
var $notificationField = (0, _jquery2.default)(this);
var targetIsThisField = $notificationField.is(e.target);
var isFocusTargetChildOfField = isFocusEventTargetInElement(e, $notificationField);
if (!targetIsThisField && !isFocusTargetChildOfField) {
hideTooltip($notificationField);
}
if (focusTogglesTooltip($notificationField)) {
hideTooltip($notificationField);
}
});
});
(0, _skate2.default)('data-aui-notification-field', {
attached: function attached(element) {
initialiseNotification((0, _jquery2.default)(element));
},
attributes: function () {
var attrs = {};
NOTIFICATION_PRIORITY.forEach(function (type) {
attrs[type] = synchroniseNotificationDisplay;
});
return attrs;
}(),
type: _skate2.default.type.ATTRIBUTE
});
(0, _amdify2.default)('aui/form-notification');
return module.exports;
}).call(this);
// src/js/aui/form-validation/validator-register.js
(typeof window === 'undefined' ? global : window).__d1c8e25e9e01e4d366088e44abd86cd0 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ATTRIBUTE_RESERVED_ARGUMENTS = ['displayfield', 'watchfield', 'when', 'novalidate', 'state'];
var _validators = [];
function getReservedArgument(validatorArguments) {
var reservedArgument = false;
validatorArguments.some(function (arg) {
var isReserved = _jquery2.default.inArray(arg, ATTRIBUTE_RESERVED_ARGUMENTS) !== -1;
if (isReserved) {
reservedArgument = arg;
}
return isReserved;
});
return reservedArgument;
}
/**
* Register a validator that can be used to validate fields. The main entry point for validator plugins.
* @param trigger - when to run the validator. Can be an array of arguments, or a selector
* @param validatorFunction - the function that will be called on the field to determine validation. Receives
* field - the field that is being validated
* args - the arguments that have been specified in HTML markup.
*/
function registerValidator(trigger, validatorFunction) {
var triggerSelector;
if (typeof trigger === 'string') {
triggerSelector = trigger;
} else {
var reservedArgument = getReservedArgument(trigger);
if (reservedArgument) {
logger.warn('Validators cannot be registered with the argument "' + reservedArgument + '", as it is a reserved argument.');
return false;
}
triggerSelector = '[data-aui-validation-' + trigger.join('],[data-aui-validation-') + ']';
}
var validator = {
validatorFunction: validatorFunction,
validatorTrigger: triggerSelector
};
_validators.push(validator);
return validator;
}
var validatorRegister = {
register: registerValidator,
validators: function validators() {
return _validators;
}
};
(0, _amdify2.default)('aui/form-validation/validator-register', validatorRegister);
exports.default = validatorRegister;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/form-validation/basic-validators.js
(typeof window === 'undefined' ? global : window).__22130538f5919f6e261036684b13c6f2 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _format = __a0d4f23ad4f9b40c6f8c8e4e6922c981;
var _format2 = _interopRequireDefault(_format);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _validatorRegister = __d1c8e25e9e01e4d366088e44abd86cd0;
var _validatorRegister2 = _interopRequireDefault(_validatorRegister);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//Input length
// eslint-disable-line no-unused-vars
function minMaxLength(field) {
var fieldValueLength = field.el.value.length;
var fieldIsEmpty = fieldValueLength === 0;
var minlength = parseInt(field.args('minlength'), 10);
var maxlength = parseInt(field.args('maxlength'), 10);
if (minlength && maxlength && minlength === maxlength && !fieldIsEmpty && fieldValueLength !== minlength) {
var exactlengthMessage = makeMessage('exactlength', field.args, [minlength]);
field.invalidate(exactlengthMessage);
} else if (minlength && fieldValueLength < minlength && !fieldIsEmpty) {
var minlengthMessage = makeMessage('minlength', field.args);
field.invalidate(minlengthMessage);
} else if (maxlength && fieldValueLength > maxlength) {
var maxlengthMessage = makeMessage('maxlength', field.args);
field.invalidate(maxlengthMessage);
} else {
field.validate();
}
} // eslint-disable-line no-unused-vars
_validatorRegister2.default.register(['maxlength', 'minlength'], minMaxLength); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[maxlength],[minlength]', minMaxLength);
//Field matching
_validatorRegister2.default.register(['matchingfield'], function (field) {
var thisFieldValue = field.el.value;
var matchingField = document.getElementById(field.args('matchingfield'));
var matchingFieldValue = matchingField.value;
var matchingFieldMessage = makeMessage('matchingfield', field.args, [thisFieldValue, matchingFieldValue]);
var shouldHidePasswords = isPasswordField(field.el) || isPasswordField(matchingField);
if (shouldHidePasswords) {
matchingFieldMessage = makeMessage('matchingfield-novalue', field.args);
}
if (!thisFieldValue || !matchingFieldValue) {
field.validate();
} else if (matchingFieldValue !== thisFieldValue) {
field.invalidate(matchingFieldMessage);
} else {
field.validate();
}
});
function isPasswordField(field) {
return field.getAttribute('type') === 'password';
}
//Banned words
_validatorRegister2.default.register(['doesnotcontain'], function (field) {
var doesNotContainMessage = makeMessage('doesnotcontain', field.args);
if (field.el.value.indexOf(field.args('doesnotcontain')) === -1) {
field.validate();
} else {
field.invalidate(doesNotContainMessage);
}
});
//Matches regex
function matchesRegex(val, regex) {
var matches = val.match(regex);
if (!matches) {
return false;
}
var isExactMatch = val === matches[0];
return isExactMatch;
}
function pattern(field) {
var patternMessage = makeMessage('pattern', field.args);
if (matchesRegex(field.el.value, new RegExp(field.args('pattern')))) {
field.validate();
} else {
field.invalidate(patternMessage);
}
}
_validatorRegister2.default.register(['pattern'], pattern); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[pattern]', pattern);
//Native Required
function required(field) {
var requiredMessage = makeMessage('required', field.args);
if (field.el.value) {
field.validate();
} else {
field.invalidate(requiredMessage);
}
}
_validatorRegister2.default.register(['required'], required); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[required]', required);
//Field value range (between min and max)
function minOrMax(field) {
var validNumberMessage = makeMessage('validnumber', field.args);
var fieldValue = parseInt(field.el.value, 10);
if (isNaN(fieldValue)) {
field.invalidate(validNumberMessage);
return;
}
var minValue = field.args('min');
var maxValue = field.args('max');
if (minValue && fieldValue < parseInt(minValue, 10)) {
field.invalidate(makeMessage('min', field.args));
} else if (maxValue && fieldValue > parseInt(maxValue, 10)) {
field.invalidate(makeMessage('max', field.args));
} else {
field.validate();
}
}
_validatorRegister2.default.register(['min', 'max'], minOrMax); //AUI-prefixed attribute is deprecated as of 5.9.0
_validatorRegister2.default.register('[min],[max]', minOrMax);
//Date format
_validatorRegister2.default.register(['dateformat'], function (field) {
var dateFormatSymbolic = field.args('dateformat');
var dateFormatMessage = makeMessage('dateformat', field.args);
var symbolRegexMap = {
'Y': '[0-9]{4}',
'y': '[0-9]{2}',
'm': '(0?[1-9]|10|11|12)',
'M': '[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]',
'D': '[Mon|Tue|Wed|Thu|Fri|Sat|Sun]',
'd': '([0-2]?[1-9]|10|20|30|31)'
};
var dateFormatSymbolArray = dateFormatSymbolic.split('');
var dateFormatRegexString = '';
dateFormatSymbolArray.forEach(function (dateSymbol) {
var isRecognisedSymbol = symbolRegexMap.hasOwnProperty(dateSymbol);
if (isRecognisedSymbol) {
dateFormatRegexString += symbolRegexMap[dateSymbol];
} else {
dateFormatRegexString += dateSymbol;
}
});
var dateFormatRegex = new RegExp(dateFormatRegexString + '$', 'i');
var isValidDate = matchesRegex(field.el.value, dateFormatRegex);
if (isValidDate) {
field.validate();
} else {
field.invalidate(dateFormatMessage);
}
});
//Checkbox count
_validatorRegister2.default.register(['minchecked', 'maxchecked'], function (field) {
var amountChecked = (0, _jquery2.default)(field.el).find(':checked').length;
var aboveMin = !field.args('minchecked') || amountChecked >= field.args('minchecked');
var belowMax = !field.args('maxchecked') || amountChecked <= field.args('maxchecked');
var belowMinMessage = makeMessage('minchecked', field.args);
var aboveMaxMessage = makeMessage('maxchecked', field.args);
if (aboveMin && belowMax) {
field.validate();
} else if (!aboveMin) {
field.invalidate(belowMinMessage);
} else if (!belowMax) {
field.invalidate(aboveMaxMessage);
}
});
/*
Retrieves a message for a plugin validator through the data attributes or the default (which is in the i18n file)
*/
function makeMessage(key, accessorFunction, customTokens) {
var inFlatpackMode = AJS.I18n.keys !== undefined;
var defaultMessage;
if (inFlatpackMode) {
defaultMessage = AJS.I18n.keys['aui.validation.message.' + key];
} else {
defaultMessage = pluginI18nMessages[key];
}
var messageTokens = customTokens;
if (!customTokens) {
messageTokens = [accessorFunction(key)];
}
var customMessageUnformatted = accessorFunction(key + '-msg');
var formattingArguments;
if (customMessageUnformatted) {
formattingArguments = [customMessageUnformatted].concat(messageTokens);
} else {
formattingArguments = [defaultMessage].concat(messageTokens);
}
return AJS.format.apply(null, formattingArguments);
}
/*
The value AJS.I18n.getText('aui.validation.message...') (defaultMessage) cannot be refactored as it
must appear verbatim for the plugin I18n transformation to pick it up
*/
var pluginI18nMessages = {
minlength: AJS.I18n.getText('aui.validation.message.minlength'),
maxlength: AJS.I18n.getText('aui.validation.message.maxlength'),
exactlength: AJS.I18n.getText('aui.validation.message.exactlength'),
matchingfield: AJS.I18n.getText('aui.validation.message.matchingfield'),
'matchingfield-novalue': AJS.I18n.getText('aui.validation.message.matchingfield-novalue'),
doesnotcontain: AJS.I18n.getText('aui.validation.message.doesnotcontain'),
pattern: AJS.I18n.getText('aui.validation.message.pattern'),
required: AJS.I18n.getText('aui.validation.message.required'),
validnumber: AJS.I18n.getText('aui.validation.message.validnumber'),
min: AJS.I18n.getText('aui.validation.message.min'),
max: AJS.I18n.getText('aui.validation.message.max'),
dateformat: AJS.I18n.getText('aui.validation.message.dateformat'),
minchecked: AJS.I18n.getText('aui.validation.message.minchecked'),
maxchecked: AJS.I18n.getText('aui.validation.message.maxchecked')
};
(0, _amdify2.default)('aui/form-validation/basic-validators');
return module.exports;
}).call(this);
// src/js/aui/form-validation.js
(typeof window === 'undefined' ? global : window).__bd4ecc7f267c4325495affa1d72b9196 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__223d4ffbfb11c7b1196e30d8f0783cb8;
__22130538f5919f6e261036684b13c6f2;
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _deprecation = __4ddcc788b1704f76a51559fc0e0d2968;
var deprecate = _interopRequireWildcard(_deprecation);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _validatorRegister = __d1c8e25e9e01e4d366088e44abd86cd0;
var _validatorRegister2 = _interopRequireDefault(_validatorRegister);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//Attributes
var ATTRIBUTE_VALIDATION_OPTION_PREFIX = 'aui-validation-';
var ATTRIBUTE_NOTIFICATION_PREFIX = 'data-aui-notification-';
var ATTRIBUTE_FIELD_STATE = 'aui-validation-state';
var INVALID = 'invalid';
var VALID = 'valid';
var VALIDATING = 'validating';
var UNVALIDATED = 'unvalidated';
var ATTRIBUTE_VALIDATION_FIELD_COMPONENT = 'data-aui-validation-field';
//Classes
var CLASS_VALIDATION_INITIALISED = '_aui-form-validation-initialised';
//Events
var EVENT_FIELD_STATE_CHANGED = '_aui-internal-field-state-changed';
function isFieldInitialised($field) {
return $field.hasClass(CLASS_VALIDATION_INITIALISED);
}
function initValidation($field) {
if (!isFieldInitialised($field)) {
initialiseDisplayField($field);
prepareFieldMarkup($field);
bindFieldEvents($field);
changeFieldState($field, UNVALIDATED);
}
}
function initialiseDisplayField($field) {
getDisplayField($field).attr('data-aui-notification-field', '');
}
function prepareFieldMarkup($field) {
$field.addClass(CLASS_VALIDATION_INITIALISED);
}
function bindFieldEvents($field) {
bindStopTypingEvent($field);
bindValidationEvent($field);
}
function bindStopTypingEvent($field) {
var keyUpTimer;
var triggerStopTypingEvent = function triggerStopTypingEvent() {
$field.trigger('aui-stop-typing');
};
$field.on('keyup', function () {
clearTimeout(keyUpTimer);
keyUpTimer = setTimeout(triggerStopTypingEvent, 1500);
});
}
function bindValidationEvent($field) {
var validateWhen = getValidationOption($field, 'when');
var watchedFieldID = getValidationOption($field, 'watchfield');
var elementsToWatch = watchedFieldID ? $field.add('#' + watchedFieldID) : $field;
elementsToWatch.on(validateWhen, function startValidation() {
validationTriggeredHandler($field);
});
}
function validationTriggeredHandler($field) {
var noValidate = getValidationOption($field, 'novalidate');
if (noValidate) {
changeFieldState($field, VALID);
return;
}
return startValidating($field);
}
function getValidationOption($field, option) {
var defaults = {
'when': 'change'
};
var optionValue = $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + option);
if (!optionValue) {
optionValue = defaults[option];
}
return optionValue;
}
function startValidating($field) {
clearFieldMessages($field);
var validatorsToRun = getActivatedValidators($field);
changeFieldState($field, VALIDATING);
var deferreds = runValidatorsAndGetDeferred($field, validatorsToRun);
var fieldValidators = _jquery2.default.when.apply(_jquery2.default, deferreds);
fieldValidators.done(function () {
changeFieldState($field, VALID);
});
return fieldValidators;
}
function clearFieldMessages($field) {
setFieldNotification(getDisplayField($field), 'none');
}
function getValidators() {
return _validatorRegister2.default.validators();
}
function getActivatedValidators($field) {
var callList = [];
getValidators().forEach(function (validator, index) {
var validatorTrigger = validator.validatorTrigger;
var runThisValidator = $field.is(validatorTrigger);
if (runThisValidator) {
callList.push(index);
}
});
return callList;
}
function runValidatorsAndGetDeferred($field, validatorsToRun) {
var allDeferreds = [];
validatorsToRun.forEach(function (validatorIndex) {
var validatorFunction = getValidators()[validatorIndex].validatorFunction;
var deferred = new _jquery2.default.Deferred();
var validatorContext = createValidatorContext($field, deferred);
validatorFunction(validatorContext);
allDeferreds.push(deferred);
});
return allDeferreds;
}
function createValidatorContext($field, validatorDeferred) {
var context = {
validate: function validate() {
validatorDeferred.resolve();
},
invalidate: function invalidate(message) {
changeFieldState($field, INVALID, message);
validatorDeferred.reject();
},
args: createArgumentAccessorFunction($field),
el: $field[0],
$el: $field
};
deprecate.prop(context, '$el', {
sinceVersion: '5.9.0',
removeInVersion: '8.0.0',
alternativeName: 'el',
extraInfo: 'See https://ecosystem.atlassian.net/browse/AUI-3263.'
});
return context;
}
function createArgumentAccessorFunction($field) {
return function (arg) {
return $field.attr('data-' + ATTRIBUTE_VALIDATION_OPTION_PREFIX + arg) || $field.attr(arg);
};
}
function changeFieldState($field, state, message) {
$field.attr('data-' + ATTRIBUTE_FIELD_STATE, state);
if (state === UNVALIDATED) {
return;
}
$field.trigger(_jquery2.default.Event(EVENT_FIELD_STATE_CHANGED));
var $displayField = getDisplayField($field);
var stateToNotificationTypeMap = {};
stateToNotificationTypeMap[VALIDATING] = 'wait';
stateToNotificationTypeMap[INVALID] = 'error';
stateToNotificationTypeMap[VALID] = 'success';
var notificationType = stateToNotificationTypeMap[state];
if (state === VALIDATING) {
showSpinnerIfSlow($field);
} else {
setFieldNotification($displayField, notificationType, message);
}
}
function showSpinnerIfSlow($field) {
setTimeout(function () {
var stillValidating = getFieldState($field) === VALIDATING;
if (stillValidating) {
setFieldNotification($field, 'wait');
}
}, 500);
}
function setFieldNotification($field, type, message) {
var spinnerWasVisible = isSpinnerVisible($field);
removeIconOnlyNotifications($field);
var skipShowingSuccessNotification = type === 'success' && !spinnerWasVisible;
if (skipShowingSuccessNotification) {
return;
}
if (type === 'none') {
removeFieldNotification($field, 'error');
} else {
var previousMessage = $field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type) || '[]';
var newMessage = message ? combineJSONMessages(message, previousMessage) : '';
$field.attr(ATTRIBUTE_NOTIFICATION_PREFIX + type, newMessage);
}
}
function removeIconOnlyNotifications($field) {
removeFieldNotification($field, 'wait');
removeFieldNotification($field, 'success');
}
function removeFieldNotification($field, type) {
$field.removeAttr(ATTRIBUTE_NOTIFICATION_PREFIX + type);
}
function isSpinnerVisible($field) {
return $field.is('[' + ATTRIBUTE_NOTIFICATION_PREFIX + 'wait]');
}
function combineJSONMessages(newString, previousString) {
var previousStackedMessageList = JSON.parse(previousString);
var newStackedMessageList = previousStackedMessageList.concat([newString]);
var newStackedMessage = JSON.stringify(newStackedMessageList);
return newStackedMessage;
}
function getDisplayField($field) {
var displayFieldID = getValidationOption($field, 'displayfield');
var notifyOnSelf = displayFieldID === undefined;
return notifyOnSelf ? $field : (0, _jquery2.default)('#' + displayFieldID);
}
function getFieldState($field) {
return $field.attr('data-' + ATTRIBUTE_FIELD_STATE);
}
/**
* Trigger validation on a field manually
* @param $field the field that validation should be triggered for
*/
function validateField($field) {
$field = (0, _jquery2.default)($field);
validationTriggeredHandler($field);
}
/**
* Form scrolling and submission prevent based on validation state
* -If the form is unvalidated, validate all fields
* -If the form is invalid, go to the first invalid element
* -If the form is validating, wait for them to validate and then try submitting again
* -If the form is valid, allow form submission
*/
(0, _jquery2.default)(document).on('submit', function (e) {
var form = e.target;
var $form = (0, _jquery2.default)(form);
var formState = getFormStateName($form);
if (formState === UNVALIDATED) {
delaySubmitUntilStateChange($form, e);
validateUnvalidatedFields($form);
} else if (formState === VALIDATING) {
delaySubmitUntilStateChange($form, e);
} else if (formState === INVALID) {
e.preventDefault();
selectFirstInvalid($form);
} else if (formState === VALID) {
var validSubmitEvent = _jquery2.default.Event('aui-valid-submit');
$form.trigger(validSubmitEvent);
var preventNormalSubmit = validSubmitEvent.isDefaultPrevented();
if (preventNormalSubmit) {
e.preventDefault(); //users can bind to aui-valid-submit for ajax forms
}
}
});
function delaySubmitUntilStateChange($form, event) {
event.preventDefault();
$form.one(EVENT_FIELD_STATE_CHANGED, function () {
$form.trigger('submit');
});
}
function getFormStateName($form) {
var $fieldCollection = $form.find('.' + CLASS_VALIDATION_INITIALISED);
var fieldStates = getFieldCollectionStateNames($fieldCollection);
var wholeFormState = mergeStates(fieldStates);
return wholeFormState;
}
function getFieldCollectionStateNames($fields) {
var states = _jquery2.default.map($fields, function (field) {
return getFieldState((0, _jquery2.default)(field));
});
return states;
}
function mergeStates(stateNames) {
var containsInvalidState = stateNames.indexOf(INVALID) !== -1;
var containsUnvalidatedState = stateNames.indexOf(UNVALIDATED) !== -1;
var containsValidatingState = stateNames.indexOf(VALIDATING) !== -1;
if (containsInvalidState) {
return INVALID;
} else if (containsUnvalidatedState) {
return UNVALIDATED;
} else if (containsValidatingState) {
return VALIDATING;
} else {
return VALID;
}
}
function validateUnvalidatedFields($form) {
var $unvalidatedElements = getFieldsInFormWithState($form, UNVALIDATED);
$unvalidatedElements.each(function (index, el) {
validator.validate((0, _jquery2.default)(el));
});
}
function selectFirstInvalid($form) {
var $firstInvalidField = getFieldsInFormWithState($form, INVALID).first();
$firstInvalidField.focus();
}
function getFieldsInFormWithState($form, state) {
var selector = '[data-' + ATTRIBUTE_FIELD_STATE + '=' + state + ']';
return $form.find(selector);
}
var validator = {
register: _validatorRegister2.default.register,
validate: validateField
};
(0, _skate2.default)(ATTRIBUTE_VALIDATION_FIELD_COMPONENT, {
attached: function attached(field) {
if (field.form) {
field.form.setAttribute('novalidate', 'novalidate');
}
var $field = (0, _jquery2.default)(field);
initValidation($field);
_skate2.default.init(field); //needed to kick off form notification skate initialisation
},
type: _skate2.default.type.ATTRIBUTE
});
(0, _amdify2.default)('aui/form-validation', validator);
(0, _globalize2.default)('formValidation', validator);
exports.default = validator;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/constants.js
(typeof window === 'undefined' ? global : window).__e378fd259e8cc11973d9809608fe9a5e = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var INPUT_SUFFIX = '-input';
exports.default = {
INPUT_SUFFIX: INPUT_SUFFIX
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/label.js
(typeof window === 'undefined' ? global : window).__7904d2f802801befa81e22aff0bd1fb6 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
var _enforcer = __65a8b3ca1b55232381cf1e189f6e2c47;
var _enforcer2 = _interopRequireDefault(_enforcer);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getLabel(element) {
return element.querySelector('label');
}
function updateLabelFor(element, change) {
if (element.hasAttribute('for')) {
getLabel(element).setAttribute('for', '' + change.newValue + _constants.INPUT_SUFFIX);
} else {
getLabel(element).removeAttribute('for');
}
}
function updateLabelForm(element, change) {
if (element.hasAttribute('form')) {
getLabel(element).setAttribute('form', change.newValue);
} else {
getLabel(element).removeAttribute('form');
}
}
var Label = (0, _skate2.default)('aui-label', {
template: (0, _skatejsTemplateHtml2.default)('<label><content></content></label>'),
created: function created(element) {
element._label = getLabel(element); // required for quick access from test
},
attached: function attached(element) {
(0, _enforcer2.default)(element).attributeExists('for');
},
attributes: {
'for': updateLabelFor,
form: updateLabelForm
},
prototype: {
get disabled() {
return this.hasAttribute('disabled');
},
set disabled(value) {
if (value) {
this.setAttribute('disabled', '');
} else {
this.removeAttribute('disabled');
}
}
},
events: {
click: function click(element, e) {
if (element.disabled) {
e.preventDefault();
}
}
}
});
exports.default = Label;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/progress-indicator.js
(typeof window === 'undefined' ? global : window).__ef3494fdb79b0ce378f14c1810d48a68 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _animation = __57bb8e7218df9c12a4337e92d4c02bd5;
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function updateProgress($progressBar, $progressBarContainer, progressValue) {
(0, _animation.recomputeStyle)($progressBar);
$progressBar.css('width', progressValue * 100 + '%');
$progressBarContainer.attr('data-value', progressValue);
}
var progressBars = {
update: function update(element, value) {
var $progressBarContainer = (0, _jquery2.default)(element).first();
var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value');
var valueAttribute = $progressBarContainer.attr('data-value');
var currentProgress = parseFloat(valueAttribute) || 0;
var isProgressNotChanged = valueAttribute && currentProgress === value;
if (isProgressNotChanged) {
return;
}
var afterTransitionEvent = 'aui-progress-indicator-after-update';
var beforeTransitionEvent = 'aui-progress-indicator-before-update';
var transitionEnd = 'transitionend webkitTransitionEnd';
var isIndeterminate = !valueAttribute;
//if the progress bar is indeterminate switch it.
if (isIndeterminate) {
$progressBar.css('width', 0);
}
if (typeof value === 'number' && value <= 1 && value >= 0) {
$progressBarContainer.trigger(beforeTransitionEvent, [currentProgress, value]);
//detect whether transitions are supported
var documentBody = document.body || document.documentElement;
var style = documentBody.style;
var isTransitionSupported = typeof style.transition === 'string' || typeof style.WebkitTransition === 'string';
//trigger the event after transition end if supported, otherwise just trigger it
if (isTransitionSupported) {
$progressBar.one(transitionEnd, function () {
$progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]);
});
updateProgress($progressBar, $progressBarContainer, value);
} else {
updateProgress($progressBar, $progressBarContainer, value);
$progressBarContainer.trigger(afterTransitionEvent, [currentProgress, value]);
}
}
return $progressBarContainer;
},
setIndeterminate: function setIndeterminate(element) {
var $progressBarContainer = (0, _jquery2.default)(element).first();
var $progressBar = $progressBarContainer.children('.aui-progress-indicator-value');
$progressBarContainer.removeAttr('data-value');
(0, _animation.recomputeStyle)($progressBarContainer);
$progressBar.css('width', '100%');
}
};
(0, _globalize2.default)('progressBars', progressBars);
exports.default = progressBars;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/backbone/backbone.js
(typeof window === 'undefined' ? global : window).__754d6596329027c6beeb095ab86facf5 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
var defineDependencies = {
"module": module,
"exports": exports,
"underscore": __b3f4465251fd1fb4828e20c3f041f71e,
"jquery": __77629c8e853846530dfdc3ccd3393ab6,
"underscore": __b3f4465251fd1fb4828e20c3f041f71e,
"jquery": __77629c8e853846530dfdc3ccd3393ab6
};
var define = function defineReplacementWrapper(generatedModuleName) {
return function defineReplacement(name, deps, func) {
var root = (typeof window === 'undefined' ? global : window);
var defineGlobal = root.define;
var rval;
var type;
func = [func, deps, name].filter(function (cur) {
return typeof cur === 'function';
})[0];
deps = [deps, name, []].filter(Array.isArray)[0];
rval = func.apply(null, deps.map(function (value) {
return defineDependencies[value];
}));
type = typeof rval;
// Support existing AMD libs.
if (typeof defineGlobal === 'function') {
// Almond always expects a name so resolve one (#29).
defineGlobal(typeof name === 'string' ? name : generatedModuleName, deps, func);
}
// Some processors like Babel don't check to make sure that the module value
// is not a primitive before calling Object.defineProperty() on it. We ensure
// it is an instance so that it can.
if (type === 'string') {
rval = String(rval);
} else if (type === 'number') {
rval = Number(rval);
} else if (type === 'boolean') {
rval = Boolean(rval);
}
// Reset the exports to the defined module. This is how we convert AMD to
// CommonJS and ensures both can either co-exist, or be used separately. We
// only set it if it is not defined because there is no object representation
// of undefined, thus calling Object.defineProperty() on it would fail.
if (rval !== undefined) {
exports = module.exports = rval;
}
};
}("__754d6596329027c6beeb095ab86facf5");
define.amd = true;
/*! THIS FILE HAS BEEN MODIFIED BY ATLASSIAN. Modified lines are marked below, search "ATLASSIAN" */
// Backbone.js 1.0.0
// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Backbone may be freely distributed under the MIT license.
// For all details and documentation:
// http://backbonejs.org
/**
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* This is a modification of the UMD wrapper used in Backbone 1.1.x
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*/
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
var _ = __b3f4465251fd1fb4828e20c3f041f71e, $;
try { $ = __77629c8e853846530dfdc3ccd3393ab6; } catch(e) {}
factory(root, exports, _, $);
// Finally, as a browser global.
} else {
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
}(this, function(root, Backbone, _, $) {
/** END ATLASSIAN */
// Initial Setup
// -------------
// Save a reference to the global object (`window` in the browser, `exports`
// on the server).
var root = this;
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var splice = array.splice;
/**
* FOLLOWING LINES REMOVED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*
* // The top-level namespace. All public Backbone classes and modules will
* // be attached to this. Exported for both the browser and the server.
* var Backbone;
* if (typeof exports !== 'undefined') {
* Backbone = exports;
* } else {
* Backbone = root.Backbone = {};
* }
*
*/
// Current version of the library. Keep in sync with `package.json`.
Backbone.VERSION = '1.0.0';
/**
* FOLLOWING LINES REMOVED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*
*
* // Require Underscore, if we're on the server, and it's not already present.
* var _ = root._;
*
* if (!_ && (typeof require !== 'undefined')) _ = __b3f4465251fd1fb4828e20c3f041f71e;
*
/** END ATLASSIAN */
/*
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* These are superseded by the UMD wrapper above.
*/
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
// the `$` variable.
Backbone.$ = $;
/** END ATLASSIAN */
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
// set a `X-Http-Method-Override` header.
Backbone.emulateHTTP = false;
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
// `application/json` requests ... will encode the body as
// `application/x-www-form-urlencoded` instead and will send the model in a
// form param named `model`.
Backbone.emulateJSON = false;
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = {};
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeners = this._listeners;
if (!listeners) return this;
var deleteListener = !name && !callback;
if (typeof name === 'object') callback = this;
if (obj) (listeners = {})[obj._listenerId] = obj;
for (var id in listeners) {
listeners[id].off(name, callback, this);
if (deleteListener) delete this._listeners[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
_.each(listenMethods, function(implementation, method) {
Events[method] = function(obj, name, callback) {
var listeners = this._listeners || (this._listeners = {});
var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
listeners[id] = obj;
if (typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var defaults;
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
_.extend(this, _.pick(options, modelOptions));
if (options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
// A list of options to be attached directly to the model, if provided.
var modelOptions = ['url', 'urlRoot', 'collection'];
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.clone(this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.clone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = true;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
options = _.extend({validate: true}, options);
// Do not persist invalid models.
if (!this._validate(attrs, options)) return false;
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend({}, attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return this.id == null;
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
return false;
}
});
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
_.each(modelMethods, function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.url) this.url = options.url;
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, merge: false, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.defaults(options || {}, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
models = _.isArray(models) ? models.slice() : [models];
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults(options || {}, setOptions);
if (options.parse) models = this.parse(models, options);
if (!_.isArray(models)) models = models ? [models] : [];
var i, l, model, attrs, existing, sort;
var at = options.at;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
if (!(model = this._prepareModel(models[i], options))) continue;
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(model)) {
if (options.remove) modelMap[existing.cid] = true;
if (options.merge) {
existing.set(model.attributes, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
// This is a new model, push it to the `toAdd` list.
} else if (options.add) {
toAdd.push(model);
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
model.on('all', this._onModelEvent, this);
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
}
// Remove nonexistent models if appropriate.
if (options.remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
splice.apply(this.models, [at, 0].concat(toAdd));
} else {
push.apply(this.models, toAdd);
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
if (options.silent) return this;
// Trigger `add` events.
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
// Trigger `sort` if the collection was sorted.
if (sort) this.trigger('sort', this, options);
return this;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
options.previousModels = this.models;
this._reset();
this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: this.length}, options));
return model;
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function(begin, end) {
return this.models.slice(begin, end);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj.id != null ? obj.id : obj.cid || obj];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (_.isString(this.comparator) || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(_.bind(this.comparator, this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Figure out the smallest index at which a model should be inserted so as
// to maintain order.
sortedIndex: function(model, value, context) {
value || (value = this.comparator);
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _.sortedIndex(this.models, model, iterator, context);
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return _.invoke(this.models, 'get', attr);
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
// ATLASSIAN CHANGES DUE TO: https://ecosystem.atlassian.net/browse/AUI-1787
// FOLLOWING LINE REMOVED BY ATLASSIAN
// options.success = function(resp) {
// FOLLOWING LINE ADDED BY ATLASSIAN
options.success = function(model, resp, options) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) {
if (!attrs.collection) attrs.collection = this;
return attrs;
}
options || (options = {});
options.collection = this;
var model = new this.model(attrs, options);
if (!model._validate(attrs, options)) {
this.trigger('invalid', this, attrs, options);
return false;
}
return model;
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Collection#models`.
_.each(methods, function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
// Use attributes instead of properties.
_.each(attributeMethods, function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = _.isFunction(value) ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be prefered to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save'
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
// Performs the initial configuration of a View with a set of options.
// Keys with special meaning *(e.g. model, collection, id, className)* are
// attached directly to the view. See `viewOptions` for an exhaustive
// list.
_configure: function(options) {
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
_.extend(this, _.pick(options, viewOptions));
this.options = options;
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
//
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
// as `POST`, with a `_method` parameter containing the true HTTP method,
// as well as all requests with the body as `application/x-www-form-urlencoded`
// instead of `application/json` with the model in a param named `model`.
// Useful when interfacing with server-side languages like **PHP** that make
// it difficult to read the body of `PUT` requests.
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default options, unless specified.
_.defaults(options || (options = {}), {
emulateHTTP: Backbone.emulateHTTP,
emulateJSON: Backbone.emulateJSON
});
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (options.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !options.emulateJSON) {
params.processData = false;
}
// If we're sending a `PATCH` request, and we're in an old Internet Explorer
// that still has ActiveX enabled by default, override jQuery to use that
// for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
if (params.type === 'PATCH' && window.ActiveXObject &&
!(window.external && window.external.msActiveXFilteringEnabled)) {
params.xhr = function() {
return new ActiveXObject("Microsoft.XMLHTTP");
};
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
callback && callback.apply(router, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional){
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param) {
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments. If the browser supports neither (old IE, natch),
// falls back to polling.
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname;
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
if (oldIE && this._wantsHashChange) {
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: options};
fragment = this.getFragment(fragment || '');
if (this.fragment === fragment) return;
this.fragment = fragment;
var url = this.root + fragment;
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier to push a
// history entry on hash-tag change. When replace is true, we don't
// want this.
if(!options.replace) this.iframe.document.open().close();
this._updateHash(this.iframe.location, fragment, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// Create the default Backbone.history.
Backbone.history = new History;
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function (model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
/**
* FOLLOWING LINES MODIFIED BY ATLASSIAN
* This is a modification of the UMD wrapper used in Backbone 1.1.x
* @see https://ecosystem.atlassian.net/browse/AUI-2989
*/
return Backbone;
/** END ATLASSIAN */
}));
return module.exports;
}).call(this);
// src/js/aui/backbone.js
(typeof window === 'undefined' ? global : window).__07cdfb826f754040b351a0110fde6536 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __754d6596329027c6beeb095ab86facf5;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// BEWARE: The following is an unused import with side-effects
if (!window.Backbone) {
window.Backbone = _backbone2.default;
} // eslint-disable-line no-unused-vars
exports.default = window.Backbone;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/progressive-data-set.js
(typeof window === 'undefined' ? global : window).__bc3aa98a1624c420c64de6459784d4cc = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @fileOverview describes a ProgressiveDataSet object.
*
* This object serves as part of a series of components to handle the various aspects of autocomplete controls.
*/
var ProgressiveDataSet = _backbone2.default.Collection.extend({
/**
* A queryable set of data that optimises the speed at which responses can be provided.
*
* ProgressiveDataSet should be given a matcher function so that it may filter results for queries locally.
*
* ProgressiveDataSet can be given a remote query endpoint to fetch data from. Should a remote endpoint
* be provided, ProgressiveDataSet will leverage both client-side matching and query caching to reduce
* the number of times the remote source need be queried.
*
* @example
* var source = new ProgressiveDataSet([], {
* model: Backbone.Model.extend({ idAttribute: "username" }),
* queryEndpoint: "/jira/rest/latest/users",
* queryParamKey: "username",
* matcher: function(model, query) {
* return _.startsWith(model.get('username'), query);
* }
* });
* source.on('respond', doStuffWithMatchingResults);
* source.query('john');
*
* @property {String} value the latest query for which the ProgressiveDataSet is responding to.
* @property {Number} activeQueryCount the number of queries being run remotely.
*/
initialize: function initialize(models, options) {
options || (options = {});
if (options.matcher) {
this.matcher = options.matcher;
}
if (options.model) {
this.model = options.model; // Fixed in backbone 0.9.2
}
this._idAttribute = new this.model().idAttribute;
this._maxResults = options.maxResults || 5;
this._queryData = options.queryData || {};
this._queryParamKey = options.queryParamKey || 'q';
this._queryEndpoint = options.queryEndpoint || '';
this.value = null;
this.queryCache = {};
this.activeQueryCount = 0;
_underscore2.default.bindAll(this, 'query', 'respond');
},
url: function url() {
return this._queryEndpoint;
},
/**
* Sets and runs a query against the ProgressiveDataSet.
*
* Bind to ProgressiveDataSet's 'respond' event to receive the results that match the latest query.
*
* @param {String} query the query to run.
*/
query: function query(_query) {
var _this = this;
var remote;
var results;
this.value = _query;
results = this.getFilteredResults(_query);
this.respond(_query, results);
if (!_query || !this._queryEndpoint || this.hasQueryCache(_query) || !this.shouldGetMoreResults(results)) {
return;
}
remote = this.fetch(_query);
this.activeQueryCount++;
this.trigger('activity', { activity: true });
remote.always(function () {
_this.activeQueryCount--;
_this.trigger('activity', { activity: !!_this.activeQueryCount });
});
remote.done(function (resp, succ, xhr) {
_this.addQueryCache(_query, resp, xhr);
});
remote.done(function () {
_query = _this.value;
results = _this.getFilteredResults(_query);
_this.respond(_query, results);
});
},
/**
* Gets all the data that should be sent in a remote request for data.
* @param {String} query the value of the query to be run.
* @return {Object} the data to to be sent to the remote when querying it.
* @private
*/
getQueryData: function getQueryData(query) {
var params = _underscore2.default.isFunction(this._queryData) ? this._queryData(query) : this._queryData;
var data = _underscore2.default.extend({}, params);
data[this._queryParamKey] = query;
return data;
},
/**
* Get data from a remote source that matches the query, and add it to this ProgressiveDataSet's set.
*
* @param {String} query the value of the query to be run.
* @return {jQuery.Deferred} a deferred object representing the remote request.
*/
fetch: function fetch(query) {
var data = this.getQueryData(query);
// {add: true} for Backbone <= 0.9.2
// {update: true, remove: false} for Backbone >= 0.9.9
var params = { add: true, update: true, remove: false, data: data };
var remote = _backbone2.default.Collection.prototype.fetch.call(this, params);
return remote;
},
/**
* Triggers the 'respond' event on this ProgressiveDataSet for the given query and associated results.
*
* @param {String} query the query that was run
* @param {Array} results a set of results that matched the query.
* @return {Array} the results.
* @private
*/
respond: function respond(query, results) {
this.trigger('respond', {
query: query,
results: results
});
return results;
},
/**
* A hook-point to define a function that tests whether a model matches a query or not.
*
* This will be called by getFilteredResults in order to generate the list of results for a query.
*
* (For you java folks, it's essentially a predicate.)
*
* @param {Backbone.Model} item a model of the data to check for a match in.
* @param {String} query the value to test against the item.
* @returns {Boolean} true if the model matches the query, otherwise false.
* @function
*/
matcher: function matcher(item, query) {}, // eslint-disable-line no-unused-vars
/**
* Filters the set of data contained by the ProgressiveDataSet down to a smaller set of results.
*
* The set will only consist of Models that "match" the query -- i.e., only Models where
* a call to ProgressiveDataSet#matcher returns true.
*
* @param query {String} the value that results should match (according to the matcher function)
* @return {Array} A set of Backbone Models that match the query.
*/
getFilteredResults: function getFilteredResults(query) {
var results = [];
if (!query) {
return results;
}
results = this.filter(function (item) {
return !!this.matcher(item, query);
}, this);
if (this._maxResults) {
results = _underscore2.default.first(results, this._maxResults);
}
return results;
},
/**
* Store a response in the query cache for a given query.
*
* @param {String} query the value to cache a response for.
* @param {Object} response the data of the response from the server.
* @param {XMLHttpRequest} xhr
* @private
*/
addQueryCache: function addQueryCache(query, response, xhr) {
var cache = this.queryCache;
var results = this.parse(response, xhr);
cache[query] = _underscore2.default.pluck(results, this._idAttribute);
},
/**
* Check if there is a query cache entry for a given query.
*
* @param query the value to check in the cache
* @return {Boolean} true if the cache contains a response for the query, false otherwise.
*/
hasQueryCache: function hasQueryCache(query) {
return this.queryCache.hasOwnProperty(query);
},
/**
* Get the query cache entry for a given query.
*
* @param query the value to check in the cache
* @return {Object[]} an array of values representing the IDs of the models the response for this query contained.
*/
findQueryCache: function findQueryCache(query) {
return this.queryCache[query];
},
/**
*
* @param {Array} results the set of results we know about right now.
* @return {Boolean} true if the ProgressiveDataSet should look for more results.
* @private
*/
shouldGetMoreResults: function shouldGetMoreResults(results) {
return results.length < this._maxResults;
},
/**
*
* @note Changing this value will trigger ProgressiveDataSet#event:respond if there is a query.
* @param {Number} number how many results should the ProgressiveDataSet aim to retrieve for a query.
*/
setMaxResults: function setMaxResults(number) {
this._maxResults = number;
this.value && this.respond(this.value, this.getFilteredResults(this.value));
}
});
(0, _globalize2.default)('ProgressiveDataSet', ProgressiveDataSet);
exports.default = ProgressiveDataSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/query-input.js
(typeof window === 'undefined' ? global : window).__b12fa1032568f0d561e20a44ba70067a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var QueryInput = _backbone2.default.View.extend({
initialize: function initialize() {
_underscore2.default.bindAll(this, 'changed', 'val');
this._lastValue = this.val();
this.$el.bind('keyup focus', this.changed);
},
val: function val() {
return this.$el.val.apply(this.$el, arguments);
},
changed: function changed() {
if (this._lastValue !== this.val()) {
this.trigger('change', this.val());
this._lastValue = this.val();
}
}
});
(0, _globalize2.default)('QueryInput', QueryInput);
exports.default = QueryInput;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/class-names.js
(typeof window === 'undefined' ? global : window).__118527544b71a67b452649071c2ae422 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
NO_VALUE: 'aui-restfultable-editable-no-value',
NO_ENTRIES: 'aui-restfultable-no-entires',
RESTFUL_TABLE: 'aui-restfultable',
ROW: 'aui-restfultable-row',
READ_ONLY: 'aui-restfultable-readonly',
ACTIVE: 'aui-restfultable-active',
ALLOW_HOVER: 'aui-restfultable-allowhover',
FOCUSED: 'aui-restfultable-focused',
MOVEABLE: 'aui-restfultable-movable',
DISABLED: 'aui-restfultable-disabled',
SUBMIT: 'aui-restfultable-submit',
CANCEL: 'aui-restfultable-cancel',
EDIT_ROW: 'aui-restfultable-editrow',
CREATE: 'aui-restfultable-create',
DRAG_HANDLE: 'aui-restfultable-draghandle',
ORDER: 'aui-restfultable-order',
EDITABLE: 'aui-restfultable-editable',
ERROR: 'error',
DELETE: 'aui-restfultable-delete',
LOADING: 'loading'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-create-view.js
(typeof window === 'undefined' ? global : window).__8d19d0bdd704aa4d4cdc512b60f140de = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-edit-view.js
(typeof window === 'undefined' ? global : window).__12a9dc86ab66cc22f78cf62feba9dd64 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/custom-read-view.js
(typeof window === 'undefined' ? global : window).__dcca2723b4c5fed4e65377ddb5d32682 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.View;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/data-keys.js
(typeof window === 'undefined' ? global : window).__b1c52d9d29b34f181b3d58c504dec0ce = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
ENABLED_SUBMIT: 'enabledSubmit',
ROW_VIEW: 'RestfulTable_Row_View'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/serializetoobject.js
(typeof window === 'undefined' ? global : window).__aa7c1770abfd4c15bea861f799ad2035 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**
* Serializes form fields within the given element to a JSON object
*
* {
* fieldName: "fieldValue"
* }
*
* @returns {Object}
*/
jQuery.fn.serializeObject = function () {
var data = {};
this.find(":input:not(:button):not(:submit):not(:radio):not('select[multiple]')").each(function () {
if (this.name === "") {
return;
}
if (this.value === null) {
this.value = "";
}
data[this.name] = this.value.match(/^(tru|fals)e$/i) ?
this.value.toLowerCase() == "true" : this.value;
});
this.find("input:radio:checked").each(function(){
data[this.name] = this.value;
});
this.find("select[multiple]").each(function(){
var $select = jQuery(this),
val = $select.val();
if ($select.data("aui-ss")) {
if (val) {
data[this.name] = val[0];
} else {
data[this.name] = "";
}
} else {
if (val !== null) {
data[this.name] = val;
} else {
data[this.name] = [];
}
}
});
return data;
};
return module.exports;
}).call(this);
// src/js/aui/restful-table/events.js
(typeof window === 'undefined' ? global : window).__229915fcac0b1d518ba82b8dccf17af7 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
// AJS
REORDER_SUCCESS: 'RestfulTable.reorderSuccess',
ROW_ADDED: 'RestfulTable.rowAdded',
ROW_REMOVED: 'RestfulTable.rowRemoved',
EDIT_ROW: 'RestfulTable.switchedToEditMode',
SERVER_ERROR: 'RestfulTable.serverError',
// Backbone
CREATED: 'created',
UPDATED: 'updated',
FOCUS: 'focus',
BLUR: 'blur',
SUBMIT: 'submit',
SAVE: 'save',
MODAL: 'modal',
MODELESS: 'modeless',
CANCEL: 'cancel',
CONTENT_REFRESHED: 'contentRefreshed',
RENDER: 'render',
FINISHED_EDITING: 'finishedEditing',
VALIDATION_ERROR: 'validationError',
SUBMIT_STARTED: 'submitStarted',
SUBMIT_FINISHED: 'submitFinished',
INITIALIZED: 'initialized',
ROW_INITIALIZED: 'rowInitialized',
ROW_EDIT: 'editRow'
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/throbber.js
(typeof window === 'undefined' ? global : window).__491c5885a1dc4d2077d5e87e221aa590 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
return '<span class="aui-restfultable-throbber"></span>';
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/edit-row.js
(typeof window === 'undefined' ? global : window).__ea66711b82bb656ccc7223576cc606c7 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__aa7c1770abfd4c15bea861f799ad2035;
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
/**
* An abstract class that gives the required behaviour for the creating and editing entries. Extend this class and pass
* it as the {views.row} property of the options passed to RestfulTable in construction.
*/
exports.default = _backbone2.default.View.extend({
tagName: 'tr',
// delegate events
events: {
'focusin': '_focus',
'click': '_focus',
'keyup': '_handleKeyUpEvent'
},
/**
* @constructor
* @param {Object} options
*/
initialize: function initialize(options) {
this.$el = (0, _jquery2.default)(this.el);
// faster lookup
this._event = _events2.default;
this.classNames = _classNames2.default;
this.dataKeys = _dataKeys2.default;
this.columns = options.columns;
this.isCreateRow = options.isCreateRow;
this.allowReorder = options.allowReorder;
// Allow cancelling an edit with support for setting a new element.
this.events['click .' + this.classNames.CANCEL] = '_cancel';
this.delegateEvents();
if (options.isUpdateMode) {
this.isUpdateMode = true;
} else {
this._modelClass = options.model;
this.model = new this._modelClass();
}
this.fieldFocusSelector = options.fieldFocusSelector;
this.bind(this._event.CANCEL, function () {
this.disabled = true;
}).bind(this._event.SAVE, function (focusUpdated) {
if (!this.disabled) {
this.submit(focusUpdated);
}
}).bind(this._event.FOCUS, function (name) {
this.focus(name);
}).bind(this._event.BLUR, function () {
this.$el.removeClass(this.classNames.FOCUSED);
this.disable();
}).bind(this._event.SUBMIT_STARTED, function () {
this._submitStarted();
}).bind(this._event.SUBMIT_FINISHED, function () {
this._submitFinished();
});
},
/**
* Renders default cell contents
*
* @param data
*/
defaultColumnRenderer: function defaultColumnRenderer(data) {
if (data.allowEdit !== false) {
return (0, _jquery2.default)("<input type='text' />").addClass('text').attr({
name: data.name,
value: data.value
});
} else if (data.value) {
return document.createTextNode(data.value);
}
},
/**
* Renders drag handle
* @return jQuery
*/
renderDragHandle: function renderDragHandle() {
return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>';
},
/**
* Executes cancel event if ESC is pressed
*
* @param {Event} e
*/
_handleKeyUpEvent: function _handleKeyUpEvent(e) {
if (e.keyCode === 27) {
this.trigger(this._event.CANCEL);
}
},
/**
* Fires cancel event
*
* @param {Event} e
*
* @return EditRow
*/
_cancel: function _cancel(e) {
this.trigger(this._event.CANCEL);
e.preventDefault();
return this;
},
/**
* Disables events/fields and adds safe guard against double submitting
*
* @return EditRow
*/
_submitStarted: function _submitStarted() {
this.submitting = true;
this.showLoading().disable().delegateEvents({});
return this;
},
/**
* Enables events & fields
*
* @return EditRow
*/
_submitFinished: function _submitFinished() {
this.submitting = false;
this.hideLoading().enable().delegateEvents(this.events);
return this;
},
/**
* Handles dom focus event, by only focusing row if it isn't already
*
* @param {Event} e
*
* @return EditRow
*/
_focus: function _focus(e) {
if (!this.hasFocus()) {
this.trigger(this._event.FOCUS, e.target.name);
}
return this;
},
/**
* Returns true if row has focused class
*
* @return Boolean
*/
hasFocus: function hasFocus() {
return this.$el.hasClass(this.classNames.FOCUSED);
},
/**
* Focus specified field (by name or id - first argument), first field with an error or first field (DOM order)
*
* @param name
*
* @return EditRow
*/
focus: function focus(name) {
var $focus;
var $error;
this.enable();
if (name) {
$focus = this.$el.find(this.fieldFocusSelector(name));
} else {
$error = this.$el.find(this.classNames.ERROR + ':first');
if ($error.length === 0) {
$focus = this.$el.find(':input:text:first');
} else {
$focus = $error.parent().find(':input');
}
}
this.$el.addClass(this.classNames.FOCUSED);
$focus.focus().trigger('select');
return this;
},
/**
* Disables all fields
*
* @return EditRow
*/
disable: function disable() {
var $replacementSubmit;
var $submit;
// firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but
// one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack.
if (isFirefox) {
$submit = this.$el.find(':submit');
if ($submit.length) {
$replacementSubmit = (0, _jquery2.default)("<input type='submit' class='" + this.classNames.SUBMIT + "' />").addClass($submit.attr('class')).val($submit.val()).data(this.dataKeys.ENABLED_SUBMIT, $submit);
$submit.replaceWith($replacementSubmit);
}
}
this.$el.addClass(this.classNames.DISABLED).find(':submit').attr('disabled', 'disabled');
return this;
},
/**
* Enables all fields
*
* @return EditRow
*/
enable: function enable() {
var $placeholderSubmit;
var $submit;
// firefox does not allow you to submit a form if there are 2 or more submit buttons in a form, even if all but
// one is disabled. It also does not let you change the type="submit' to type="button". Therfore he lies the hack.
if (isFirefox) {
$placeholderSubmit = this.$el.find(this.classNames.SUBMIT);
$submit = $placeholderSubmit.data(this.dataKeys.ENABLED_SUBMIT);
if ($submit && $placeholderSubmit.length) {
$placeholderSubmit.replaceWith($submit);
}
}
this.$el.removeClass(this.classNames.DISABLED).find(':submit').removeAttr('disabled');
return this;
},
/**
* Shows loading indicator
*
* @return EditRow
*/
showLoading: function showLoading() {
this.$el.addClass(this.classNames.LOADING);
return this;
},
/**
* Hides loading indicator
*
* @return EditRow
*/
hideLoading: function hideLoading() {
this.$el.removeClass(this.classNames.LOADING);
return this;
},
/**
* If any of the fields have changed
*
* @return {Boolean}
*/
hasUpdates: function hasUpdates() {
return !!this.mapSubmitParams(this.serializeObject());
},
/**
* Serializes the view into model representation.
* Default implementation uses simple jQuery plugin to serialize form fields into object
*
* @return Object
*/
serializeObject: function serializeObject() {
var $el = this.$el;
return $el.serializeObject ? $el.serializeObject() : $el.serialize();
},
mapSubmitParams: function mapSubmitParams(params) {
return this.model.changedAttributes(params);
},
/**
* Handle submission of new entries and editing of old.
*
* @param {Boolean} focusUpdated - flag of whether to focus read-only view after succssful submission
*
* @return EditRow
*/
submit: function submit(focusUpdated) {
var instance = this;
var values;
// IE doesnt like it when the focused element is removed
if (document.activeElement !== window) {
(0, _jquery2.default)(document.activeElement).blur();
}
if (this.isUpdateMode) {
values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON
if (!values) {
return instance.trigger(instance._event.CANCEL);
}
} else {
this.model.clear();
values = this.mapSubmitParams(this.serializeObject()); // serialize form fields into JSON
}
this.trigger(this._event.SUBMIT_STARTED);
/* Attempt to add to server model. If fail delegate to createView to render errors etc. Otherwise,
add a new model to this._models and render a row to represent it. */
this.model.save(values, {
success: function success() {
if (instance.isUpdateMode) {
instance.trigger(instance._event.UPDATED, instance.model, focusUpdated);
} else {
instance.trigger(instance._event.CREATED, instance.model.toJSON());
instance.model = new instance._modelClass(); // reset
instance.render({ errors: {}, values: {} }); // pulls in instance's model for create row
instance.trigger(instance._event.FOCUS);
}
instance.trigger(instance._event.SUBMIT_FINISHED);
},
error: function error(model, data, xhr) {
if (xhr.status === 400) {
instance.renderErrors(data.errors);
instance.trigger(instance._event.VALIDATION_ERROR, data.errors);
}
instance.trigger(instance._event.SUBMIT_FINISHED);
},
silent: true
});
return this;
},
/**
* Render an error message
*
* @param msg
*
* @return {jQuery}
*/
renderError: function renderError(name, msg) {
return (0, _jquery2.default)('<div />').attr('data-field', name).addClass(this.classNames.ERROR).text(msg);
},
/**
* Render and append error messages. The property name will be matched to the input name to determine which cell to
* append the error message to. If this does not meet your needs please extend this method.
*
* @param errors
*/
renderErrors: function renderErrors(errors) {
var instance = this;
this.$('.' + this.classNames.ERROR).remove(); // avoid duplicates
if (errors) {
_jquery2.default.each(errors, function (name, msg) {
instance.$el.find("[name='" + name + "']").closest('td').append(instance.renderError(name, msg));
});
}
return this;
},
/**
* Handles rendering of row
*
* @param {Object} renderData
* ... {Object} vales - Values of fields
*/
render: function render(renderData) {
var instance = this;
this.$el.empty();
if (this.allowReorder) {
(0, _jquery2.default)('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el);
}
_jquery2.default.each(this.columns, function (i, column) {
var contents;
var $cell;
var value = renderData.values[column.id];
var args = [{ name: column.id, value: value, allowEdit: column.allowEdit }, renderData.values, instance.model];
if (value) {
instance.$el.attr('data-' + column.id, value); // helper for webdriver testing
}
if (instance.isCreateRow && column.createView) {
// TODO AUI-1058 - The row's model should be guaranteed to be in the correct state by this point.
contents = new column.createView({
model: instance.model
}).render(args[0]);
} else if (column.editView) {
contents = new column.editView({
model: instance.model
}).render(args[0]);
} else {
contents = instance.defaultColumnRenderer.apply(instance, args);
}
$cell = (0, _jquery2.default)('<td />');
if ((typeof contents === 'undefined' ? 'undefined' : _typeof(contents)) === 'object' && contents.done) {
contents.done(function (contents) {
$cell.append(contents);
});
} else {
$cell.append(contents);
}
if (column.styleClass) {
$cell.addClass(column.styleClass);
}
$cell.appendTo(instance.$el);
});
this.$el.append(this.renderOperations(renderData.update, renderData.values)) // add submit/cancel buttons
.addClass(this.classNames.ROW + ' ' + this.classNames.EDIT_ROW);
this.trigger(this._event.RENDER, this.$el, renderData.values);
this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]);
return this;
},
/**
* Gets markup for add/update and cancel buttons
*
* @param {Boolean} update
*/
renderOperations: function renderOperations(update) {
var $operations = (0, _jquery2.default)('<td class="aui-restfultable-operations" />');
if (update) {
$operations.append((0, _jquery2.default)('<input class="aui-button" type="submit" />').attr({
accesskey: this.submitAccessKey,
value: AJS.I18n.getText('aui.words.update')
})).append((0, _jquery2.default)('<a class="aui-button aui-button-link" href="#" />').addClass(this.classNames.CANCEL).text(AJS.I18n.getText('aui.words.cancel')).attr({
accesskey: this.cancelAccessKey
}));
} else {
$operations.append((0, _jquery2.default)('<input class="aui-button" type="submit" />').attr({
accesskey: this.submitAccessKey,
value: AJS.I18n.getText('aui.words.add')
}));
}
return $operations.add((0, _jquery2.default)('<td class="aui-restfultable-status" />').append((0, _throbber2.default)()));
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/entry-model.js
(typeof window === 'undefined' ? global : window).__085efe8598a83df67ac0ec7155e156ad = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _events = __a8a2a7bb852460b812b29dc7b998d456;
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _events2 = __229915fcac0b1d518ba82b8dccf17af7;
var _events3 = _interopRequireDefault(_events2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A class provided to fill some gaps with the out of the box Backbone.Model class. Most notiably the inability
* to send ONLY modified attributes back to the server.
*/
var EntryModel = _backbone2.default.Model.extend({
sync: function sync(method, model, options) {
var instance = this;
var oldError = options.error;
options.error = function (xhr) {
instance._serverErrorHandler(xhr, this);
if (oldError) {
oldError.apply(this, arguments);
}
};
return _backbone2.default.sync.apply(_backbone2.default, arguments);
},
/**
* Overrides default save handler to only save (send to server) attributes that have changed.
* Also provides some default error handling.
*
* @override
* @param attributes
* @param options
*/
save: function save(attributes, options) {
options = options || {};
var instance = this;
var Model;
var syncModel;
var error = options.error; // we override, so store original
var success = options.success;
// override error handler to provide some defaults
options.error = function (model, xhr) {
var data = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
// call original error handler
if (error) {
error.call(instance, instance, data, xhr);
}
};
// if it is a new model, we don't have to worry about updating only changed attributes because they are all new
if (this.isNew()) {
// call super
_backbone2.default.Model.prototype.save.call(this, attributes, options);
// only go to server if something has changed
} else if (attributes) {
// create temporary model
Model = EntryModel.extend({
url: this.url()
});
syncModel = new Model({
id: this.id
});
syncModel.save = _backbone2.default.Model.prototype.save;
options.success = function (model, xhr) {
// update original model with saved attributes
instance.clear().set(model.toJSON());
// call original success handler
if (success) {
success.call(instance, instance, xhr);
}
};
// update temporary model with the changed attributes
syncModel.save(attributes, options);
}
},
/**
* Destroys the model on the server. We need to override the default method as it does not support sending of
* query paramaters.
*
* @override
* @param options
* ... {function} success - Server success callback
* ... {function} error - Server error callback
* ... {object} data
*
* @return EntryModel
*/
destroy: function destroy(options) {
options = options || {};
var instance = this;
var url = this.url();
var data;
if (options.data) {
data = _jquery2.default.param(options.data);
}
if (data !== '') {
// we need to add to the url as the data param does not work for jQuery DELETE requests
url = url + '?' + data;
}
_jquery2.default.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
contentType: 'application/json',
success: function success(data) {
if (instance.collection) {
instance.collection.remove(instance);
}
if (options.success) {
options.success.call(instance, data);
}
},
error: function error(xhr) {
instance._serverErrorHandler(xhr, this);
if (options.error) {
options.error.call(instance, xhr);
}
}
});
return this;
},
/**
* A more complex lookup for changed attributes then default backbone one.
*
* @param attributes
*/
changedAttributes: function changedAttributes(attributes) {
var changed = {};
var current = this.toJSON();
_jquery2.default.each(attributes, function (name, value) {
if (!current[name]) {
if (typeof value === 'string') {
if (_jquery2.default.trim(value) !== '') {
changed[name] = value;
}
} else if (_jquery2.default.isArray(value)) {
if (value.length !== 0) {
changed[name] = value;
}
} else {
changed[name] = value;
}
} else if (current[name] && current[name] !== value) {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
if (!_underscore2.default.isEqual(value, current[name])) {
changed[name] = value;
}
} else {
changed[name] = value;
}
}
});
if (!_underscore2.default.isEmpty(changed)) {
this.addExpand(changed);
return changed;
}
},
/**
* Useful point to override if you always want to add an expand to your rest calls.
*
* @param changed attributes that have already changed
*/
addExpand: function addExpand(changed) {},
/**
* Throws a server error event unless user input validation error (status 400)
*
* @param xhr
*/
_serverErrorHandler: function _serverErrorHandler(xhr, ajaxOptions) {
var data;
if (xhr.status !== 400) {
data = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
(0, _events.triggerEvtForInst)(_events3.default.SERVER_ERROR, this, [data, xhr, ajaxOptions]);
}
},
/**
* Fetches values, with some generic error handling
*
* @override
* @param options
*/
fetch: function fetch(options) {
options = options || {};
// clear the model, so we do not merge the old with the new
this.clear();
// call super
_backbone2.default.Model.prototype.fetch.call(this, options);
}
});
exports.default = EntryModel;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table/row.js
(typeof window === 'undefined' ? global : window).__8da0d4434ee98ffecf6e34940b133dfd = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _dialog = __8d4634fbee21b3e51cb6c1e2a1adb5ff;
var dialog = _interopRequireWildcard(_dialog);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* An abstract class that gives the required behaviour for RestfulTable rows.
* Extend this class and pass it as the {views.row} property of the options passed to RestfulTable in construction.
*/
exports.default = _backbone2.default.View.extend({
tagName: 'tr',
events: {
'click .aui-restfultable-editable': 'edit'
},
initialize: function initialize(options) {
var instance = this;
options = options || {};
this._event = _events2.default;
this.classNames = _classNames2.default;
this.dataKeys = _dataKeys2.default;
this.columns = options.columns;
this.allowEdit = options.allowEdit;
this.allowDelete = options.allowDelete;
if (!this.events['click .aui-restfultable-editable']) {
throw new Error('It appears you have overridden the events property. To add events you will need to use' + 'a work around. https://github.com/documentcloud/backbone/issues/244');
}
this.index = options.index || 0;
this.deleteConfirmation = options.deleteConfirmation;
this.allowReorder = options.allowReorder;
this.$el = (0, _jquery2.default)(this.el);
this.bind(this._event.CANCEL, function () {
this.disabled = true;
}).bind(this._event.FOCUS, function (field) {
this.focus(field);
}).bind(this._event.BLUR, function () {
this.unfocus();
}).bind(this._event.MODAL, function () {
this.$el.addClass(this.classNames.ACTIVE);
}).bind(this._event.MODELESS, function () {
this.$el.removeClass(this.classNames.ACTIVE);
});
},
/**
* Renders drag handle
*
* @return jQuery
*/
renderDragHandle: function renderDragHandle() {
return '<span class="' + this.classNames.DRAG_HANDLE + '"></span></td>';
},
/**
* Renders default cell contents
*
* @param data
*
* @return {undefiend, String}
*/
defaultColumnRenderer: function defaultColumnRenderer(data) {
if (data.value) {
return document.createTextNode(data.value.toString());
}
},
/**
* Save changed attributes back to server and re-render
*
* @param attr
*
* @return {Row}
*/
sync: function sync(attr) {
var instance = this;
this.model.addExpand(attr);
this.showLoading();
this.model.save(attr, {
success: function success() {
instance.hideLoading().render();
instance.trigger(instance._event.UPDATED);
},
error: function error() {
instance.hideLoading();
}
});
return this;
},
/**
* Get model from server and re-render
*
* @return {Row}
*/
refresh: function refresh(_success, _error) {
var instance = this;
this.showLoading();
this.model.fetch({
success: function success() {
instance.hideLoading().render();
if (_success) {
_success.apply(this, arguments);
}
},
error: function error() {
instance.hideLoading();
if (_error) {
_error.apply(this, arguments);
}
}
});
return this;
},
/**
* Returns true if row has focused class
*
* @return Boolean
*/
hasFocus: function hasFocus() {
return this.$el.hasClass(this.classNames.FOCUSED);
},
/**
* Adds focus class (Item has been recently updated)
*
* @return Row
*/
focus: function focus() {
(0, _jquery2.default)(this.el).addClass(this.classNames.FOCUSED);
return this;
},
/**
* Removes focus class
*
* @return Row
*/
unfocus: function unfocus() {
(0, _jquery2.default)(this.el).removeClass(this.classNames.FOCUSED);
return this;
},
/**
* Adds loading class (to show server activity)
*
* @return Row
*/
showLoading: function showLoading() {
this.$el.addClass(this.classNames.LOADING);
return this;
},
/**
* Hides loading class (to show server activity)
*
* @return Row
*/
hideLoading: function hideLoading() {
this.$el.removeClass(this.classNames.LOADING);
return this;
},
/**
* Switches row into edit mode
*
* @param e
*/
edit: function edit(e) {
var field;
if ((0, _jquery2.default)(e.target).is('.' + this.classNames.EDITABLE)) {
field = (0, _jquery2.default)(e.target).attr('data-field-name');
} else {
field = (0, _jquery2.default)(e.target).closest('.' + this.classNames.EDITABLE).attr('data-field-name');
}
this.trigger(this._event.ROW_EDIT, field);
return this;
},
/**
* Can be overriden to add custom options.
*
* @returns {jQuery}
*/
renderOperations: function renderOperations() {
var instance = this;
if (this.allowDelete !== false) {
return (0, _jquery2.default)("<a href='#' class='aui-button' />").addClass(this.classNames.DELETE).text(AJS.I18n.getText('aui.words.delete')).click(function (e) {
e.preventDefault();
instance.destroy();
});
}
},
/**
* Removes entry from table.
*
* @returns {undefined}
*/
destroy: function destroy() {
if (this.deleteConfirmation) {
var popup = dialog.popup(400, 200, 'delete-entity-' + this.model.get('id'));
popup.element.html(this.deleteConfirmation(this.model.toJSON()));
popup.show();
popup.element.find('.cancel').click(function () {
popup.hide();
});
popup.element.find('form').submit(function (e) {
popup.hide();
this.model.destroy();
e.preventDefault();
}.bind(this));
} else {
this.model.destroy();
}
},
/**
* Renders a generic edit row. You probably want to override this in a sub class.
*
* @return Row
*/
render: function render() {
var instance = this;
var renderData = this.model.toJSON();
var $opsCell = (0, _jquery2.default)("<td class='aui-restfultable-operations' />").append(this.renderOperations({}, renderData));
var $throbberCell = (0, _jquery2.default)("<td class='aui-restfultable-status' />").append((0, _throbber2.default)());
// restore state
this.$el.removeClass(this.classNames.DISABLED + ' ' + this.classNames.FOCUSED + ' ' + this.classNames.LOADING + ' ' + this.classNames.EDIT_ROW).addClass(this.classNames.READ_ONLY).empty();
if (this.allowReorder) {
(0, _jquery2.default)('<td class="' + this.classNames.ORDER + '" />').append(this.renderDragHandle()).appendTo(instance.$el);
}
this.$el.attr('data-id', this.model.id); // helper for webdriver testing
_jquery2.default.each(this.columns, function (i, column) {
var contents;
var $cell = (0, _jquery2.default)('<td />');
var value = renderData[column.id];
var fieldName = column.fieldName || column.id;
var args = [{ name: fieldName, value: value, allowEdit: column.allowEdit }, renderData, instance.model];
if (value) {
instance.$el.attr('data-' + column.id, value); // helper for webdriver testing
}
if (column.readView) {
contents = new column.readView({
model: instance.model
}).render(args[0]);
} else {
contents = instance.defaultColumnRenderer.apply(instance, args);
}
if (instance.allowEdit !== false && column.allowEdit !== false) {
var $editableRegion = (0, _jquery2.default)('<span />').addClass(instance.classNames.EDITABLE).append('<span class="aui-icon aui-icon-small aui-iconfont-edit"></span>').append(contents).attr('data-field-name', fieldName);
$cell = (0, _jquery2.default)('<td />').append($editableRegion).appendTo(instance.$el);
if (!contents || _jquery2.default.trim(contents) == '') {
$cell.addClass(instance.classNames.NO_VALUE);
$editableRegion.html((0, _jquery2.default)('<em />').text(this.emptyText || AJS.I18n.getText('aui.enter.value')));
}
} else {
$cell.append(contents);
}
if (column.styleClass) {
$cell.addClass(column.styleClass);
}
$cell.appendTo(instance.$el);
});
this.$el.append($opsCell).append($throbberCell).addClass(this.classNames.ROW + ' ' + this.classNames.READ_ONLY);
this.trigger(this._event.RENDER, this.$el, renderData);
this.$el.trigger(this._event.CONTENT_REFRESHED, [this.$el]);
return this;
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/restful-table.js
(typeof window === 'undefined' ? global : window).__d9778e9495b7a4889d0567cf2b8e1182 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _log = __bbcdfae479e60b56b982bbcdcc7a0191;
var logger = _interopRequireWildcard(_log);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _classNames = __118527544b71a67b452649071c2ae422;
var _classNames2 = _interopRequireDefault(_classNames);
var _customCreateView = __8d19d0bdd704aa4d4cdc512b60f140de;
var _customCreateView2 = _interopRequireDefault(_customCreateView);
var _customEditView = __12a9dc86ab66cc22f78cf62feba9dd64;
var _customEditView2 = _interopRequireDefault(_customEditView);
var _customReadView = __dcca2723b4c5fed4e65377ddb5d32682;
var _customReadView2 = _interopRequireDefault(_customReadView);
var _dataKeys = __b1c52d9d29b34f181b3d58c504dec0ce;
var _dataKeys2 = _interopRequireDefault(_dataKeys);
var _editRow = __ea66711b82bb656ccc7223576cc606c7;
var _editRow2 = _interopRequireDefault(_editRow);
var _entryModel = __085efe8598a83df67ac0ec7155e156ad;
var _entryModel2 = _interopRequireDefault(_entryModel);
var _events = __229915fcac0b1d518ba82b8dccf17af7;
var _events2 = _interopRequireDefault(_events);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _i18n = __be3e01199078cdf5ded88dda6a8fbec9;
var _i18n2 = _interopRequireDefault(_i18n);
var _row = __8da0d4434ee98ffecf6e34940b133dfd;
var _row2 = _interopRequireDefault(_row);
var _throbber = __491c5885a1dc4d2077d5e87e221aa590;
var _throbber2 = _interopRequireDefault(_throbber);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Triggers a custom event on the document object
*
* @param {String} name - name of event
* @param {Array} args - args for event handler
*/
function triggerEvt(name, args) {
(0, _jquery2.default)(document).trigger(name, args);
}
/**
* Some generic error handling that fires event in multiple contexts
* - on document
* - on Instance
* - on document with prefixed id.
*
* @param evt
* @param inst
* @param args
*/
function triggerEvtForInst(evt, inst, args) {
(0, _jquery2.default)(inst).trigger(evt, args);
triggerEvt(evt, args);
if (inst.id) {
triggerEvt(inst.id + '_' + evt, args);
}
}
/**
* A table whose entries/rows can be retrieved, added and updated via REST (CRUD).
* It uses backbone.js to sync the table's state back to the server, avoiding page refreshes.
*
* @class RestfulTable
*/
var RestfulTable = _backbone2.default.View.extend({
/**
* @param {!Object} options
* ... {!Object} resources
* ... ... {(string|function(function(Array.<Object>)))} all - URL of REST resource OR function that retrieves all entities.
* ... ... {string} self - URL of REST resource to sync a single entities state (CRUD).
* ... {!(selector|Element|jQuery)} el - Table element or selector of the table element to populate.
* ... {!Array.<Object>} columns - Which properties of the entities to render. The id of a column maps to the property of an entity.
* ... {Object} views
* ... ... {RestfulTable.EditRow} editRow - Backbone view that renders the edit & create row. Your view MUST extend RestfulTable.EditRow.
* ... ... {RestfulTable.Row} row - Backbone view that renders the readonly row. Your view MUST extend RestfulTable.Row.
* ... {boolean} allowEdit - Is the table editable. If true, clicking row will switch it to edit state. Default true.
* ... {boolean} allowDelete - Can entries be removed from the table, default true.
* ... {boolean} allowCreate - Can new entries be added to the table, default true.
* ... {boolean} allowReorder - Can we drag rows to reorder them, default false.
* ... {boolean} autoFocus - Automatically set focus to first field on init, default false.
* ... {boolean} reverseOrder - Reverse the order of rows, default false.
* ... {boolean} silent - Do not trigger a "refresh" event on sort, default false.
* ... {String} id - The id for the table. This id will be used to fire events specific to this instance.
* ... {string} createPosition - If set to "bottom", place the create form at the bottom of the table instead of the top.
* ... {string} addPosition - If set to "bottom", add new rows at the bottom of the table instead of the top. If undefined, createPosition will be used to define where to add the new row.
* ... {string} noEntriesMsg - Text to display under the table header if it is empty, default empty.
* ... {string} loadingMsg - Text/HTML to display while loading, default "Loading".
* ... {string} submitAccessKey - Access key for submitting.
* ... {string} cancelAccessKey - Access key for canceling.
* ... {function(Object): (string|function(number, string): string)} deleteConfirmation - HTML to display in popup to confirm deletion.
* ... {function(string): (selector|jQuery|Element)} fieldFocusSelector - Element to focus on given a name.
* ... {EntryModel} model - Backbone model representing a row, default EntryModel.
* ... {Backbone.Collection} Collection - Backbone collection representing the entire table, default Backbone.Collection.
*/
initialize: function initialize(options) {
var instance = this;
// combine default and user options
instance.options = _jquery2.default.extend(true, instance._getDefaultOptions(options), options);
// Prefix events for this instance with this id.
instance.id = this.options.id;
// faster lookup
instance._event = _events2.default;
instance.classNames = _classNames2.default;
instance.dataKeys = _dataKeys2.default;
// shortcuts to popular elements
this.$table = (0, _jquery2.default)(options.el).addClass(this.classNames.RESTFUL_TABLE).addClass(this.classNames.ALLOW_HOVER).addClass('aui').addClass(instance.classNames.LOADING);
this.$table.wrapAll("<form class='aui' action='#' />");
this.$thead = (0, _jquery2.default)('<thead/>');
this.$theadRow = (0, _jquery2.default)('<tr />').appendTo(this.$thead);
this.$tbody = (0, _jquery2.default)('<tbody/>');
if (!this.$table.length) {
throw new Error('RestfulTable: Init failed! The table you have specified [' + this.$table.selector + '] cannot be found.');
}
if (!this.options.columns) {
throw new Error("RestfulTable: Init failed! You haven't provided any columns to render.");
}
// Let user know the table is loading
this.showGlobalLoading();
this.options.columns.forEach(function (column) {
var header = _jquery2.default.isFunction(column.header) ? column.header() : column.header;
if (typeof header === 'undefined') {
logger.warn('You have not specified [header] for column [' + column.id + ']. Using id for now...');
header = column.id;
}
instance.$theadRow.append('<th>' + header + '</th>');
});
// columns for submit buttons and loading indicator used when editing
instance.$theadRow.append('<th></th><th></th>');
// create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection)
this._models = this._createCollection();
// shortcut to the class we use to create rows
this._rowClass = this.options.views.row;
this.editRows = []; // keep track of rows that are being edited concurrently
this.$table.closest('form').submit(function (e) {
if (instance.focusedRow) {
// Delegates saving of row. See EditRow.submit
instance.focusedRow.trigger(instance._event.SAVE);
}
e.preventDefault();
});
if (this.options.allowReorder) {
// Add allowance for another cell to the <thead>
this.$theadRow.prepend('<th />');
// Allow drag and drop reordering of rows
this.$tbody.sortable({
handle: '.' + this.classNames.DRAG_HANDLE,
helper: function helper(e, elt) {
var helper = (0, _jquery2.default)('<div/>').attr('class', elt.attr('class')).addClass(instance.classNames.MOVEABLE);
elt.children().each(function (i) {
var $td = (0, _jquery2.default)(this);
// .offsetWidth/.outerWidth() is broken in webkit for tables, so we do .clientWidth + borders
// Need to coerce the border-left-width to an in because IE - http://bugs.jquery.com/ticket/10855
var borderLeft = parseInt(0 + $td.css('border-left-width'), 10);
var borderRight = parseInt(0 + $td.css('border-right-width'), 10);
var width = $td[0].clientWidth + borderLeft + borderRight;
helper.append((0, _jquery2.default)('<div/>').html($td.html()).attr('class', $td.attr('class')).width(width));
});
helper = (0, _jquery2.default)("<div class='aui-restfultable-readonly'/>").append(helper); // Basically just to get the styles.
helper.css({ left: elt.offset().left }); // To align with the other table rows, since we've locked scrolling on x.
helper.appendTo(document.body);
return helper;
},
start: function start(event, ui) {
var cachedHeight = ui.helper[0].clientHeight;
var $this = ui.placeholder.find('td');
// Make sure that when we start dragging widths do not change
ui.item.addClass(instance.classNames.MOVEABLE).children().each(function (i) {
(0, _jquery2.default)(this).width($this.eq(i).width());
});
// Create a <td> to add to the placeholder <tr> to inherit CSS styles.
var td = '<td colspan="' + instance.getColumnCount() + '"> </td>';
ui.placeholder.html(td).css({
height: cachedHeight,
visibility: 'visible'
});
// Stop hover effects etc from occuring as we move the mouse (while dragging) over other rows
instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODAL);
},
stop: function stop(event, ui) {
if ((0, _jquery2.default)(ui.item[0]).is(':visible')) {
ui.item.removeClass(instance.classNames.MOVEABLE).children().attr('style', '');
ui.placeholder.removeClass(instance.classNames.ROW);
// Return table to a normal state
instance.getRowFromElement(ui.item[0]).trigger(instance._event.MODELESS);
}
},
update: function update(event, ui) {
var context = {
row: instance.getRowFromElement(ui.item[0]),
item: ui.item,
nextItem: ui.item.next(),
prevItem: ui.item.prev()
};
instance.move(context);
},
axis: 'y',
delay: 0,
containment: 'document',
cursor: 'move',
scroll: true,
zIndex: 8000
});
// Prevent text selection while reordering.
this.$tbody.bind('selectstart mousedown', function (event) {
return !(0, _jquery2.default)(event.target).is('.' + instance.classNames.DRAG_HANDLE);
});
}
if (this.options.allowCreate !== false) {
// Create row responsible for adding new entries ...
this._createRow = new this.options.views.editRow({
columns: this.options.columns,
isCreateRow: true,
model: this.options.model.extend({
url: function url() {
return instance.options.resources.self;
}
}),
cancelAccessKey: this.options.cancelAccessKey,
submitAccessKey: this.options.submitAccessKey,
allowReorder: this.options.allowReorder,
fieldFocusSelector: this.options.fieldFocusSelector
}).bind(this._event.CREATED, function (values) {
if (instance.options.addPosition == undefined && instance.options.createPosition === 'bottom' || instance.options.addPosition === 'bottom') {
instance.addRow(values);
} else {
instance.addRow(values, 0);
}
}).bind(this._event.VALIDATION_ERROR, function () {
this.trigger(instance._event.FOCUS);
}).render({
errors: {},
values: {}
});
// ... and appends it as the first row
this.$create = (0, _jquery2.default)('<tbody class="' + this.classNames.CREATE + '" />').append(this._createRow.el);
// Manage which row has focus
this._applyFocusCoordinator(this._createRow);
// focus create row
this._createRow.trigger(this._event.FOCUS);
}
// when a model is removed from the collection, remove it from the viewport also
this._models.bind('remove', function (model) {
instance.getRows().forEach(function (row) {
if (row.model === model) {
if (row.hasFocus() && instance._createRow) {
instance._createRow.trigger(instance._event.FOCUS);
}
instance.removeRow(row);
}
});
});
this.fetchInitialResources();
},
fetchInitialResources: function fetchInitialResources() {
var instance = this;
if (_jquery2.default.isFunction(this.options.resources.all)) {
this.options.resources.all(function (entries) {
instance.populate(entries);
});
} else {
_jquery2.default.get(this.options.resources.all, function (entries) {
instance.populate(entries);
});
}
},
move: function move(context) {
var instance = this;
var createRequest = function createRequest(afterElement) {
if (!afterElement.length) {
return {
position: 'First'
};
} else {
var afterModel = instance.getRowFromElement(afterElement).model;
return {
after: afterModel.url()
};
}
};
if (context.row) {
var data = instance.options.reverseOrder ? createRequest(context.nextItem) : createRequest(context.prevItem);
_jquery2.default.ajax({
url: context.row.model.url() + '/move',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
complete: function complete() {
// hides loading indicator (spinner)
context.row.hideLoading();
},
success: function success(xhr) {
triggerEvtForInst(instance._event.REORDER_SUCCESS, instance, [xhr]);
},
error: function error(xhr) {
var responseData = _jquery2.default.parseJSON(xhr.responseText || xhr.data);
triggerEvtForInst(instance._event.SERVER_ERROR, instance, [responseData, xhr, this]);
}
});
// shows loading indicator (spinner)
context.row.showLoading();
}
},
_createCollection: function _createCollection() {
var instance = this;
// create a new Backbone collection to represent rows (http://documentcloud.github.com/backbone/#Collection)
var RowsAwareCollection = this.options.Collection.extend({
// Force the collection to re-sort itself. You don't need to call this under normal
// circumstances, as the set will maintain sort order as each item is added.
sort: function sort(options) {
options || (options = {});
if (!this.comparator) {
throw new Error('Cannot sort a set without a comparator');
}
this.tableRows = instance.getRows();
this.models = this.sortBy(this.comparator);
this.tableRows = undefined;
if (!options.silent) {
this.trigger('refresh', this, options);
}
return this;
},
remove: function remove(models, options) {
this.tableRows = instance.getRows();
_backbone2.default.Collection.prototype.remove.apply(this, arguments);
this.tableRows = undefined;
return this;
}
});
return new RowsAwareCollection([], {
comparator: function comparator(row) {
// sort models in collection based on dom ordering
var index;
var currentTableRows = this.tableRows !== undefined ? this.tableRows : instance.getRows();
currentTableRows.some(function (item, i) {
if (item.model.id === row.id) {
index = i;
return true;
}
});
return index;
}
});
},
/**
* Refreshes table with entries
*
* @param entries
*/
populate: function populate(entries) {
if (this.options.reverseOrder) {
entries.reverse();
}
this.hideGlobalLoading();
if (entries && entries.length) {
// Empty the models collection
this._models.reset([], { silent: true });
// Add all the entries to collection and render them
this.renderRows(entries);
// show message to user if we have no entries
if (this.isEmpty()) {
this.showNoEntriesMsg();
}
} else {
this.showNoEntriesMsg();
}
// Ok, lets let everyone know that we are done...
this.$table.append(this.$thead);
if (this.options.createPosition === 'bottom') {
this.$table.append(this.$tbody).append(this.$create);
} else {
this.$table.append(this.$create).append(this.$tbody);
}
this.$table.removeClass(this.classNames.LOADING).trigger(this._event.INITIALIZED, [this]);
triggerEvtForInst(this._event.INITIALIZED, this, [this]);
if (this.options.autoFocus) {
this.$table.find(':input:text:first').focus(); // set focus to first field
}
},
/**
* Shows loading indicator and text
*
* @return {RestfulTable}
*/
showGlobalLoading: function showGlobalLoading() {
if (!this.$loading) {
this.$loading = (0, _jquery2.default)('<div class="aui-restfultable-init">' + (0, _throbber2.default)() + '<span class="aui-restfultable-loading">' + this.options.loadingMsg + '</span></div>');
}
if (!this.$loading.is(':visible')) {
this.$loading.insertAfter(this.$table);
}
return this;
},
/**
* Hides loading indicator and text
* @return {RestfulTable}
*/
hideGlobalLoading: function hideGlobalLoading() {
if (this.$loading) {
this.$loading.remove();
}
return this;
},
/**
* Adds row to collection and renders it
*
* @param {Object} values
* @param {number} index
* @return {RestfulTable}
*/
addRow: function addRow(values, index) {
var view;
var model;
if (!values.id) {
throw new Error('RestfulTable.addRow: to add a row values object must contain an id. ' + 'Maybe you are not returning it from your restend point?' + 'Recieved:' + JSON.stringify(values));
}
model = new this.options.model(values);
view = this._renderRow(model, index);
this._models.add(model);
this.removeNoEntriesMsg();
// Let everyone know we added a row
triggerEvtForInst(this._event.ROW_ADDED, this, [view, this]);
return this;
},
/**
* Provided a view, removes it from display and backbone collection
*
* @param row {Row} The row to remove.
*/
removeRow: function removeRow(row) {
this._models.remove(row.model);
row.remove();
if (this.isEmpty()) {
this.showNoEntriesMsg();
}
// Let everyone know we removed a row
triggerEvtForInst(this._event.ROW_REMOVED, this, [row, this]);
},
/**
* Is there any entries in the table
*
* @return {Boolean}
*/
isEmpty: function isEmpty() {
return this._models.length === 0;
},
/**
* Gets all models
*
* @return {Backbone.Collection}
*/
getModels: function getModels() {
return this._models;
},
/**
* Gets table body
*
* @return {jQuery}
*/
getTable: function getTable() {
return this.$table;
},
/**
* Gets table body
*
* @return {jQuery}
*/
getTableBody: function getTableBody() {
return this.$tbody;
},
/**
* Gets create Row
*
* @return {EditRow}
*/
getCreateRow: function getCreateRow() {
return this._createRow;
},
/**
* Gets the number of table columns, accounting for the number of
* additional columns added by RestfulTable itself
* (such as the drag handle column, buttons and actions columns)
*
* @return {Number}
*/
getColumnCount: function getColumnCount() {
var staticFieldCount = 2; // accounts for the columns allocated to submit buttons and loading indicator
if (this.allowReorder) {
++staticFieldCount;
}
return this.options.columns.length + staticFieldCount;
},
/**
* Get the Row that corresponds to the given <tr> element.
*
* @param {HTMLElement} tr
*
* @return {Row}
*/
getRowFromElement: function getRowFromElement(tr) {
return (0, _jquery2.default)(tr).data(this.dataKeys.ROW_VIEW);
},
/**
* Shows message {options.noEntriesMsg} to the user if there are no entries
*
* @return {RestfulTable}
*/
showNoEntriesMsg: function showNoEntriesMsg() {
if (this.$noEntries) {
this.$noEntries.remove();
}
this.$noEntries = (0, _jquery2.default)('<tr>').addClass(this.classNames.NO_ENTRIES).append((0, _jquery2.default)('<td>').attr('colspan', this.getColumnCount()).text(this.options.noEntriesMsg)).appendTo(this.$tbody);
return this;
},
/**
* Removes message {options.noEntriesMsg} to the user if there ARE entries
*
* @return {RestfulTable}
*/
removeNoEntriesMsg: function removeNoEntriesMsg() {
if (this.$noEntries && this._models.length > 0) {
this.$noEntries.remove();
}
return this;
},
/**
* Gets the Row from their associated <tr> elements
*
* @return {Array}
*/
getRows: function getRows() {
var instance = this;
var views = [];
this.$tbody.find('.' + this.classNames.READ_ONLY).each(function () {
var $row = (0, _jquery2.default)(this);
var view = $row.data(instance.dataKeys.ROW_VIEW);
if (view) {
views.push(view);
}
});
return views;
},
/**
* Appends entry to end or specified index of table
*
* @param {EntryModel} model
* @param index
*
* @return {jQuery}
*/
_renderRow: function _renderRow(model, index) {
var instance = this;
var $rows = this.$tbody.find('.' + this.classNames.READ_ONLY);
var $row;
var view;
view = new this._rowClass({
model: model,
columns: this.options.columns,
allowEdit: this.options.allowEdit,
allowDelete: this.options.allowDelete,
allowReorder: this.options.allowReorder,
deleteConfirmation: this.options.deleteConfirmation
});
this.removeNoEntriesMsg();
view.bind(this._event.ROW_EDIT, function (field) {
triggerEvtForInst(this._event.EDIT_ROW, {}, [this, instance]);
instance.edit(this, field);
});
$row = view.render().$el;
if (index !== -1) {
if (typeof index === 'number' && $rows.length !== 0) {
$row.insertBefore($rows[index]);
} else {
this.$tbody.append($row);
}
}
$row.data(this.dataKeys.ROW_VIEW, view);
// deactivate all rows - used in the cases, such as opening a dropdown where you do not want the table editable
// or any interactions
view.bind(this._event.MODAL, function () {
instance.$table.removeClass(instance.classNames.ALLOW_HOVER);
instance.$tbody.sortable('disable');
instance.getRows().forEach(function (row) {
if (!instance.isRowBeingEdited(row)) {
row.delegateEvents({}); // clear all events
}
});
});
// activate all rows - used in the cases, such as opening a dropdown where you do not want the table editable
// or any interactions
view.bind(this._event.MODELESS, function () {
instance.$table.addClass(instance.classNames.ALLOW_HOVER);
instance.$tbody.sortable('enable');
instance.getRows().forEach(function (row) {
if (!instance.isRowBeingEdited(row)) {
row.delegateEvents(); // rebind all events
}
});
});
// ensure that when this row is focused no other are
this._applyFocusCoordinator(view);
this.trigger(this._event.ROW_INITIALIZED, view);
return view;
},
/**
* Returns if the row is edit mode or note.
*
* @param {Row} row Read-only row to check if being edited.
*
* @return {Boolean}
*/
isRowBeingEdited: function isRowBeingEdited(row) {
var isBeingEdited = false;
this.editRows.some(function (editRow) {
if (editRow.el === row.el) {
isBeingEdited = true;
return true;
}
});
return isBeingEdited;
},
/**
* Ensures that when supplied view is focused no others are
*
* @param {Backbone.View} view
* @return {RestfulTable}
*/
_applyFocusCoordinator: function _applyFocusCoordinator(view) {
var instance = this;
if (!view.hasFocusBound) {
view.hasFocusBound = true;
view.bind(this._event.FOCUS, function () {
if (instance.focusedRow && instance.focusedRow !== view) {
instance.focusedRow.trigger(instance._event.BLUR);
}
instance.focusedRow = view;
if (view instanceof _row2.default && instance._createRow) {
instance._createRow.enable();
}
});
}
return this;
},
/**
* Remove specified row from collection holding rows being concurrently edited
*
* @param {EditRow} editView
*
* @return {RestfulTable}
*/
_removeEditRow: function _removeEditRow(editView) {
var index = _jquery2.default.inArray(editView, this.editRows);
this.editRows.splice(index, 1);
return this;
},
/**
* Focuses last row still being edited or create row (if it exists)
*
* @return {RestfulTable}
*/
_shiftFocusAfterEdit: function _shiftFocusAfterEdit() {
if (this.editRows.length > 0) {
this.editRows[this.editRows.length - 1].trigger(this._event.FOCUS);
} else if (this._createRow) {
this._createRow.trigger(this._event.FOCUS);
}
return this;
},
/**
* Evaluate if we save row when we blur. We can only do this when there is one row being edited at a time, otherwise
* it causes an infinite loop JRADEV-5325
*
* @return {boolean}
*/
_saveEditRowOnBlur: function _saveEditRowOnBlur() {
return this.editRows.length <= 1;
},
/**
* Dismisses rows being edited concurrently that have no changes
*/
dismissEditRows: function dismissEditRows() {
this.editRows.forEach(function (editRow) {
if (!editRow.hasUpdates()) {
editRow.trigger(this._event.FINISHED_EDITING);
}
}, this);
},
/**
* Converts readonly row to editable view
*
* @param {Backbone.View} row
* @param {String} field - field name to focus
* @return {Backbone.View} editRow
*/
edit: function edit(row, field) {
var instance = this;
var editRow = new this.options.views.editRow({
el: row.el,
columns: this.options.columns,
isUpdateMode: true,
allowReorder: this.options.allowReorder,
fieldFocusSelector: this.options.fieldFocusSelector,
model: row.model,
cancelAccessKey: this.options.cancelAccessKey,
submitAccessKey: this.options.submitAccessKey
});
var values = row.model.toJSON();
values.update = true;
editRow.render({
errors: {},
update: true,
values: values
}).bind(instance._event.UPDATED, function (model, focusUpdated) {
instance._removeEditRow(this);
this.unbind();
row.render().delegateEvents(); // render and rebind events
row.trigger(instance._event.UPDATED); // trigger blur fade out
if (focusUpdated !== false) {
instance._shiftFocusAfterEdit();
}
}).bind(instance._event.VALIDATION_ERROR, function () {
this.trigger(instance._event.FOCUS);
}).bind(instance._event.FINISHED_EDITING, function () {
instance._removeEditRow(this);
row.render().delegateEvents();
this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired
}).bind(instance._event.CANCEL, function () {
instance._removeEditRow(this);
this.unbind(); // avoid any other updating, blurring, finished editing, cancel events being fired
row.render().delegateEvents(); // render and rebind events
instance._shiftFocusAfterEdit();
}).bind(instance._event.BLUR, function () {
instance.dismissEditRows(); // dismiss edit rows that have no changes
if (instance._saveEditRowOnBlur()) {
this.trigger(instance._event.SAVE, false); // save row, which if successful will call the updated event above
}
});
// Ensure that if focus is pulled to another row, we blur the edit row
this._applyFocusCoordinator(editRow);
// focus edit row, which has the flow on effect of blurring current focused row
editRow.trigger(instance._event.FOCUS, field);
// disables form fields
if (instance._createRow) {
instance._createRow.disable();
}
this.editRows.push(editRow);
return editRow;
},
/**
* Renders all specified rows
*
* @param rows {Array<Backbone.Model>} array of objects describing Backbone.Model's to render
* @return {RestfulTable}
*/
renderRows: function renderRows() {
var _this = this;
var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var comparator = this._models.comparator;
var els = [];
this._models.comparator = undefined; // disable temporarily, assume rows are sorted
var models = rows.map(function (row) {
var model = new _this.options.model(row);
els.push(_this._renderRow(model, -1).el);
return model;
});
this._models.add(models, { silent: true });
this._models.comparator = comparator;
this.removeNoEntriesMsg();
this.$tbody.append(els);
return this;
},
/**
* Gets default options
*
* @param {Object} options
*/
_getDefaultOptions: function _getDefaultOptions(options) {
return {
model: options.model || _entryModel2.default,
allowEdit: true,
views: {
editRow: _editRow2.default,
row: _row2.default
},
Collection: _backbone2.default.Collection.extend({
url: options.resources.self,
model: options.model || _entryModel2.default
}),
allowReorder: false,
fieldFocusSelector: function fieldFocusSelector(name) {
return ':input[name=' + name + '], #' + name;
},
loadingMsg: options.loadingMsg || AJS.I18n.getText('aui.words.loading')
};
}
});
RestfulTable.ClassNames = _classNames2.default;
RestfulTable.CustomCreateView = _customCreateView2.default;
RestfulTable.CustomEditView = _customEditView2.default;
RestfulTable.CustomReadView = _customReadView2.default;
RestfulTable.DataKeys = _dataKeys2.default;
RestfulTable.EditRow = _editRow2.default;
RestfulTable.EntryModel = _entryModel2.default;
RestfulTable.Events = _events2.default;
RestfulTable.Row = _row2.default;
RestfulTable.Throbber = _throbber2.default;
(0, _globalize2.default)('RestfulTable', RestfulTable);
exports.default = RestfulTable;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/result-set.js
(typeof window === 'undefined' ? global : window).__e9e07e92893b0b7f9f3e6e2ffe018c96 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ResultSet = _backbone2.default.Model.extend({
initialize: function initialize(options) {
this.set('active', null, { silent: true });
this.collection = new _backbone2.default.Collection();
this.collection.bind('reset', this.setActive, this);
this.source = options.source;
this.source.bind('respond', this.process, this);
},
url: false,
process: function process(response) {
this.set('query', response.query);
this.collection.reset(response.results);
this.set('length', response.results.length);
this.trigger('update', this);
},
setActive: function setActive() {
var id = arguments[0] instanceof _backbone2.default.Collection ? false : arguments[0];
var model = id ? this.collection.get(id) : this.collection.first();
this.set('active', model || null);
return this.get('active');
},
next: function next() {
var current = this.collection.indexOf(this.get('active'));
var i = (current + 1) % this.get('length');
var next = this.collection.at(i);
return this.setActive(next && next.id);
},
prev: function prev() {
var current = this.collection.indexOf(this.get('active'));
var i = (current === 0 ? this.get('length') : current) - 1;
var prev = this.collection.at(i);
return this.setActive(prev && prev.id);
},
each: function each() {
return this.collection.each.apply(this.collection, arguments);
}
});
(0, _globalize2.default)('ResultSet', ResultSet);
exports.default = ResultSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/results-list.js
(typeof window === 'undefined' ? global : window).__1e2a7fafeebd870fc623ea9cf84e84eb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _underscore = __e622bd457fe11fb15e9fb452ca3772d0;
var _underscore2 = _interopRequireDefault(_underscore);
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _resultSet = __e9e07e92893b0b7f9f3e6e2ffe018c96;
var _resultSet2 = _interopRequireDefault(_resultSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ResultsList = _backbone2.default.View.extend({
events: {
'click [data-id]': 'setSelection'
},
initialize: function initialize(options) {
if (!this.model) {
this.model = new _resultSet2.default({ source: options.source });
}
if (!(this.model instanceof _resultSet2.default)) {
throw new Error('model must be set to a ResultSet');
}
this.model.bind('update', this.process, this);
this.render = _underscore2.default.wrap(this.render, function (func) {
this.trigger('rendering');
func.apply(this, arguments);
this.trigger('rendered');
});
},
process: function process() {
if (!this._shouldShow(this.model.get('query'))) {
return;
}
this.show();
},
render: function render() {
var ul = _backbone2.default.$('<ul/>');
this.model.each(function (model) {
var li = _backbone2.default.$('<li/>').attr('data-id', model.id).html(this.renderItem(model)).appendTo(ul);
}, this);
this.$el.html(ul);
return this;
},
renderItem: function renderItem() {
return;
},
setSelection: function setSelection(event) {
var id = event.target.getAttribute('data-id');
var selected = this.model.setActive(id);
this.trigger('selected', selected);
},
show: function show() {
this.lastQuery = this.model.get('query');
this._hiddenQuery = null;
this.render();
this.$el.show();
},
hide: function hide() {
this.$el.hide();
this._hiddenQuery = this.lastQuery;
},
size: function size() {
return this.model.get('length');
},
_shouldShow: function _shouldShow(query) {
return query === '' || !(this._hiddenQuery && this._hiddenQuery === query);
}
});
(0, _globalize2.default)('ResultsList', ResultsList);
exports.default = ResultsList;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/option.js
(typeof window === 'undefined' ? global : window).__9635740841d5de6fc1070a95b24a5161 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _escapeHtml = __8106a911fd0030e07f16b2767ac9f548;
var _escapeHtml2 = _interopRequireDefault(_escapeHtml);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = (0, _skate2.default)('aui-option', {
created: function created(element) {
Object.defineProperty(element, 'value', {
get: function get() {
return element.getAttribute('value') || (0, _escapeHtml2.default)(this.textContent);
},
set: function set(value) {
element.setAttribute('value', value);
}
});
},
prototype: {
serialize: function serialize() {
var json = {};
if (this.hasAttribute('img-src')) {
json['img-src'] = this.getAttribute('img-src');
}
json.value = this.value;
json.label = (0, _escapeHtml2.default)(this.textContent);
return json;
}
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestion-model.js
(typeof window === 'undefined' ? global : window).__2b6275390f681ad9cb41cbbc6712cb3a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _backbone = __07cdfb826f754040b351a0110fde6536;
var _backbone2 = _interopRequireDefault(_backbone);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _backbone2.default.Model.extend({
idAttribute: 'label',
getLabel: function getLabel() {
return this.get('label') || this.get('value');
}
});
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestions-model.js
(typeof window === 'undefined' ? global : window).__1288846ede15fbf7e700f826a71a60c0 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function SuggestionsModel() {
this._suggestions = [];
this._activeIndex = -1;
}
SuggestionsModel.prototype = {
onChange: function onChange() {},
onHighlightChange: function onHighlightChange() {},
get: function get(index) {
return this._suggestions[index];
},
set: function set(suggestions) {
var oldSuggestions = this._suggestions;
this._suggestions = suggestions || [];
this.onChange(oldSuggestions);
return this;
},
getNumberOfResults: function getNumberOfResults() {
return this._suggestions.length;
},
setHighlighted: function setHighlighted(toHighlight) {
if (toHighlight) {
for (var i = 0; i < this._suggestions.length; i++) {
if (this._suggestions[i].id === toHighlight.id) {
this.highlight(i);
}
}
}
return this;
},
highlight: function highlight(index) {
this._activeIndex = index;
this.onHighlightChange();
return this;
},
highlightPrevious: function highlightPrevious() {
var current = this._activeIndex;
var previousActiveIndex = current === 0 ? current : current - 1;
this.highlight(previousActiveIndex);
return this;
},
highlightNext: function highlightNext() {
var current = this._activeIndex;
var nextActiveIndex = current === this._suggestions.length - 1 ? current : current + 1;
this.highlight(nextActiveIndex);
return this;
},
highlighted: function highlighted() {
return this.get(this._activeIndex);
},
highlightedIndex: function highlightedIndex() {
return this._activeIndex;
}
};
exports.default = SuggestionsModel;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/suggestions-view.js
(typeof window === 'undefined' ? global : window).__93aa20046b4aad30a18c95a624221d6b = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__be3e01199078cdf5ded88dda6a8fbec9;
var _alignment = __640a50a417a578824aa17827db8c9d2f;
var _alignment2 = _interopRequireDefault(_alignment);
var _layer = __06224e18e744dc8a44794ab29f247385;
var _layer2 = _interopRequireDefault(_layer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateListItemID(listId, index) {
return listId + '-' + index;
}
/**
*
* @param view SuggestionsView
*/
function enableAlignment(view) {
if (view.anchor && !view.auiAlignment) {
view.auiAlignment = new _alignment2.default(view.el, view.anchor);
}
if (view.auiAlignment) {
view.auiAlignment.enable();
}
}
function destroyAlignment(view) {
if (view.auiAlignment) {
view.auiAlignment.destroy();
}
}
function matchWidth(view) {
(0, _jquery2.default)(view.el).css('min-width', (0, _jquery2.default)(view.anchor).outerWidth());
}
function SuggestionsView(element, anchor) {
this.el = element;
this.anchor = anchor;
}
function clearActive(element) {
(0, _jquery2.default)(element).find('.aui-select-active').removeClass('aui-select-active');
}
SuggestionsView.prototype = {
render: function render(suggestions, currentLength, listId) {
this.currListId = listId;
var html = '';
// Do nothing if we have no new suggestions, otherwise append anything else we find.
if (suggestions.length) {
var i = currentLength;
suggestions.forEach(function (sugg) {
var label = sugg.getLabel();
var imageSrc = sugg.get('img-src');
var image = imageSrc ? '<img src="' + imageSrc + '"/>' : '';
var newValueText = sugg.get('new-value') ? ' (<em>' + AJS.I18n.getText('aui.select.new.value') + '</em>)' : '';
html += '<li role="option" class="aui-select-suggestion" id="' + generateListItemID(listId, i) + '">' + image + label + newValueText + '</li>';
i++;
});
// If the old suggestions were empty, a <li> of 'No suggestions' will be appended, we need to remove it
if (currentLength) {
this.el.querySelector('ul').innerHTML += html;
} else {
this.el.querySelector('ul').innerHTML = html;
}
} else if (!currentLength) {
this.el.querySelector('ul').innerHTML = '<li role="option" class="aui-select-no-suggestions">' + AJS.I18n.getText('aui.select.no.suggestions') + '</li>';
}
return this;
},
setActive: function setActive(active) {
clearActive(this.el);
(0, _jquery2.default)(this.el).find('#' + generateListItemID(this.currListId, active)).addClass('aui-select-active');
},
getActive: function getActive() {
return this.el.querySelector('.aui-select-active');
},
show: function show() {
matchWidth(this);
(0, _layer2.default)(this.el).show();
enableAlignment(this);
},
hide: function hide() {
clearActive(this.el);
(0, _layer2.default)(this.el).hide();
destroyAlignment(this);
},
isVisible: function isVisible() {
return (0, _jquery2.default)(this.el).is(':visible');
}
};
exports.default = SuggestionsView;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/select/template.js
(typeof window === 'undefined' ? global : window).__e2c1f657d183d1b538d81a87ba0b4760 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = (0, _skatejsTemplateHtml2.default)('\n <input type="text" class="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false">\n <select></select>\n <datalist>\n <content select="aui-option"></content>\n </datalist>\n <button class="aui-button" role="button" tabindex="-1" type="button"></button>\n <div class="aui-popover" role="listbox" data-aui-alignment="bottom left">\n <ul class="aui-optionlist" role="presentation"></ul>\n </div>\n <div class="aui-select-status assistive" aria-live="polite" role="status"></div>\n');
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/select.js
(typeof window === 'undefined' ? global : window).__c7e0d50b6a65bf58a28e1b310881043e = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__133851082a1337b5710e5a2aa98258e9;
__be3e01199078cdf5ded88dda6a8fbec9;
__313e15322266d7b6cc6ffb039891d9ce;
var _option = __9635740841d5de6fc1070a95b24a5161;
var _option2 = _interopRequireDefault(_option);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _customEvent = __16bf5f1d761138a726209288b7afb338;
var _customEvent2 = _interopRequireDefault(_customEvent);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _progressiveDataSet = __bc3aa98a1624c420c64de6459784d4cc;
var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _state = __6b822d4c87bd59d8adf46df64b0f24c7;
var _state2 = _interopRequireDefault(_state);
var _suggestionModel = __2b6275390f681ad9cb41cbbc6712cb3a;
var _suggestionModel2 = _interopRequireDefault(_suggestionModel);
var _suggestionsModel = __1288846ede15fbf7e700f826a71a60c0;
var _suggestionsModel2 = _interopRequireDefault(_suggestionsModel);
var _suggestionsView = __93aa20046b4aad30a18c95a624221d6b;
var _suggestionsView2 = _interopRequireDefault(_suggestionsView);
var _template = __e2c1f657d183d1b538d81a87ba0b4760;
var _template2 = _interopRequireDefault(_template);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DESELECTED = -1;
var NO_HIGHLIGHT = -1;
var DEFAULT_SS_PDS_SIZE = 20;
function clearElementImage(element) {
element._input.removeAttribute('style');
(0, _jquery2.default)(element._input).removeClass('aui-select-has-inline-image');
}
function deselect(element) {
element._select.selectedIndex = DESELECTED;
clearElementImage(element);
}
function hasResults(element) {
return element._suggestionModel.getNumberOfResults();
}
function waitForAssistive(callback) {
setTimeout(callback, 50);
}
function setBusyState(element) {
if (!element._button.isBusy()) {
element._button.busy();
element._input.setAttribute('aria-busy', 'true');
element._dropdown.setAttribute('aria-busy', 'true');
}
}
function setIdleState(element) {
element._button.idle();
element._input.setAttribute('aria-busy', 'false');
element._dropdown.setAttribute('aria-busy', 'false');
}
function matchPrefix(model, query) {
var value = model.get('label').toLowerCase();
return value.indexOf(query.toLowerCase()) === 0;
}
function hideDropdown(element) {
element._suggestionsView.hide();
element._input.setAttribute('aria-expanded', 'false');
}
function setInitialVisualState(element) {
var initialHighlightedItem = hasResults(element) ? 0 : NO_HIGHLIGHT;
element._suggestionModel.highlight(initialHighlightedItem);
hideDropdown(element);
}
function setElementImage(element, imageSource) {
(0, _jquery2.default)(element._input).addClass('aui-select-has-inline-image');
element._input.setAttribute('style', 'background-image: url(' + imageSource + ')');
}
function suggest(element, autoHighlight, query) {
element._autoHighlight = autoHighlight;
if (query === undefined) {
query = element._input.value;
}
element._progressiveDataSet.query(query);
}
function setInputImageToHighlightedSuggestion(element) {
var imageSource = element._suggestionModel.highlighted() && element._suggestionModel.highlighted().get('img-src');
if (imageSource) {
setElementImage(element, imageSource);
}
}
function setValueAndDisplayFromModel(element, model) {
if (!model) {
return;
}
var option = document.createElement('option');
var select = element._select;
var value = model.get('value') || model.get('label');
option.setAttribute('selected', '');
option.setAttribute('value', value);
option.textContent = model.getLabel();
// Sync element value.
element._input.value = option.textContent;
select.innerHTML = '';
select.options.add(option);
select.dispatchEvent(new _customEvent2.default('change', { bubbles: true }));
}
function clearValue(element) {
element._input.value = '';
element._select.innerHTML = '';
}
function selectHighlightedSuggestion(element) {
setValueAndDisplayFromModel(element, element._suggestionModel.highlighted());
setInputImageToHighlightedSuggestion(element);
setInitialVisualState(element);
}
function convertOptionToModel(option) {
return new _suggestionModel2.default(option.serialize());
}
function convertOptionsToModels(element) {
var models = [];
for (var i = 0; i < element._datalist.children.length; i++) {
var option = element._datalist.children[i];
models.push(convertOptionToModel(option));
}
return models;
}
function clearAndSet(element, data) {
element._suggestionModel.set();
element._suggestionModel.set(data.results);
}
function getActiveId(select) {
var active = select._dropdown.querySelector('.aui-select-active');
return active && active.id;
}
function getIndexInResults(id, results) {
var resultsIds = _jquery2.default.map(results, function (result) {
return result.id;
});
return resultsIds.indexOf(id);
}
function createNewValueModel(element) {
var option = new _option2.default();
option.setAttribute('value', element._input.value);
var newValueSuggestionModel = convertOptionToModel(option);
newValueSuggestionModel.set('new-value', true);
return newValueSuggestionModel;
}
function initialiseProgressiveDataSet(element) {
element._progressiveDataSet = new _progressiveDataSet2.default(convertOptionsToModels(element), {
model: _suggestionModel2.default,
matcher: matchPrefix,
queryEndpoint: element._queryEndpoint,
maxResults: DEFAULT_SS_PDS_SIZE
});
element._isSync = element._queryEndpoint ? false : true;
// Progressive data set should indicate whether or not it is busy when processing any async requests.
// Check if there's any active queries left, if so: set spinner and state to busy, else set to idle and remove
// the spinner.
element._progressiveDataSet.on('activity', function () {
if (element._progressiveDataSet.activeQueryCount && !element._isSync) {
setBusyState(element);
(0, _state2.default)(element).set('should-flag-new-suggestions', false);
} else {
setIdleState(element);
(0, _state2.default)(element).set('should-flag-new-suggestions', true);
}
});
// Progressive data set doesn't do anything if the query is empty so we
// must manually convert all data list options into models.
//
// Otherwise progressive data set can do everything else for us:
// 1. Sync matching
// 2. Async fetching and matching
element._progressiveDataSet.on('respond', function (data) {
var optionToHighlight;
// This means that a query was made before the input was cleared and
// we should cancel the response.
if (data.query && !element._input.value) {
return;
}
if ((0, _state2.default)(element).get('should-cancel-response')) {
if (!element._progressiveDataSet.activeQueryCount) {
(0, _state2.default)(element).set('should-cancel-response', false);
}
return;
}
if (!data.query) {
data.results = convertOptionsToModels(element);
}
var isInputExactMatch = getIndexInResults(element._input.value, data.results) !== -1;
var isInputEmpty = !element._input.value;
if (element.hasAttribute('can-create-values') && !isInputExactMatch && !isInputEmpty) {
data.results.push(createNewValueModel(element));
}
if (!(0, _state2.default)(element).get('should-include-selected')) {
var indexOfValueInResults = getIndexInResults(element.value, data.results);
if (indexOfValueInResults >= 0) {
data.results.splice(indexOfValueInResults, 1);
}
}
clearAndSet(element, data);
optionToHighlight = element._suggestionModel.highlighted() || data.results[0];
if (element._autoHighlight) {
element._suggestionModel.setHighlighted(optionToHighlight);
waitForAssistive(function () {
element._input.setAttribute('aria-activedescendant', getActiveId(element));
});
}
element._input.setAttribute('aria-expanded', 'true');
// If the response is async (append operation), has elements to append and has a highlighted element, we need to update the status.
if (!element._isSync && element._suggestionsView.getActive() && (0, _state2.default)(element).get('should-flag-new-suggestions')) {
element.querySelector('.aui-select-status').innerHTML = AJS.I18n.getText('aui.select.new.suggestions');
}
element._suggestionsView.show();
if (element._autoHighlight) {
waitForAssistive(function () {
element._input.setAttribute('aria-activedescendant', getActiveId(element));
});
}
});
}
function associateDropdownAndTrigger(element) {
element._dropdown.id = element._listId;
element.querySelector('button').setAttribute('aria-controls', element._listId);
}
function bindHighlightMouseover(element) {
(0, _jquery2.default)(element._dropdown).on('mouseover', 'li', function (e) {
if (hasResults(element)) {
element._suggestionModel.highlight((0, _jquery2.default)(e.target).index());
}
});
}
function bindSelectMousedown(element) {
(0, _jquery2.default)(element._dropdown).on('mousedown', 'li', function (e) {
if (hasResults(element)) {
element._suggestionModel.highlight((0, _jquery2.default)(e.target).index());
selectHighlightedSuggestion(element);
element._suggestionsView.hide();
element._input.removeAttribute('aria-activedescendant');
} else {
return false;
}
});
}
function initialiseValue(element) {
var option = element._datalist.querySelector('aui-option[selected]');
if (option) {
setValueAndDisplayFromModel(element, convertOptionToModel(option));
}
}
function isQueryInProgress(element) {
return element._progressiveDataSet.activeQueryCount > 0;
}
function focusInHandler(element) {
//if there is a selected value the single select should do an empty
//search and return everything
var searchValue = element.value ? '' : element._input.value;
var isInputEmpty = element._input.value === '';
(0, _state2.default)(element).set('should-include-selected', isInputEmpty);
suggest(element, true, searchValue);
}
function cancelInProgressQueries(element) {
if (isQueryInProgress(element)) {
(0, _state2.default)(element).set('should-cancel-response', true);
}
}
function getSelectedLabel(element) {
if (element._select.selectedIndex >= 0) {
return element._select.options[element._select.selectedIndex].textContent;
}
}
function handleInvalidInputOnFocusOut(element) {
var selectCanBeEmpty = !element.hasAttribute('no-empty-values');
var selectionIsEmpty = !element._input.value;
var selectionNotExact = element._input.value !== getSelectedLabel(element);
var selectionNotValid = selectionIsEmpty || selectionNotExact;
if (selectionNotValid) {
if (selectCanBeEmpty) {
deselect(element);
} else {
var selection = getSelectedLabel(element);
if (typeof selection === 'undefined') {
deselect(element);
} else {
element._input.value = selection;
}
}
}
}
function handleHighlightOnFocusOut(element) {
// Forget the highlighted suggestion.
element._suggestionModel.highlight(NO_HIGHLIGHT);
}
function focusOutHandler(element) {
cancelInProgressQueries(element);
handleInvalidInputOnFocusOut(element);
handleHighlightOnFocusOut(element);
hideDropdown(element);
}
function handleTabOut(element) {
var isSuggestionViewVisible = element._suggestionsView.isVisible();
if (isSuggestionViewVisible) {
selectHighlightedSuggestion(element);
}
}
var select = (0, _skate2.default)('aui-select', {
template: _template2.default,
created: function created(element) {
element._listId = (0, _uniqueId2.default)();
element._input = element.querySelector('input');
element._select = element.querySelector('select');
element._dropdown = element.querySelector('.aui-popover');
element._datalist = element.querySelector('datalist');
element._button = element.querySelector('button');
element._suggestionsView = new _suggestionsView2.default(element._dropdown, element._input);
element._suggestionModel = new _suggestionsModel2.default();
element._suggestionModel.onChange = function (oldSuggestions) {
var suggestionsToAdd = [];
element._suggestionModel._suggestions.forEach(function (newSuggestion) {
var inArray = oldSuggestions.some(function (oldSuggestion) {
return newSuggestion.id === oldSuggestion.id;
});
if (!inArray) {
suggestionsToAdd.push(newSuggestion);
}
});
element._suggestionsView.render(suggestionsToAdd, oldSuggestions.length, element._listId);
};
element._suggestionModel.onHighlightChange = function () {
var active = element._suggestionModel.highlightedIndex();
element._suggestionsView.setActive(active);
element._input.setAttribute('aria-activedescendant', getActiveId(element));
};
},
attached: function attached(element) {
_skate2.default.init(element);
initialiseProgressiveDataSet(element);
associateDropdownAndTrigger(element);
element._input.setAttribute('aria-controls', element._listId);
element.setAttribute('tabindex', '-1');
bindHighlightMouseover(element);
bindSelectMousedown(element);
initialiseValue(element);
setInitialVisualState(element);
setInputImageToHighlightedSuggestion(element);
},
attributes: {
id: function id(element, data) {
if (element.id) {
element.querySelector('input').id = data.newValue + _constants.INPUT_SUFFIX;
}
},
name: function name(element, data) {
element.querySelector('select').setAttribute('name', data.newValue);
},
placeholder: function placeholder(element, data) {
element.querySelector('input').setAttribute('placeholder', data.newValue);
},
src: function src(element, data) {
element._queryEndpoint = data.newValue;
}
},
events: {
'blur input': function blurInput(element) {
focusOutHandler(element);
},
'mousedown button': function mousedownButton(element) {
if (document.activeElement === element._input && element._dropdown.getAttribute('aria-hidden') === 'false') {
(0, _state2.default)(element).set('prevent-open-on-button-click', true);
}
},
'click input': function clickInput(element) {
focusInHandler(element);
},
'click button': function clickButton(element) {
var data = (0, _state2.default)(element);
if (data.get('prevent-open-on-button-click')) {
data.set('prevent-open-on-button-click', false);
} else {
element.focus();
}
},
input: function input(element) {
if (!element._input.value) {
hideDropdown(element);
} else {
(0, _state2.default)(element).set('should-include-selected', true);
suggest(element, true);
}
},
'keydown input': function keydownInput(element, e) {
var currentValue = element._input.value;
var handled = false;
if (e.keyCode === _keyCode2.default.ESCAPE) {
cancelInProgressQueries(element);
hideDropdown(element);
return;
}
var isSuggestionViewVisible = element._suggestionsView.isVisible();
if (isSuggestionViewVisible && hasResults(element)) {
if (e.keyCode === _keyCode2.default.ENTER) {
cancelInProgressQueries(element);
selectHighlightedSuggestion(element);
e.preventDefault();
} else if (e.keyCode === _keyCode2.default.TAB) {
handleTabOut(element);
handled = true;
} else if (e.keyCode === _keyCode2.default.UP) {
element._suggestionModel.highlightPrevious();
e.preventDefault();
} else if (e.keyCode === _keyCode2.default.DOWN) {
element._suggestionModel.highlightNext();
e.preventDefault();
}
} else if (e.keyCode === _keyCode2.default.UP || e.keyCode === _keyCode2.default.DOWN) {
focusInHandler(element);
e.preventDefault();
}
handled = handled || e.defaultPrevented;
setTimeout(function emulateCrossBrowserInputEvent() {
if (element._input.value !== currentValue && !handled) {
element.dispatchEvent(new _customEvent2.default('input', { bubbles: true }));
}
}, 0);
}
},
prototype: {
get value() {
var selected = this._select.options[this._select.selectedIndex];
return selected ? selected.value : '';
},
set value(value) {
if (value === '') {
clearValue(this);
} else if (value) {
var data = this._progressiveDataSet;
var model = data.findWhere({
value: value
}) || data.findWhere({
label: value
});
// Create a new value if allowed and the value doesn't exist.
if (!model && this.hasAttribute('can-create-values')) {
model = new _suggestionModel2.default({ value: value, label: value });
}
setValueAndDisplayFromModel(this, model);
}
return this;
},
get displayValue() {
return this._input.value;
},
blur: function blur() {
this._input.blur();
focusOutHandler(this);
return this;
},
focus: function focus() {
this._input.focus();
focusInHandler(this);
return this;
}
}
});
(0, _amdify2.default)('aui/select', select);
(0, _globalize2.default)('select', select);
exports.default = select;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/plugins/jquery.select2.js
(typeof window === 'undefined' ? global : window).__b2190710f2822b5d7286528d3eaff37f = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/*
Copyright 2012 Igor Vaynberg
Version: 3.4.5 Timestamp: Mon Nov 4 08:22:42 PST 2013
This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.
You may obtain a copy of the Apache License and the GPL License at:
http://www.apache.org/licenses/LICENSE-2.0
http://www.gnu.org/licenses/gpl-2.0.html
Unless required by applicable law or agreed to in writing, software distributed under the
Apache License or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the Apache License and the GPL License for
the specific language governing permissions and limitations under the Apache License and the GPL License.
*/
(function ($) {
if(typeof $.fn.each2 == "undefined") {
$.extend($.fn, {
/*
* 4-10 times faster .each replacement
* use it carefully, as it overrides jQuery context of element on each iteration
*/
each2 : function (c) {
var j = $([0]), i = -1, l = this.length;
while (
++i < l
&& (j.context = j[0] = this[i])
&& c.call(j[0], i, j) !== false //"this"=DOM, i=index, j=jQuery object
);
return this;
}
});
}
})(jQuery);
(function ($, undefined) {
/*global document, window, jQuery, console */
if (window.Select2 !== undefined) {
return;
}
var KEY, AbstractSelect2, SingleSelect2, MultiSelect2, nextUid, sizer,
lastMousePosition={x:0,y:0}, $document, scrollBarDimensions,
KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
isArrow: function (k) {
k = k.which ? k.which : k;
switch (k) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
return true;
}
return false;
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
}
},
MEASURE_SCROLLBAR_TEMPLATE = "<div class='select2-measure-scrollbar'></div>",
DIACRITICS = {"\u24B6":"A","\uFF21":"A","\u00C0":"A","\u00C1":"A","\u00C2":"A","\u1EA6":"A","\u1EA4":"A","\u1EAA":"A","\u1EA8":"A","\u00C3":"A","\u0100":"A","\u0102":"A","\u1EB0":"A","\u1EAE":"A","\u1EB4":"A","\u1EB2":"A","\u0226":"A","\u01E0":"A","\u00C4":"A","\u01DE":"A","\u1EA2":"A","\u00C5":"A","\u01FA":"A","\u01CD":"A","\u0200":"A","\u0202":"A","\u1EA0":"A","\u1EAC":"A","\u1EB6":"A","\u1E00":"A","\u0104":"A","\u023A":"A","\u2C6F":"A","\uA732":"AA","\u00C6":"AE","\u01FC":"AE","\u01E2":"AE","\uA734":"AO","\uA736":"AU","\uA738":"AV","\uA73A":"AV","\uA73C":"AY","\u24B7":"B","\uFF22":"B","\u1E02":"B","\u1E04":"B","\u1E06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24B8":"C","\uFF23":"C","\u0106":"C","\u0108":"C","\u010A":"C","\u010C":"C","\u00C7":"C","\u1E08":"C","\u0187":"C","\u023B":"C","\uA73E":"C","\u24B9":"D","\uFF24":"D","\u1E0A":"D","\u010E":"D","\u1E0C":"D","\u1E10":"D","\u1E12":"D","\u1E0E":"D","\u0110":"D","\u018B":"D","\u018A":"D","\u0189":"D","\uA779":"D","\u01F1":"DZ","\u01C4":"DZ","\u01F2":"Dz","\u01C5":"Dz","\u24BA":"E","\uFF25":"E","\u00C8":"E","\u00C9":"E","\u00CA":"E","\u1EC0":"E","\u1EBE":"E","\u1EC4":"E","\u1EC2":"E","\u1EBC":"E","\u0112":"E","\u1E14":"E","\u1E16":"E","\u0114":"E","\u0116":"E","\u00CB":"E","\u1EBA":"E","\u011A":"E","\u0204":"E","\u0206":"E","\u1EB8":"E","\u1EC6":"E","\u0228":"E","\u1E1C":"E","\u0118":"E","\u1E18":"E","\u1E1A":"E","\u0190":"E","\u018E":"E","\u24BB":"F","\uFF26":"F","\u1E1E":"F","\u0191":"F","\uA77B":"F","\u24BC":"G","\uFF27":"G","\u01F4":"G","\u011C":"G","\u1E20":"G","\u011E":"G","\u0120":"G","\u01E6":"G","\u0122":"G","\u01E4":"G","\u0193":"G","\uA7A0":"G","\uA77D":"G","\uA77E":"G","\u24BD":"H","\uFF28":"H","\u0124":"H","\u1E22":"H","\u1E26":"H","\u021E":"H","\u1E24":"H","\u1E28":"H","\u1E2A":"H","\u0126":"H","\u2C67":"H","\u2C75":"H","\uA78D":"H","\u24BE":"I","\uFF29":"I","\u00CC":"I","\u00CD":"I","\u00CE":"I","\u0128":"I","\u012A":"I","\u012C":"I","\u0130":"I","\u00CF":"I","\u1E2E":"I","\u1EC8":"I","\u01CF":"I","\u0208":"I","\u020A":"I","\u1ECA":"I","\u012E":"I","\u1E2C":"I","\u0197":"I","\u24BF":"J","\uFF2A":"J","\u0134":"J","\u0248":"J","\u24C0":"K","\uFF2B":"K","\u1E30":"K","\u01E8":"K","\u1E32":"K","\u0136":"K","\u1E34":"K","\u0198":"K","\u2C69":"K","\uA740":"K","\uA742":"K","\uA744":"K","\uA7A2":"K","\u24C1":"L","\uFF2C":"L","\u013F":"L","\u0139":"L","\u013D":"L","\u1E36":"L","\u1E38":"L","\u013B":"L","\u1E3C":"L","\u1E3A":"L","\u0141":"L","\u023D":"L","\u2C62":"L","\u2C60":"L","\uA748":"L","\uA746":"L","\uA780":"L","\u01C7":"LJ","\u01C8":"Lj","\u24C2":"M","\uFF2D":"M","\u1E3E":"M","\u1E40":"M","\u1E42":"M","\u2C6E":"M","\u019C":"M","\u24C3":"N","\uFF2E":"N","\u01F8":"N","\u0143":"N","\u00D1":"N","\u1E44":"N","\u0147":"N","\u1E46":"N","\u0145":"N","\u1E4A":"N","\u1E48":"N","\u0220":"N","\u019D":"N","\uA790":"N","\uA7A4":"N","\u01CA":"NJ","\u01CB":"Nj","\u24C4":"O","\uFF2F":"O","\u00D2":"O","\u00D3":"O","\u00D4":"O","\u1ED2":"O","\u1ED0":"O","\u1ED6":"O","\u1ED4":"O","\u00D5":"O","\u1E4C":"O","\u022C":"O","\u1E4E":"O","\u014C":"O","\u1E50":"O","\u1E52":"O","\u014E":"O","\u022E":"O","\u0230":"O","\u00D6":"O","\u022A":"O","\u1ECE":"O","\u0150":"O","\u01D1":"O","\u020C":"O","\u020E":"O","\u01A0":"O","\u1EDC":"O","\u1EDA":"O","\u1EE0":"O","\u1EDE":"O","\u1EE2":"O","\u1ECC":"O","\u1ED8":"O","\u01EA":"O","\u01EC":"O","\u00D8":"O","\u01FE":"O","\u0186":"O","\u019F":"O","\uA74A":"O","\uA74C":"O","\u01A2":"OI","\uA74E":"OO","\u0222":"OU","\u24C5":"P","\uFF30":"P","\u1E54":"P","\u1E56":"P","\u01A4":"P","\u2C63":"P","\uA750":"P","\uA752":"P","\uA754":"P","\u24C6":"Q","\uFF31":"Q","\uA756":"Q","\uA758":"Q","\u024A":"Q","\u24C7":"R","\uFF32":"R","\u0154":"R","\u1E58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1E5A":"R","\u1E5C":"R","\u0156":"R","\u1E5E":"R","\u024C":"R","\u2C64":"R","\uA75A":"R","\uA7A6":"R","\uA782":"R","\u24C8":"S","\uFF33":"S","\u1E9E":"S","\u015A":"S","\u1E64":"S","\u015C":"S","\u1E60":"S","\u0160":"S","\u1E66":"S","\u1E62":"S","\u1E68":"S","\u0218":"S","\u015E":"S","\u2C7E":"S","\uA7A8":"S","\uA784":"S","\u24C9":"T","\uFF34":"T","\u1E6A":"T","\u0164":"T","\u1E6C":"T","\u021A":"T","\u0162":"T","\u1E70":"T","\u1E6E":"T","\u0166":"T","\u01AC":"T","\u01AE":"T","\u023E":"T","\uA786":"T","\uA728":"TZ","\u24CA":"U","\uFF35":"U","\u00D9":"U","\u00DA":"U","\u00DB":"U","\u0168":"U","\u1E78":"U","\u016A":"U","\u1E7A":"U","\u016C":"U","\u00DC":"U","\u01DB":"U","\u01D7":"U","\u01D5":"U","\u01D9":"U","\u1EE6":"U","\u016E":"U","\u0170":"U","\u01D3":"U","\u0214":"U","\u0216":"U","\u01AF":"U","\u1EEA":"U","\u1EE8":"U","\u1EEE":"U","\u1EEC":"U","\u1EF0":"U","\u1EE4":"U","\u1E72":"U","\u0172":"U","\u1E76":"U","\u1E74":"U","\u0244":"U","\u24CB":"V","\uFF36":"V","\u1E7C":"V","\u1E7E":"V","\u01B2":"V","\uA75E":"V","\u0245":"V","\uA760":"VY","\u24CC":"W","\uFF37":"W","\u1E80":"W","\u1E82":"W","\u0174":"W","\u1E86":"W","\u1E84":"W","\u1E88":"W","\u2C72":"W","\u24CD":"X","\uFF38":"X","\u1E8A":"X","\u1E8C":"X","\u24CE":"Y","\uFF39":"Y","\u1EF2":"Y","\u00DD":"Y","\u0176":"Y","\u1EF8":"Y","\u0232":"Y","\u1E8E":"Y","\u0178":"Y","\u1EF6":"Y","\u1EF4":"Y","\u01B3":"Y","\u024E":"Y","\u1EFE":"Y","\u24CF":"Z","\uFF3A":"Z","\u0179":"Z","\u1E90":"Z","\u017B":"Z","\u017D":"Z","\u1E92":"Z","\u1E94":"Z","\u01B5":"Z","\u0224":"Z","\u2C7F":"Z","\u2C6B":"Z","\uA762":"Z","\u24D0":"a","\uFF41":"a","\u1E9A":"a","\u00E0":"a","\u00E1":"a","\u00E2":"a","\u1EA7":"a","\u1EA5":"a","\u1EAB":"a","\u1EA9":"a","\u00E3":"a","\u0101":"a","\u0103":"a","\u1EB1":"a","\u1EAF":"a","\u1EB5":"a","\u1EB3":"a","\u0227":"a","\u01E1":"a","\u00E4":"a","\u01DF":"a","\u1EA3":"a","\u00E5":"a","\u01FB":"a","\u01CE":"a","\u0201":"a","\u0203":"a","\u1EA1":"a","\u1EAD":"a","\u1EB7":"a","\u1E01":"a","\u0105":"a","\u2C65":"a","\u0250":"a","\uA733":"aa","\u00E6":"ae","\u01FD":"ae","\u01E3":"ae","\uA735":"ao","\uA737":"au","\uA739":"av","\uA73B":"av","\uA73D":"ay","\u24D1":"b","\uFF42":"b","\u1E03":"b","\u1E05":"b","\u1E07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24D2":"c","\uFF43":"c","\u0107":"c","\u0109":"c","\u010B":"c","\u010D":"c","\u00E7":"c","\u1E09":"c","\u0188":"c","\u023C":"c","\uA73F":"c","\u2184":"c","\u24D3":"d","\uFF44":"d","\u1E0B":"d","\u010F":"d","\u1E0D":"d","\u1E11":"d","\u1E13":"d","\u1E0F":"d","\u0111":"d","\u018C":"d","\u0256":"d","\u0257":"d","\uA77A":"d","\u01F3":"dz","\u01C6":"dz","\u24D4":"e","\uFF45":"e","\u00E8":"e","\u00E9":"e","\u00EA":"e","\u1EC1":"e","\u1EBF":"e","\u1EC5":"e","\u1EC3":"e","\u1EBD":"e","\u0113":"e","\u1E15":"e","\u1E17":"e","\u0115":"e","\u0117":"e","\u00EB":"e","\u1EBB":"e","\u011B":"e","\u0205":"e","\u0207":"e","\u1EB9":"e","\u1EC7":"e","\u0229":"e","\u1E1D":"e","\u0119":"e","\u1E19":"e","\u1E1B":"e","\u0247":"e","\u025B":"e","\u01DD":"e","\u24D5":"f","\uFF46":"f","\u1E1F":"f","\u0192":"f","\uA77C":"f","\u24D6":"g","\uFF47":"g","\u01F5":"g","\u011D":"g","\u1E21":"g","\u011F":"g","\u0121":"g","\u01E7":"g","\u0123":"g","\u01E5":"g","\u0260":"g","\uA7A1":"g","\u1D79":"g","\uA77F":"g","\u24D7":"h","\uFF48":"h","\u0125":"h","\u1E23":"h","\u1E27":"h","\u021F":"h","\u1E25":"h","\u1E29":"h","\u1E2B":"h","\u1E96":"h","\u0127":"h","\u2C68":"h","\u2C76":"h","\u0265":"h","\u0195":"hv","\u24D8":"i","\uFF49":"i","\u00EC":"i","\u00ED":"i","\u00EE":"i","\u0129":"i","\u012B":"i","\u012D":"i","\u00EF":"i","\u1E2F":"i","\u1EC9":"i","\u01D0":"i","\u0209":"i","\u020B":"i","\u1ECB":"i","\u012F":"i","\u1E2D":"i","\u0268":"i","\u0131":"i","\u24D9":"j","\uFF4A":"j","\u0135":"j","\u01F0":"j","\u0249":"j","\u24DA":"k","\uFF4B":"k","\u1E31":"k","\u01E9":"k","\u1E33":"k","\u0137":"k","\u1E35":"k","\u0199":"k","\u2C6A":"k","\uA741":"k","\uA743":"k","\uA745":"k","\uA7A3":"k","\u24DB":"l","\uFF4C":"l","\u0140":"l","\u013A":"l","\u013E":"l","\u1E37":"l","\u1E39":"l","\u013C":"l","\u1E3D":"l","\u1E3B":"l","\u017F":"l","\u0142":"l","\u019A":"l","\u026B":"l","\u2C61":"l","\uA749":"l","\uA781":"l","\uA747":"l","\u01C9":"lj","\u24DC":"m","\uFF4D":"m","\u1E3F":"m","\u1E41":"m","\u1E43":"m","\u0271":"m","\u026F":"m","\u24DD":"n","\uFF4E":"n","\u01F9":"n","\u0144":"n","\u00F1":"n","\u1E45":"n","\u0148":"n","\u1E47":"n","\u0146":"n","\u1E4B":"n","\u1E49":"n","\u019E":"n","\u0272":"n","\u0149":"n","\uA791":"n","\uA7A5":"n","\u01CC":"nj","\u24DE":"o","\uFF4F":"o","\u00F2":"o","\u00F3":"o","\u00F4":"o","\u1ED3":"o","\u1ED1":"o","\u1ED7":"o","\u1ED5":"o","\u00F5":"o","\u1E4D":"o","\u022D":"o","\u1E4F":"o","\u014D":"o","\u1E51":"o","\u1E53":"o","\u014F":"o","\u022F":"o","\u0231":"o","\u00F6":"o","\u022B":"o","\u1ECF":"o","\u0151":"o","\u01D2":"o","\u020D":"o","\u020F":"o","\u01A1":"o","\u1EDD":"o","\u1EDB":"o","\u1EE1":"o","\u1EDF":"o","\u1EE3":"o","\u1ECD":"o","\u1ED9":"o","\u01EB":"o","\u01ED":"o","\u00F8":"o","\u01FF":"o","\u0254":"o","\uA74B":"o","\uA74D":"o","\u0275":"o","\u01A3":"oi","\u0223":"ou","\uA74F":"oo","\u24DF":"p","\uFF50":"p","\u1E55":"p","\u1E57":"p","\u01A5":"p","\u1D7D":"p","\uA751":"p","\uA753":"p","\uA755":"p","\u24E0":"q","\uFF51":"q","\u024B":"q","\uA757":"q","\uA759":"q","\u24E1":"r","\uFF52":"r","\u0155":"r","\u1E59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1E5B":"r","\u1E5D":"r","\u0157":"r","\u1E5F":"r","\u024D":"r","\u027D":"r","\uA75B":"r","\uA7A7":"r","\uA783":"r","\u24E2":"s","\uFF53":"s","\u00DF":"s","\u015B":"s","\u1E65":"s","\u015D":"s","\u1E61":"s","\u0161":"s","\u1E67":"s","\u1E63":"s","\u1E69":"s","\u0219":"s","\u015F":"s","\u023F":"s","\uA7A9":"s","\uA785":"s","\u1E9B":"s","\u24E3":"t","\uFF54":"t","\u1E6B":"t","\u1E97":"t","\u0165":"t","\u1E6D":"t","\u021B":"t","\u0163":"t","\u1E71":"t","\u1E6F":"t","\u0167":"t","\u01AD":"t","\u0288":"t","\u2C66":"t","\uA787":"t","\uA729":"tz","\u24E4":"u","\uFF55":"u","\u00F9":"u","\u00FA":"u","\u00FB":"u","\u0169":"u","\u1E79":"u","\u016B":"u","\u1E7B":"u","\u016D":"u","\u00FC":"u","\u01DC":"u","\u01D8":"u","\u01D6":"u","\u01DA":"u","\u1EE7":"u","\u016F":"u","\u0171":"u","\u01D4":"u","\u0215":"u","\u0217":"u","\u01B0":"u","\u1EEB":"u","\u1EE9":"u","\u1EEF":"u","\u1EED":"u","\u1EF1":"u","\u1EE5":"u","\u1E73":"u","\u0173":"u","\u1E77":"u","\u1E75":"u","\u0289":"u","\u24E5":"v","\uFF56":"v","\u1E7D":"v","\u1E7F":"v","\u028B":"v","\uA75F":"v","\u028C":"v","\uA761":"vy","\u24E6":"w","\uFF57":"w","\u1E81":"w","\u1E83":"w","\u0175":"w","\u1E87":"w","\u1E85":"w","\u1E98":"w","\u1E89":"w","\u2C73":"w","\u24E7":"x","\uFF58":"x","\u1E8B":"x","\u1E8D":"x","\u24E8":"y","\uFF59":"y","\u1EF3":"y","\u00FD":"y","\u0177":"y","\u1EF9":"y","\u0233":"y","\u1E8F":"y","\u00FF":"y","\u1EF7":"y","\u1E99":"y","\u1EF5":"y","\u01B4":"y","\u024F":"y","\u1EFF":"y","\u24E9":"z","\uFF5A":"z","\u017A":"z","\u1E91":"z","\u017C":"z","\u017E":"z","\u1E93":"z","\u1E95":"z","\u01B6":"z","\u0225":"z","\u0240":"z","\u2C6C":"z","\uA763":"z"};
$document = $(document);
nextUid=(function() { var counter=1; return function() { return counter++; }; }());
function stripDiacritics(str) {
var ret, i, l, c;
if (!str || str.length < 1) return str;
ret = "";
for (i = 0, l = str.length; i < l; i++) {
c = str.charAt(i);
ret += DIACRITICS[c] || c;
}
return ret;
}
function indexOf(value, array) {
var i = 0, l = array.length;
for (; i < l; i = i + 1) {
if (equal(value, array[i])) return i;
}
return -1;
}
function measureScrollbar () {
var $template = $( MEASURE_SCROLLBAR_TEMPLATE );
$template.appendTo('body');
var dim = {
width: $template.width() - $template[0].clientWidth,
height: $template.height() - $template[0].clientHeight
};
$template.remove();
return dim;
}
/**
* Compares equality of a and b
* @param a
* @param b
*/
function equal(a, b) {
if (a === b) return true;
if (a === undefined || b === undefined) return false;
if (a === null || b === null) return false;
// Check whether 'a' or 'b' is a string (primitive or object).
// The concatenation of an empty string (+'') converts its argument to a string's primitive.
if (a.constructor === String) return a+'' === b+''; // a+'' - in case 'a' is a String object
if (b.constructor === String) return b+'' === a+''; // b+'' - in case 'b' is a String object
return false;
}
/**
* Splits the string into an array of values, trimming each value. An empty array is returned for nulls or empty
* strings
* @param string
* @param separator
*/
function splitVal(string, separator) {
var val, i, l;
if (string === null || string.length < 1) return [];
val = string.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
return val;
}
function getSideBorderPadding(element) {
return element.outerWidth(false) - element.width();
}
function installKeyUpChangeEvent(element) {
var key="keyup-change-value";
element.on("keydown", function () {
if ($.data(element, key) === undefined) {
$.data(element, key, element.val());
}
});
element.on("keyup", function () {
var val= $.data(element, key);
if (val !== undefined && element.val() !== val) {
$.removeData(element, key);
element.trigger("keyup-change");
}
});
}
$document.on("mousemove", function (e) {
lastMousePosition.x = e.pageX;
lastMousePosition.y = e.pageY;
});
/**
* filters mouse events so an event is fired only if the mouse moved.
*
* filters out mouse events that occur when mouse is stationary but
* the elements under the pointer are scrolled.
*/
function installFilteredMouseMove(element) {
element.on("mousemove", function (e) {
var lastpos = lastMousePosition;
if (lastpos === undefined || lastpos.x !== e.pageX || lastpos.y !== e.pageY) {
$(e.target).trigger("mousemove-filtered", e);
}
});
}
/**
* Debounces a function. Returns a function that calls the original fn function only if no invocations have been made
* within the last quietMillis milliseconds.
*
* @param quietMillis number of milliseconds to wait before invoking fn
* @param fn function to be debounced
* @param ctx object to be used as this reference within fn
* @return debounced version of fn
*/
function debounce(quietMillis, fn, ctx) {
ctx = ctx || undefined;
var timeout;
return function () {
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(ctx, args);
}, quietMillis);
};
}
/**
* A simple implementation of a thunk
* @param formula function used to lazily initialize the thunk
* @return {Function}
*/
function thunk(formula) {
var evaluated = false,
value;
return function() {
if (evaluated === false) { value = formula(); evaluated = true; }
return value;
};
};
function installDebouncedScroll(threshold, element) {
var notify = debounce(threshold, function (e) { element.trigger("scroll-debounced", e);});
element.on("scroll", function (e) {
if (indexOf(e.target, element.get()) >= 0) notify(e);
});
}
function focus($el) {
if ($el[0] === document.activeElement) return;
/* set the focus in a 0 timeout - that way the focus is set after the processing
of the current event has finished - which seems like the only reliable way
to set focus */
window.setTimeout(function() {
var el=$el[0], pos=$el.val().length, range;
$el.focus();
/* make sure el received focus so we do not error out when trying to manipulate the caret.
sometimes modals or others listeners may steal it after its set */
if ($el.is(":visible") && el === document.activeElement) {
/* after the focus is set move the caret to the end, necessary when we val()
just before setting focus */
if(el.setSelectionRange)
{
el.setSelectionRange(pos, pos);
}
else if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
}
}
}, 0);
}
function getCursorInfo(el) {
el = $(el)[0];
var offset = 0;
var length = 0;
if ('selectionStart' in el) {
offset = el.selectionStart;
length = el.selectionEnd - offset;
} else if ('selection' in document) {
el.focus();
var sel = document.selection.createRange();
length = document.selection.createRange().text.length;
sel.moveStart('character', -el.value.length);
offset = sel.text.length - length;
}
return { offset: offset, length: length };
}
function killEvent(event) {
event.preventDefault();
event.stopPropagation();
}
function killEventImmediately(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function measureTextWidth(e) {
if (!sizer){
var style = e[0].currentStyle || window.getComputedStyle(e[0], null);
sizer = $(document.createElement("div")).css({
position: "absolute",
left: "-10000px",
top: "-10000px",
display: "none",
fontSize: style.fontSize,
fontFamily: style.fontFamily,
fontStyle: style.fontStyle,
fontWeight: style.fontWeight,
letterSpacing: style.letterSpacing,
textTransform: style.textTransform,
whiteSpace: "nowrap"
});
sizer.attr("class","select2-sizer");
$("body").append(sizer);
}
sizer.text(e.val());
return sizer.width();
}
function syncCssClasses(dest, src, adapter) {
var classes, replacements = [], adapted;
classes = dest.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") === 0) {
replacements.push(this);
}
});
}
classes = src.attr("class");
if (classes) {
classes = '' + classes; // for IE which returns object
$(classes.split(" ")).each2(function() {
if (this.indexOf("select2-") !== 0) {
adapted = adapter(this);
if (adapted) {
replacements.push(adapted);
}
}
});
}
dest.attr("class", replacements.join(" "));
}
function markMatch(text, term, markup, escapeMarkup) {
var match=stripDiacritics(text.toUpperCase()).indexOf(stripDiacritics(term.toUpperCase())),
tl=term.length;
if (match<0) {
markup.push(escapeMarkup(text));
return;
}
markup.push(escapeMarkup(text.substring(0, match)));
markup.push("<span class='select2-match'>");
markup.push(escapeMarkup(text.substring(match, match + tl)));
markup.push("</span>");
markup.push(escapeMarkup(text.substring(match + tl, text.length)));
}
function defaultEscapeMarkup(markup) {
var replace_map = {
'\\': '\',
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
"/": '/'
};
return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
return replace_map[match];
});
}
/**
* Produces an ajax-based query function
*
* @param options object containing configuration paramters
* @param options.params parameter map for the transport ajax call, can contain such options as cache, jsonpCallback, etc. see $.ajax
* @param options.transport function that will be used to execute the ajax request. must be compatible with parameters supported by $.ajax
* @param options.url url for the data
* @param options.data a function(searchTerm, pageNumber, context) that should return an object containing query string parameters for the above url.
* @param options.dataType request data type: ajax, jsonp, other datatatypes supported by jQuery's $.ajax function or the transport function if specified
* @param options.quietMillis (optional) milliseconds to wait before making the ajaxRequest, helps debounce the ajax function if invoked too often
* @param options.results a function(remoteData, pageNumber) that converts data returned form the remote request to the format expected by Select2.
* The expected format is an object containing the following keys:
* results array of objects that will be used as choices
* more (optional) boolean indicating whether there are more results available
* Example: {results:[{id:1, text:'Red'},{id:2, text:'Blue'}], more:true}
*/
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler) { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
// TODO - replace query.page with query so users have access to term, page, etc.
var results = options.results(data, query.page);
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
/**
* Produces a query function that works with a local array
*
* @param options object containing configuration parameters. The options parameter can either be an array or an
* object.
*
* If the array form is used it is assumed that it contains objects with 'id' and 'text' keys.
*
* If the object form is used ti is assumed that it contains 'data' and 'text' keys. The 'data' key should contain
* an array of objects that will be used as choices. These objects must contain at least an 'id' key. The 'text'
* key can either be a String in which case it is expected that each element in the 'data' array has a key with the
* value of 'text' which will be used to match choices. Alternatively, text can be a function(item) that can extract
* the text.
*/
function local(options) {
var data = options, // data elements
dataText,
tmp,
text = function (item) { return ""+item.text; }; // function used to retrieve the text portion of a data item that is matched against the search
if ($.isArray(data)) {
tmp = data;
data = { results: tmp };
}
if ($.isFunction(data) === false) {
tmp = data;
data = function() { return tmp; };
}
var dataItem = data();
if (dataItem.text) {
text = dataItem.text;
// if text is not a function we assume it to be a key name
if (!$.isFunction(text)) {
dataText = dataItem.text; // we need to store this in a separate variable because in the next step data gets reset and data.text is no longer available
text = function (item) { return item[dataText]; };
}
}
return function (query) {
var t = query.term, filtered = { results: [] }, process;
if (t === "") {
query.callback(data());
return;
}
process = function(datum, collection) {
var group, attr;
datum = datum[0];
if (datum.children) {
group = {};
for (attr in datum) {
if (datum.hasOwnProperty(attr)) group[attr]=datum[attr];
}
group.children=[];
$(datum.children).each2(function(i, childDatum) { process(childDatum, group.children); });
if (group.children.length || query.matcher(t, text(group), datum)) {
collection.push(group);
}
} else {
if (query.matcher(t, text(datum), datum)) {
collection.push(datum);
}
}
};
$(data().results).each2(function(i, datum) { process(datum, filtered.results); });
query.callback(filtered);
};
}
// TODO javadoc
function tags(data) {
var isFunc = $.isFunction(data);
return function (query) {
var t = query.term, filtered = {results: []};
$(isFunc ? data() : data).each(function () {
var isObject = this.text !== undefined,
text = isObject ? this.text : this;
if (t === "" || query.matcher(t, text)) {
filtered.results.push(isObject ? this : {id: this, text: this});
}
});
query.callback(filtered);
};
}
/**
* Checks if the formatter function should be used.
*
* Throws an error if it is not a function. Returns true if it should be used,
* false if no formatting should be performed.
*
* @param formatter
*/
function checkFormatter(formatter, formatterName) {
if ($.isFunction(formatter)) return true;
if (!formatter) return false;
throw new Error(formatterName +" must be a function or a falsy value");
}
function evaluate(val) {
return $.isFunction(val) ? val() : val;
}
function countResults(results) {
var count = 0;
$.each(results, function(i, item) {
if (item.children) {
count += countResults(item.children);
} else {
count++;
}
});
return count;
}
/**
* Default tokenizer. This function uses breaks the input on substring match of any string from the
* opts.tokenSeparators array and uses opts.createSearchChoice to create the choice object. Both of those
* two options have to be defined in order for the tokenizer to work.
*
* @param input text user has typed so far or pasted into the search field
* @param selection currently selected choices
* @param selectCallback function(choice) callback tho add the choice to selection
* @param opts select2's opts
* @return undefined/null to leave the current input unchanged, or a string to change the input to the returned value
*/
function defaultTokenizer(input, selection, selectCallback, opts) {
var original = input, // store the original so we can compare and know if we need to tell the search to update its text
dupe = false, // check for whether a token we extracted represents a duplicate selected choice
token, // token
index, // position at which the separator was found
i, l, // looping variables
separator; // the matched separator
if (!opts.createSearchChoice || !opts.tokenSeparators || opts.tokenSeparators.length < 1) return undefined;
while (true) {
index = -1;
for (i = 0, l = opts.tokenSeparators.length; i < l; i++) {
separator = opts.tokenSeparators[i];
index = input.indexOf(separator);
if (index >= 0) break;
}
if (index < 0) break; // did not find any token separator in the input string, bail
token = input.substring(0, index);
input = input.substring(index + separator.length);
if (token.length > 0) {
token = opts.createSearchChoice.call(this, token, selection);
if (token !== undefined && token !== null && opts.id(token) !== undefined && opts.id(token) !== null) {
dupe = false;
for (i = 0, l = selection.length; i < l; i++) {
if (equal(opts.id(token), opts.id(selection[i]))) {
dupe = true; break;
}
}
if (!dupe) selectCallback(token);
}
}
}
if (original!==input) return input;
}
/**
* Creates a new class
*
* @param superClass
* @param methods
*/
function clazz(SuperClass, methods) {
var constructor = function () {};
constructor.prototype = new SuperClass;
constructor.prototype.constructor = constructor;
constructor.prototype.parent = SuperClass.prototype;
constructor.prototype = $.extend(constructor.prototype, methods);
return constructor;
}
AbstractSelect2 = clazz(Object, {
// abstract
bind: function (func) {
var self = this;
return function () {
func.apply(self, arguments);
};
},
// abstract
init: function (opts) {
var results, search, resultsSelector = ".select2-results";
// prepare options
this.opts = opts = this.prepareOpts(opts);
this.id=opts.id;
// destroy if called on an existing component
if (opts.element.data("select2") !== undefined &&
opts.element.data("select2") !== null) {
opts.element.data("select2").destroy();
}
this.container = this.createContainer();
this.containerId="s2id_"+(opts.element.attr("id") || "autogen"+nextUid());
this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
this.container.attr("id", this.containerId);
// cache the body so future lookups are cheap
this.body = thunk(function() { return opts.element.closest("body"); });
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.attr("style", opts.element.attr("style"));
this.container.css(evaluate(opts.containerCss));
this.container.addClass(evaluate(opts.containerCssClass));
this.elementTabIndex = this.opts.element.attr("tabindex");
// swap container for the element
this.opts.element
.data("select2", this)
.attr("tabindex", "-1")
.before(this.container)
.on("click.select2", killEvent); // do not leak click events
this.container.data("select2", this);
this.dropdown = this.container.find(".select2-drop");
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(opts.dropdownCssClass));
this.dropdown.data("select2", this);
this.dropdown.on("click", killEvent);
this.results = results = this.container.find(resultsSelector);
this.search = search = this.container.find("input.select2-input");
this.queryCount = 0;
this.resultsPage = 0;
this.context = null;
// initialize the container
this.initContainer();
this.container.on("click", killEvent);
installFilteredMouseMove(this.results);
this.dropdown.on("mousemove-filtered touchstart touchmove touchend", resultsSelector, this.bind(this.highlightUnderEvent));
installDebouncedScroll(80, this.results);
this.dropdown.on("scroll-debounced", resultsSelector, this.bind(this.loadMoreIfNeeded));
// do not propagate change event from the search field out of the component
$(this.container).on("change", ".select2-input", function(e) {e.stopPropagation();});
$(this.dropdown).on("change", ".select2-input", function(e) {e.stopPropagation();});
// if jquery.mousewheel plugin is installed we can prevent out-of-bounds scrolling of results via mousewheel
if ($.fn.mousewheel) {
results.mousewheel(function (e, delta, deltaX, deltaY) {
var top = results.scrollTop();
if (deltaY > 0 && top - deltaY <= 0) {
results.scrollTop(0);
killEvent(e);
} else if (deltaY < 0 && results.get(0).scrollHeight - results.scrollTop() + deltaY <= results.height()) {
results.scrollTop(results.get(0).scrollHeight - results.height());
killEvent(e);
}
});
}
installKeyUpChangeEvent(search);
search.on("keyup-change input paste", this.bind(this.updateResults));
search.on("focus", function () { search.addClass("select2-focused"); });
search.on("blur", function () { search.removeClass("select2-focused");});
this.dropdown.on("mouseup", resultsSelector, this.bind(function (e) {
if ($(e.target).closest(".select2-result-selectable").length > 0) {
this.highlightUnderEvent(e);
this.selectHighlighted(e);
}
}));
// trap all mouse events from leaving the dropdown. sometimes there may be a modal that is listening
// for mouse events outside of itself so it can close itself. since the dropdown is now outside the select2's
// dom it will trigger the popup close, which is not what we want
this.dropdown.on("click mouseup mousedown", function (e) { e.stopPropagation(); });
if ($.isFunction(this.opts.initSelection)) {
// initialize selection based on the current value of the source element
this.initSelection();
// if the user has provided a function that can set selection based on the value of the source element
// we monitor the change event on the element and trigger it, allowing for two way synchronization
this.monitorSource();
}
if (opts.maximumInputLength !== null) {
this.search.attr("maxlength", opts.maximumInputLength);
}
var disabled = opts.element.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = opts.element.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
// Calculate size of scrollbar
scrollBarDimensions = scrollBarDimensions || measureScrollbar();
this.autofocus = opts.element.prop("autofocus");
opts.element.prop("autofocus", false);
if (this.autofocus) this.focus();
this.nextSearchTerm = undefined;
},
// abstract
destroy: function () {
var element=this.opts.element, select2 = element.data("select2");
this.close();
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
if (select2 !== undefined) {
select2.container.remove();
select2.dropdown.remove();
element
.removeClass("select2-offscreen")
.removeData("select2")
.off(".select2")
.prop("autofocus", this.autofocus || false);
if (this.elementTabIndex) {
element.attr({tabindex: this.elementTabIndex});
} else {
element.removeAttr("tabindex");
}
element.show();
}
},
// abstract
optionToData: function(element) {
if (element.is("option")) {
return {
id:element.prop("value"),
text:element.text(),
element: element.get(),
css: element.attr("class"),
disabled: element.prop("disabled"),
locked: equal(element.attr("locked"), "locked") || equal(element.data("locked"), true)
};
} else if (element.is("optgroup")) {
return {
text:element.attr("label"),
children:[],
element: element.get(),
css: element.attr("class")
};
}
},
// abstract
prepareOpts: function (opts) {
var element, select, idKey, ajaxUrl, self = this;
element = opts.element;
if (element.get(0).tagName.toLowerCase() === "select") {
this.select = select = opts.element;
}
if (select) {
// these options are not allowed when attached to a select because they are picked up off the element itself
$.each(["id", "multiple", "ajax", "query", "createSearchChoice", "initSelection", "data", "tags"], function () {
if (this in opts) {
throw new Error("Option '" + this + "' is not allowed for Select2 when attached to a <select> element.");
}
});
}
opts = $.extend({}, {
populateResults: function(container, results, query) {
var populate, id=this.opts.id;
populate=function(results, container, depth) {
var i, l, result, selectable, disabled, compound, node, label, innerContainer, formatted;
results = opts.sortResults(results, container, query);
for (i = 0, l = results.length; i < l; i = i + 1) {
result=results[i];
disabled = (result.disabled === true);
selectable = (!disabled) && (id(result) !== undefined);
compound=result.children && result.children.length > 0;
node=$("<li></li>");
node.addClass("select2-results-dept-"+depth);
node.addClass("select2-result");
node.addClass(selectable ? "select2-result-selectable" : "select2-result-unselectable");
if (disabled) { node.addClass("select2-disabled"); }
if (compound) { node.addClass("select2-result-with-children"); }
node.addClass(self.opts.formatResultCssClass(result));
label=$(document.createElement("div"));
label.addClass("select2-result-label");
formatted=opts.formatResult(result, label, query, self.opts.escapeMarkup);
if (formatted!==undefined) {
label.html(formatted);
}
node.append(label);
if (compound) {
innerContainer=$("<ul></ul>");
innerContainer.addClass("select2-result-sub");
populate(result.children, innerContainer, depth+1);
node.append(innerContainer);
}
node.data("select2-data", result);
container.append(node);
}
};
populate(results, container, 0);
}
}, $.fn.select2.defaults, opts);
if (typeof(opts.id) !== "function") {
idKey = opts.id;
opts.id = function (e) { return e[idKey]; };
}
if ($.isArray(opts.element.data("select2Tags"))) {
if ("tags" in opts) {
throw "tags specified as both an attribute 'data-select2-tags' and in options of Select2 " + opts.element.attr("id");
}
opts.tags=opts.element.data("select2Tags");
}
if (select) {
opts.query = this.bind(function (query) {
var data = { results: [], more: false },
term = query.term,
children, placeholderOption, process;
process=function(element, collection) {
var group;
if (element.is("option")) {
if (query.matcher(term, element.text(), element)) {
collection.push(self.optionToData(element));
}
} else if (element.is("optgroup")) {
group=self.optionToData(element);
element.children().each2(function(i, elm) { process(elm, group.children); });
if (group.children.length>0) {
collection.push(group);
}
}
};
children=element.children();
// ignore the placeholder option if there is one
if (this.getPlaceholder() !== undefined && children.length > 0) {
placeholderOption = this.getPlaceholderOption();
if (placeholderOption) {
children=children.not(placeholderOption);
}
}
children.each2(function(i, elm) { process(elm, data.results); });
query.callback(data);
});
// this is needed because inside val() we construct choices from options and there id is hardcoded
opts.id=function(e) { return e.id; };
opts.formatResultCssClass = function(data) { return data.css; };
} else {
if (!("query" in opts)) {
if ("ajax" in opts) {
ajaxUrl = opts.element.data("ajax-url");
if (ajaxUrl && ajaxUrl.length > 0) {
opts.ajax.url = ajaxUrl;
}
opts.query = ajax.call(opts.element, opts.ajax);
} else if ("data" in opts) {
opts.query = local(opts.data);
} else if ("tags" in opts) {
opts.query = tags(opts.tags);
if (opts.createSearchChoice === undefined) {
opts.createSearchChoice = function (term) { return {id: $.trim(term), text: $.trim(term)}; };
}
if (opts.initSelection === undefined) {
opts.initSelection = function (element, callback) {
var data = [];
$(splitVal(element.val(), opts.separator)).each(function () {
var obj = { id: this, text: this },
tags = opts.tags;
if ($.isFunction(tags)) tags=tags();
$(tags).each(function() { if (equal(this.id, obj.id)) { obj = this; return false; } });
data.push(obj);
});
callback(data);
};
}
}
}
}
if (typeof(opts.query) !== "function") {
throw "query function not defined for Select2 " + opts.element.attr("id");
}
return opts;
},
/**
* Monitor the original element for changes and update select2 accordingly
*/
// abstract
monitorSource: function () {
var el = this.opts.element, sync, observer;
el.on("change.select2", this.bind(function (e) {
if (this.opts.element.data("select2-change-triggered") !== true) {
this.initSelection();
}
}));
sync = this.bind(function () {
// sync enabled state
var disabled = el.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = el.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.addClass(evaluate(this.opts.containerCssClass));
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(this.opts.dropdownCssClass));
});
// IE8-10
el.on("propertychange.select2", sync);
// hold onto a reference of the callback to work around a chromium bug
if (this.mutationCallback === undefined) {
this.mutationCallback = function (mutations) {
mutations.forEach(sync);
}
}
// safari, chrome, firefox, IE11
observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
if (observer !== undefined) {
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
this.propertyObserver = new observer(this.mutationCallback);
this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
}
},
// abstract
triggerSelect: function(data) {
var evt = $.Event("select2-selecting", { val: this.id(data), object: data });
this.opts.element.trigger(evt);
return !evt.isDefaultPrevented();
},
/**
* Triggers the change event on the source element
*/
// abstract
triggerChange: function (details) {
details = details || {};
details= $.extend({}, details, { type: "change", val: this.val() });
// prevents recursive triggering
this.opts.element.data("select2-change-triggered", true);
this.opts.element.trigger(details);
this.opts.element.data("select2-change-triggered", false);
// some validation frameworks ignore the change event and listen instead to keyup, click for selects
// so here we trigger the click event manually
this.opts.element.click();
// ValidationEngine ignorea the change event and listens instead to blur
// so here we trigger the blur event manually if so desired
if (this.opts.blurOnChange)
this.opts.element.blur();
},
//abstract
isInterfaceEnabled: function()
{
return this.enabledInterface === true;
},
// abstract
enableInterface: function() {
var enabled = this._enabled && !this._readonly,
disabled = !enabled;
if (enabled === this.enabledInterface) return false;
this.container.toggleClass("select2-container-disabled", disabled);
this.close();
this.enabledInterface = enabled;
return true;
},
// abstract
enable: function(enabled) {
if (enabled === undefined) enabled = true;
if (this._enabled === enabled) return;
this._enabled = enabled;
this.opts.element.prop("disabled", !enabled);
this.enableInterface();
},
// abstract
disable: function() {
this.enable(false);
},
// abstract
readonly: function(enabled) {
if (enabled === undefined) enabled = false;
if (this._readonly === enabled) return false;
this._readonly = enabled;
this.opts.element.prop("readonly", enabled);
this.enableInterface();
return true;
},
// abstract
opened: function () {
return this.container.hasClass("select2-dropdown-open");
},
// abstract
positionDropdown: function() {
var $dropdown = this.dropdown,
offset = this.container.offset(),
height = this.container.outerHeight(false),
width = this.container.outerWidth(false),
dropHeight = $dropdown.outerHeight(false),
$window = $(window),
windowWidth = $window.width(),
windowHeight = $window.height(),
viewPortRight = $window.scrollLeft() + windowWidth,
viewportBottom = $window.scrollTop() + windowHeight,
dropTop = offset.top + height,
dropLeft = offset.left,
enoughRoomBelow = dropTop + dropHeight <= viewportBottom,
enoughRoomAbove = (offset.top - dropHeight) >= this.body().scrollTop(),
dropWidth = $dropdown.outerWidth(false),
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight,
aboveNow = $dropdown.hasClass("select2-drop-above"),
bodyOffset,
above,
changeDirection,
css,
resultsListNode;
// always prefer the current above/below alignment, unless there is not enough room
if (aboveNow) {
above = true;
if (!enoughRoomAbove && enoughRoomBelow) {
changeDirection = true;
above = false;
}
} else {
above = false;
if (!enoughRoomBelow && enoughRoomAbove) {
changeDirection = true;
above = true;
}
}
//if we are changing direction we need to get positions when dropdown is hidden;
if (changeDirection) {
$dropdown.hide();
offset = this.container.offset();
height = this.container.outerHeight(false);
width = this.container.outerWidth(false);
dropHeight = $dropdown.outerHeight(false);
viewPortRight = $window.scrollLeft() + windowWidth;
viewportBottom = $window.scrollTop() + windowHeight;
dropTop = offset.top + height;
dropLeft = offset.left;
dropWidth = $dropdown.outerWidth(false);
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
$dropdown.show();
}
if (this.opts.dropdownAutoWidth) {
resultsListNode = $('.select2-results', $dropdown)[0];
$dropdown.addClass('select2-drop-auto-width');
$dropdown.css('width', '');
// Add scrollbar width to dropdown if vertical scrollbar is present
dropWidth = $dropdown.outerWidth(false) + (resultsListNode.scrollHeight === resultsListNode.clientHeight ? 0 : scrollBarDimensions.width);
dropWidth > width ? width = dropWidth : dropWidth = width;
enoughRoomOnRight = dropLeft + dropWidth <= viewPortRight;
}
else {
this.container.removeClass('select2-drop-auto-width');
}
//console.log("below/ droptop:", dropTop, "dropHeight", dropHeight, "sum", (dropTop+dropHeight)+" viewport bottom", viewportBottom, "enough?", enoughRoomBelow);
//console.log("above/ offset.top", offset.top, "dropHeight", dropHeight, "top", (offset.top-dropHeight), "scrollTop", this.body().scrollTop(), "enough?", enoughRoomAbove);
// fix positioning when body has an offset and is not position: static
if (this.body().css('position') !== 'static') {
bodyOffset = this.body().offset();
dropTop -= bodyOffset.top;
dropLeft -= bodyOffset.left;
}
if (!enoughRoomOnRight) {
dropLeft = offset.left + width - dropWidth;
}
css = {
left: dropLeft,
width: width
};
if (above) {
css.bottom = windowHeight - offset.top;
css.top = 'auto';
this.container.addClass("select2-drop-above");
$dropdown.addClass("select2-drop-above");
}
else {
css.top = dropTop;
css.bottom = 'auto';
this.container.removeClass("select2-drop-above");
$dropdown.removeClass("select2-drop-above");
}
css = $.extend(css, evaluate(this.opts.dropdownCss));
$dropdown.css(css);
},
// abstract
shouldOpen: function() {
var event;
if (this.opened()) return false;
if (this._enabled === false || this._readonly === true) return false;
event = $.Event("select2-opening");
this.opts.element.trigger(event);
return !event.isDefaultPrevented();
},
// abstract
clearDropdownAlignmentPreference: function() {
// clear the classes used to figure out the preference of where the dropdown should be opened
this.container.removeClass("select2-drop-above");
this.dropdown.removeClass("select2-drop-above");
},
/**
* Opens the dropdown
*
* @return {Boolean} whether or not dropdown was opened. This method will return false if, for example,
* the dropdown is already open, or if the 'open' event listener on the element called preventDefault().
*/
// abstract
open: function () {
if (!this.shouldOpen()) return false;
this.opening();
return true;
},
/**
* Performs the opening of the dropdown
*/
// abstract
opening: function() {
var cid = this.containerId,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid,
mask;
this.container.addClass("select2-dropdown-open").addClass("select2-container-active");
this.clearDropdownAlignmentPreference();
if(this.dropdown[0] !== this.body().children().last()[0]) {
this.dropdown.detach().appendTo(this.body());
}
// create the dropdown mask if doesnt already exist
mask = $("#select2-drop-mask");
if (mask.length == 0) {
mask = $(document.createElement("div"));
mask.attr("id","select2-drop-mask").attr("class","select2-drop-mask");
mask.hide();
mask.appendTo(this.body());
mask.on("mousedown touchstart click", function (e) {
var dropdown = $("#select2-drop"), self;
if (dropdown.length > 0) {
self=dropdown.data("select2");
if (self.opts.selectOnBlur) {
self.selectHighlighted({noFocus: true});
}
self.close({focus:true});
e.preventDefault();
e.stopPropagation();
}
});
}
// ensure the mask is always right before the dropdown
if (this.dropdown.prev()[0] !== mask[0]) {
this.dropdown.before(mask);
}
// move the global id to the correct dropdown
$("#select2-drop").removeAttr("id");
this.dropdown.attr("id", "select2-drop");
// show the elements
mask.show();
this.positionDropdown();
this.dropdown.show();
this.positionDropdown();
this.dropdown.addClass("select2-drop-active");
// attach listeners to events that can change the position of the container and thus require
// the position of the dropdown to be updated as well so it does not come unglued from the container
var that = this;
this.container.parents().add(window).each(function () {
$(this).on(resize+" "+scroll+" "+orient, function (e) {
that.positionDropdown();
});
});
},
// abstract
close: function () {
if (!this.opened()) return;
var cid = this.containerId,
scroll = "scroll." + cid,
resize = "resize."+cid,
orient = "orientationchange."+cid;
// unbind event listeners
this.container.parents().add(window).each(function () { $(this).off(scroll).off(resize).off(orient); });
this.clearDropdownAlignmentPreference();
$("#select2-drop-mask").hide();
this.dropdown.removeAttr("id"); // only the active dropdown has the select2-drop id
this.dropdown.hide();
this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active");
this.results.empty();
this.clearSearch();
this.search.removeClass("select2-active");
this.opts.element.trigger($.Event("select2-close"));
},
/**
* Opens control, sets input value, and updates results.
*/
// abstract
externalSearch: function (term) {
this.open();
this.search.val(term);
this.updateResults(false);
},
// abstract
clearSearch: function () {
},
//abstract
getMaximumSelectionSize: function() {
return evaluate(this.opts.maximumSelectionSize);
},
// abstract
ensureHighlightVisible: function () {
var results = this.results, children, index, child, hb, rb, y, more;
index = this.highlight();
if (index < 0) return;
if (index == 0) {
// if the first element is highlighted scroll all the way to the top,
// that way any unselectable headers above it will also be scrolled
// into view
results.scrollTop(0);
return;
}
children = this.findHighlightableChoices().find('.select2-result-label');
child = $(children[index]);
hb = child.offset().top + child.outerHeight(true);
// if this is the last child lets also make sure select2-more-results is visible
if (index === children.length - 1) {
more = results.find("li.select2-more-results");
if (more.length > 0) {
hb = more.offset().top + more.outerHeight(true);
}
}
rb = results.offset().top + results.outerHeight(true);
if (hb > rb) {
results.scrollTop(results.scrollTop() + (hb - rb));
}
y = child.offset().top - results.offset().top;
// make sure the top of the element is visible
if (y < 0 && child.css('display') != 'none' ) {
results.scrollTop(results.scrollTop() + y); // y is negative
}
},
// abstract
findHighlightableChoices: function() {
return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)");
},
// abstract
moveHighlight: function (delta) {
var choices = this.findHighlightableChoices(),
index = this.highlight();
while (index > -1 && index < choices.length) {
index += delta;
var choice = $(choices[index]);
if (choice.hasClass("select2-result-selectable") && !choice.hasClass("select2-disabled") && !choice.hasClass("select2-selected")) {
this.highlight(index);
break;
}
}
},
// abstract
highlight: function (index) {
var choices = this.findHighlightableChoices(),
choice,
data;
if (arguments.length === 0) {
return indexOf(choices.filter(".select2-highlighted")[0], choices.get());
}
if (index >= choices.length) index = choices.length - 1;
if (index < 0) index = 0;
this.removeHighlight();
choice = $(choices[index]);
choice.addClass("select2-highlighted");
this.ensureHighlightVisible();
data = choice.data("select2-data");
if (data) {
this.opts.element.trigger({ type: "select2-highlight", val: this.id(data), choice: data });
}
},
removeHighlight: function() {
this.results.find(".select2-highlighted").removeClass("select2-highlighted");
},
// abstract
countSelectableResults: function() {
return this.findHighlightableChoices().length;
},
// abstract
highlightUnderEvent: function (event) {
var el = $(event.target).closest(".select2-result-selectable");
if (el.length > 0 && !el.is(".select2-highlighted")) {
var choices = this.findHighlightableChoices();
this.highlight(choices.index(el));
} else if (el.length == 0) {
// if we are over an unselectable item remove all highlights
this.removeHighlight();
}
},
// abstract
loadMoreIfNeeded: function () {
var results = this.results,
more = results.find("li.select2-more-results"),
below, // pixels the element is below the scroll fold, below==0 is when the element is starting to be visible
page = this.resultsPage + 1,
self=this,
term=this.search.val(),
context=this.context;
if (more.length === 0) return;
below = more.offset().top - results.offset().top - results.height();
if (below <= this.opts.loadMorePadding) {
more.addClass("select2-active");
this.opts.query({
element: this.opts.element,
term: term,
page: page,
context: context,
matcher: this.opts.matcher,
callback: this.bind(function (data) {
// ignore a response if the select2 has been closed before it was received
if (!self.opened()) return;
self.opts.populateResults.call(this, results, data.results, {term: term, page: page, context:context});
self.postprocessResults(data, false, false);
if (data.more===true) {
more.detach().appendTo(results).text(self.opts.formatLoadMore(page+1));
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
} else {
more.remove();
}
self.positionDropdown();
self.resultsPage = page;
self.context = data.context;
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
}
},
/**
* Default tokenizer function which does nothing
*/
tokenize: function() {
},
/**
* @param initial whether or not this is the call to this method right after the dropdown has been opened
*/
// abstract
updateResults: function (initial) {
var search = this.search,
results = this.results,
opts = this.opts,
data,
self = this,
input,
term = search.val(),
lastTerm = $.data(this.container, "select2-last-term"),
// sequence number used to drop out-of-order responses
queryNumber;
// prevent duplicate queries against the same term
if (initial !== true && lastTerm && equal(term, lastTerm)) return;
$.data(this.container, "select2-last-term", term);
// if the search is currently hidden we do not alter the results
if (initial !== true && (this.showSearchInput === false || !this.opened())) {
return;
}
function postRender() {
search.removeClass("select2-active");
self.positionDropdown();
}
function render(html) {
results.html(html);
postRender();
}
queryNumber = ++this.queryCount;
var maxSelSize = this.getMaximumSelectionSize();
if (maxSelSize >=1) {
data = this.data();
if ($.isArray(data) && data.length >= maxSelSize && checkFormatter(opts.formatSelectionTooBig, "formatSelectionTooBig")) {
render("<li class='select2-selection-limit'>" + opts.formatSelectionTooBig(maxSelSize) + "</li>");
return;
}
}
if (search.val().length < opts.minimumInputLength) {
if (checkFormatter(opts.formatInputTooShort, "formatInputTooShort")) {
render("<li class='select2-no-results'>" + opts.formatInputTooShort(search.val(), opts.minimumInputLength) + "</li>");
} else {
render("");
}
if (initial && this.showSearch) this.showSearch(true);
return;
}
if (opts.maximumInputLength && search.val().length > opts.maximumInputLength) {
if (checkFormatter(opts.formatInputTooLong, "formatInputTooLong")) {
render("<li class='select2-no-results'>" + opts.formatInputTooLong(search.val(), opts.maximumInputLength) + "</li>");
} else {
render("");
}
return;
}
if (opts.formatSearching && this.findHighlightableChoices().length === 0) {
render("<li class='select2-searching'>" + opts.formatSearching() + "</li>");
}
search.addClass("select2-active");
this.removeHighlight();
// give the tokenizer a chance to pre-process the input
input = this.tokenize();
if (input != undefined && input != null) {
search.val(input);
}
this.resultsPage = 1;
opts.query({
element: opts.element,
term: search.val(),
page: this.resultsPage,
context: null,
matcher: opts.matcher,
callback: this.bind(function (data) {
var def; // default choice
// ignore old responses
if (queryNumber != this.queryCount) {
return;
}
// ignore a response if the select2 has been closed before it was received
if (!this.opened()) {
this.search.removeClass("select2-active");
return;
}
// save context, if any
this.context = (data.context===undefined) ? null : data.context;
// create a default choice and prepend it to the list
if (this.opts.createSearchChoice && search.val() !== "") {
def = this.opts.createSearchChoice.call(self, search.val(), data.results);
if (def !== undefined && def !== null && self.id(def) !== undefined && self.id(def) !== null) {
if ($(data.results).filter(
function () {
return equal(self.id(this), self.id(def));
}).length === 0) {
data.results.unshift(def);
}
}
}
if (data.results.length === 0 && checkFormatter(opts.formatNoMatches, "formatNoMatches")) {
render("<li class='select2-no-results'>" + opts.formatNoMatches(search.val()) + "</li>");
return;
}
results.empty();
self.opts.populateResults.call(this, results, data.results, {term: search.val(), page: this.resultsPage, context:null});
if (data.more === true && checkFormatter(opts.formatLoadMore, "formatLoadMore")) {
results.append("<li class='select2-more-results'>" + self.opts.escapeMarkup(opts.formatLoadMore(this.resultsPage)) + "</li>");
window.setTimeout(function() { self.loadMoreIfNeeded(); }, 10);
}
this.postprocessResults(data, initial);
postRender();
this.opts.element.trigger({ type: "select2-loaded", items: data });
})});
},
// abstract
cancel: function () {
this.close();
},
// abstract
blur: function () {
// if selectOnBlur == true, select the currently highlighted option
if (this.opts.selectOnBlur)
this.selectHighlighted({noFocus: true});
this.close();
this.container.removeClass("select2-container-active");
// synonymous to .is(':focus'), which is available in jquery >= 1.6
if (this.search[0] === document.activeElement) { this.search.blur(); }
this.clearSearch();
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
},
// abstract
focusSearch: function () {
focus(this.search);
},
// abstract
selectHighlighted: function (options) {
var index=this.highlight(),
highlighted=this.results.find(".select2-highlighted"),
data = highlighted.closest('.select2-result').data("select2-data");
if (data) {
this.highlight(index);
this.onSelect(data, options);
} else if (options && options.noFocus) {
this.close();
}
},
// abstract
getPlaceholder: function () {
var placeholderOption;
return this.opts.element.attr("placeholder") ||
this.opts.element.attr("data-placeholder") || // jquery 1.4 compat
this.opts.element.data("placeholder") ||
this.opts.placeholder ||
((placeholderOption = this.getPlaceholderOption()) !== undefined ? placeholderOption.text() : undefined);
},
// abstract
getPlaceholderOption: function() {
if (this.select) {
var firstOption = this.select.children('option').first();
if (this.opts.placeholderOption !== undefined ) {
//Determine the placeholder option based on the specified placeholderOption setting
return (this.opts.placeholderOption === "first" && firstOption) ||
(typeof this.opts.placeholderOption === "function" && this.opts.placeholderOption(this.select));
} else if (firstOption.text() === "" && firstOption.val() === "") {
//No explicit placeholder option specified, use the first if it's blank
return firstOption;
}
}
},
/**
* Get the desired width for the container element. This is
* derived first from option `width` passed to select2, then
* the inline 'style' on the original element, and finally
* falls back to the jQuery calculated element width.
*/
// abstract
initContainerWidth: function () {
function resolveContainerWidth() {
var style, attrs, matches, i, l, attr;
if (this.opts.width === "off") {
return null;
} else if (this.opts.width === "element"){
return this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px';
} else if (this.opts.width === "copy" || this.opts.width === "resolve") {
// check if there is inline style on the element that contains width
style = this.opts.element.attr('style');
if (style !== undefined) {
attrs = style.split(';');
for (i = 0, l = attrs.length; i < l; i = i + 1) {
attr = attrs[i].replace(/\s/g, '');
matches = attr.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i);
if (matches !== null && matches.length >= 1)
return matches[1];
}
}
if (this.opts.width === "resolve") {
// next check if css('width') can resolve a width that is percent based, this is sometimes possible
// when attached to input type=hidden or elements hidden via css
style = this.opts.element.css('width');
if (style.indexOf("%") > 0) return style;
// finally, fallback on the calculated width of the element
return (this.opts.element.outerWidth(false) === 0 ? 'auto' : this.opts.element.outerWidth(false) + 'px');
}
return null;
} else if ($.isFunction(this.opts.width)) {
return this.opts.width();
} else {
return this.opts.width;
}
};
var width = resolveContainerWidth.call(this);
if (width !== null) {
this.container.css("width", width);
}
}
});
SingleSelect2 = clazz(AbstractSelect2, {
// single
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container"
}).html([
"<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>",
" <span class='select2-chosen'> </span><abbr class='select2-search-choice-close'></abbr>",
" <span class='select2-arrow'><b></b></span>",
"</a>",
"<input class='select2-focusser select2-offscreen' type='text'/>",
"<div class='select2-drop select2-display-none'>",
" <div class='select2-search'>",
" <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>",
" </div>",
" <ul class='select2-results'>",
" </ul>",
"</div>"].join(""));
return container;
},
// single
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.focusser.prop("disabled", !this.isInterfaceEnabled());
}
},
// single
opening: function () {
var el, range, len;
if (this.opts.minimumResultsForSearch >= 0) {
this.showSearch(true);
}
this.parent.opening.apply(this, arguments);
if (this.showSearchInput !== false) {
// IE appends focusser.val() at the end of field :/ so we manually insert it at the beginning using a range
// all other browsers handle this just fine
this.search.val(this.focusser.val());
}
this.search.focus();
// move the cursor to the end after focussing, otherwise it will be at the beginning and
// new text will appear *before* focusser.val()
el = this.search.get(0);
if (el.createTextRange) {
range = el.createTextRange();
range.collapse(false);
range.select();
} else if (el.setSelectionRange) {
len = this.search.val().length;
el.setSelectionRange(len, len);
}
// initializes search's value with nextSearchTerm (if defined by user)
// ignore nextSearchTerm if the dropdown is opened by the user pressing a letter
if(this.search.val() === "") {
if(this.nextSearchTerm != undefined){
this.search.val(this.nextSearchTerm);
this.search.select();
}
}
this.focusser.prop("disabled", true).val("");
this.updateResults(true);
this.opts.element.trigger($.Event("select2-open"));
},
// single
close: function (params) {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
params = params || {focus: true};
this.focusser.removeAttr("disabled");
if (params.focus) {
this.focusser.focus();
}
},
// single
focus: function () {
if (this.opened()) {
this.close();
} else {
this.focusser.removeAttr("disabled");
this.focusser.focus();
}
},
// single
isFocused: function () {
return this.container.hasClass("select2-container-active");
},
// single
cancel: function () {
this.parent.cancel.apply(this, arguments);
this.focusser.removeAttr("disabled");
this.focusser.focus();
},
// single
destroy: function() {
$("label[for='" + this.focusser.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
},
// single
initContainer: function () {
var selection,
container = this.container,
dropdown = this.dropdown;
if (this.opts.minimumResultsForSearch < 0) {
this.showSearch(false);
} else {
this.showSearch(true);
}
this.selection = selection = container.find(".select2-choice");
this.focusser = container.find(".select2-focusser");
// rewrite labels from original element to focusser
this.focusser.attr("id", "s2id_autogen"+nextUid());
$("label[for='" + this.opts.element.attr("id") + "']")
.attr('for', this.focusser.attr('id'));
this.focusser.attr("tabindex", this.elementTabIndex);
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
return;
}
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus: true});
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}));
this.search.on("blur", this.bind(function(e) {
// a workaround for chrome to keep the search field focussed when the scroll bar is used to scroll the dropdown.
// without this the search field loses focus which is annoying
if (document.activeElement === this.body().get(0)) {
window.setTimeout(this.bind(function() {
this.search.focus();
}), 0);
}
}));
this.focusser.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (this.opts.openOnEnter === false && e.which === KEY.ENTER) {
killEvent(e);
return;
}
if (e.which == KEY.DOWN || e.which == KEY.UP
|| (e.which == KEY.ENTER && this.opts.openOnEnter)) {
if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) return;
this.open();
killEvent(e);
return;
}
if (e.which == KEY.DELETE || e.which == KEY.BACKSPACE) {
if (this.opts.allowClear) {
this.clear();
}
killEvent(e);
return;
}
}));
installKeyUpChangeEvent(this.focusser);
this.focusser.on("keyup-change input", this.bind(function(e) {
if (this.opts.minimumResultsForSearch >= 0) {
e.stopPropagation();
if (this.opened()) return;
this.open();
}
}));
selection.on("mousedown", "abbr", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
this.clear();
killEventImmediately(e);
this.close();
this.selection.focus();
}));
selection.on("mousedown", this.bind(function (e) {
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
if (this.opened()) {
this.close();
} else if (this.isInterfaceEnabled()) {
this.open();
}
killEvent(e);
}));
dropdown.on("mousedown", this.bind(function() { this.search.focus(); }));
selection.on("focus", this.bind(function(e) {
killEvent(e);
}));
this.focusser.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
})).on("blur", this.bind(function() {
if (!this.opened()) {
this.container.removeClass("select2-container-active");
this.opts.element.trigger($.Event("select2-blur"));
}
}));
this.search.on("focus", this.bind(function(){
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
this.setPlaceholder();
},
// single
clear: function(triggerChange) {
var data=this.selection.data("select2-data");
if (data) { // guard against queued quick consecutive clicks
var evt = $.Event("select2-clearing");
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return;
}
var placeholderOption = this.getPlaceholderOption();
this.opts.element.val(placeholderOption ? placeholderOption.val() : "");
this.selection.find(".select2-chosen").empty();
this.selection.removeData("select2-data");
this.setPlaceholder();
if (triggerChange !== false){
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({removed:data});
}
}
},
/**
* Sets selection based on source element's value
*/
// single
initSelection: function () {
var selected;
if (this.isPlaceholderOptionSelected()) {
this.updateSelection(null);
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
},
isPlaceholderOptionSelected: function() {
var placeholderOption;
if (!this.getPlaceholder()) return false; // no placeholder specified so no option should be considered
return ((placeholderOption = this.getPlaceholderOption()) !== undefined && placeholderOption.prop("selected"))
|| (this.opts.element.val() === "")
|| (this.opts.element.val() === undefined)
|| (this.opts.element.val() === null);
},
// single
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install the selection initializer
opts.initSelection = function (element, callback) {
var selected = element.find("option").filter(function() { return this.selected });
// a single select box always has a value, no need to null check 'selected'
callback(self.optionToData(selected));
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var id = element.val();
//search in data by id, storing the actual matching item
var match = null;
opts.query({
matcher: function(term, text, el){
var is_match = equal(id, opts.id(el));
if (is_match) {
match = el;
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
callback(match);
}
});
};
}
return opts;
},
// single
getPlaceholder: function() {
// if a placeholder is specified on a single select without a valid placeholder option ignore it
if (this.select) {
if (this.getPlaceholderOption() === undefined) {
return undefined;
}
}
return this.parent.getPlaceholder.apply(this, arguments);
},
// single
setPlaceholder: function () {
var placeholder = this.getPlaceholder();
if (this.isPlaceholderOptionSelected() && placeholder !== undefined) {
// check for a placeholder option if attached to a select
if (this.select && this.getPlaceholderOption() === undefined) return;
this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(placeholder));
this.selection.addClass("select2-default");
this.container.removeClass("select2-allowclear");
}
},
// single
postprocessResults: function (data, initial, noHighlightUpdate) {
var selected = 0, self = this, showSearchInput = true;
// find the selected element in the result list
this.findHighlightableChoices().each2(function (i, elm) {
if (equal(self.id(elm.data("select2-data")), self.opts.element.val())) {
selected = i;
return false;
}
});
// and highlight it
if (noHighlightUpdate !== false) {
if (initial === true && selected >= 0) {
this.highlight(selected);
} else {
this.highlight(0);
}
}
// hide the search box if this is the first we got the results and there are enough of them for search
if (initial === true) {
var min = this.opts.minimumResultsForSearch;
if (min >= 0) {
this.showSearch(countResults(data.results) >= min);
}
}
},
// single
showSearch: function(showSearchInput) {
if (this.showSearchInput === showSearchInput) return;
this.showSearchInput = showSearchInput;
this.dropdown.find(".select2-search").toggleClass("select2-search-hidden", !showSearchInput);
this.dropdown.find(".select2-search").toggleClass("select2-offscreen", !showSearchInput);
//add "select2-with-searchbox" to the container if search box is shown
$(this.dropdown, this.container).toggleClass("select2-with-searchbox", showSearchInput);
},
// single
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
var old = this.opts.element.val(),
oldData = this.data();
this.opts.element.val(this.id(data));
this.updateSelection(data);
this.opts.element.trigger({ type: "select2-selected", val: this.id(data), choice: data });
this.nextSearchTerm = this.opts.nextSearchTerm(data, this.search.val());
this.close();
if (!options || !options.noFocus)
this.focusser.focus();
if (!equal(old, this.id(data))) { this.triggerChange({added:data,removed:oldData}); }
},
// single
updateSelection: function (data) {
var container=this.selection.find(".select2-chosen"), formatted, cssClass;
this.selection.data("select2-data", data);
container.empty();
if (data !== null) {
formatted=this.opts.formatSelection(data, container, this.opts.escapeMarkup);
}
if (formatted !== undefined) {
container.append(formatted);
}
cssClass=this.opts.formatSelectionCssClass(data, container);
if (cssClass !== undefined) {
container.addClass(cssClass);
}
this.selection.removeClass("select2-default");
if (this.opts.allowClear && this.getPlaceholder() !== undefined) {
this.container.addClass("select2-allowclear");
}
},
// single
val: function () {
var val,
triggerChange = false,
data = null,
self = this,
oldData = this.data();
if (arguments.length === 0) {
return this.opts.element.val();
}
val = arguments[0];
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (this.select) {
this.select
.val(val)
.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
data = self.optionToData(elm);
return false;
});
this.updateSelection(data);
this.setPlaceholder();
if (triggerChange) {
this.triggerChange({added: data, removed:oldData});
}
} else {
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.clear(triggerChange);
return;
}
if (this.opts.initSelection === undefined) {
throw new Error("cannot call val() if initSelection() is not defined");
}
this.opts.element.val(val);
this.opts.initSelection(this.opts.element, function(data){
self.opts.element.val(!data ? "" : self.id(data));
self.updateSelection(data);
self.setPlaceholder();
if (triggerChange) {
self.triggerChange({added: data, removed:oldData});
}
});
}
},
// single
clearSearch: function () {
this.search.val("");
this.focusser.val("");
},
// single
data: function(value) {
var data,
triggerChange = false;
if (arguments.length === 0) {
data = this.selection.data("select2-data");
if (data == undefined) data = null;
return data;
} else {
if (arguments.length > 1) {
triggerChange = arguments[1];
}
if (!value) {
this.clear(triggerChange);
} else {
data = this.data();
this.opts.element.val(!value ? "" : this.id(value));
this.updateSelection(value);
if (triggerChange) {
this.triggerChange({added: value, removed:data});
}
}
}
}
});
MultiSelect2 = clazz(AbstractSelect2, {
// multi
createContainer: function () {
var container = $(document.createElement("div")).attr({
"class": "select2-container select2-container-multi"
}).html([
"<ul class='select2-choices'>",
" <li class='select2-search-field'>",
" <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>",
" </li>",
"</ul>",
"<div class='select2-drop select2-drop-multi select2-display-none'>",
" <ul class='select2-results'>",
" </ul>",
"</div>"].join(""));
return container;
},
// multi
prepareOpts: function () {
var opts = this.parent.prepareOpts.apply(this, arguments),
self=this;
// TODO validate placeholder is a string if specified
if (opts.element.get(0).tagName.toLowerCase() === "select") {
// install sthe selection initializer
opts.initSelection = function (element, callback) {
var data = [];
element.find("option").filter(function() { return this.selected }).each2(function (i, elm) {
data.push(self.optionToData(elm));
});
callback(data);
};
} else if ("data" in opts) {
// install default initSelection when applied to hidden input and data is local
opts.initSelection = opts.initSelection || function (element, callback) {
var ids = splitVal(element.val(), opts.separator);
//search in data by array of ids, storing matching items in a list
var matches = [];
opts.query({
matcher: function(term, text, el){
var is_match = $.grep(ids, function(id) {
return equal(id, opts.id(el));
}).length;
if (is_match) {
matches.push(el);
}
return is_match;
},
callback: !$.isFunction(callback) ? $.noop : function() {
// reorder matches based on the order they appear in the ids array because right now
// they are in the order in which they appear in data array
var ordered = [];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
for (var j = 0; j < matches.length; j++) {
var match = matches[j];
if (equal(id, opts.id(match))) {
ordered.push(match);
matches.splice(j, 1);
break;
}
}
}
callback(ordered);
}
});
};
}
return opts;
},
// multi
selectChoice: function (choice) {
var selected = this.container.find(".select2-search-choice-focus");
if (selected.length && choice && choice[0] == selected[0]) {
} else {
if (selected.length) {
this.opts.element.trigger("choice-deselected", selected);
}
selected.removeClass("select2-search-choice-focus");
if (choice && choice.length) {
this.close();
choice.addClass("select2-search-choice-focus");
this.opts.element.trigger("choice-selected", choice);
}
}
},
// multi
destroy: function() {
$("label[for='" + this.search.attr('id') + "']")
.attr('for', this.opts.element.attr("id"));
this.parent.destroy.apply(this, arguments);
},
// multi
initContainer: function () {
var selector = ".select2-choices", selection;
this.searchContainer = this.container.find(".select2-search-field");
this.selection = selection = this.container.find(selector);
var _this = this;
this.selection.on("click", ".select2-search-choice:not(.select2-locked)", function (e) {
//killEvent(e);
_this.search[0].focus();
_this.selectChoice($(this));
});
// rewrite labels from original element to focusser
this.search.attr("id", "s2id_autogen"+nextUid());
$("label[for='" + this.opts.element.attr("id") + "']")
.attr('for', this.search.attr('id'));
this.search.on("input paste", this.bind(function() {
if (!this.isInterfaceEnabled()) return;
if (!this.opened()) {
this.open();
}
}));
this.search.attr("tabindex", this.elementTabIndex);
this.keydowns = 0;
this.search.on("keydown", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
++this.keydowns;
var selected = selection.find(".select2-search-choice-focus");
var prev = selected.prev(".select2-search-choice:not(.select2-locked)");
var next = selected.next(".select2-search-choice:not(.select2-locked)");
var pos = getCursorInfo(this.search);
if (selected.length &&
(e.which == KEY.LEFT || e.which == KEY.RIGHT || e.which == KEY.BACKSPACE || e.which == KEY.DELETE || e.which == KEY.ENTER)) {
var selectedChoice = selected;
if (e.which == KEY.LEFT && prev.length) {
selectedChoice = prev;
}
else if (e.which == KEY.RIGHT) {
selectedChoice = next.length ? next : null;
}
else if (e.which === KEY.BACKSPACE) {
this.unselect(selected.first());
this.search.width(10);
selectedChoice = prev.length ? prev : next;
} else if (e.which == KEY.DELETE) {
this.unselect(selected.first());
this.search.width(10);
selectedChoice = next.length ? next : null;
} else if (e.which == KEY.ENTER) {
selectedChoice = null;
}
this.selectChoice(selectedChoice);
killEvent(e);
if (!selectedChoice || !selectedChoice.length) {
this.open();
}
return;
} else if (((e.which === KEY.BACKSPACE && this.keydowns == 1)
|| e.which == KEY.LEFT) && (pos.offset == 0 && !pos.length)) {
this.selectChoice(selection.find(".select2-search-choice:not(.select2-locked)").last());
killEvent(e);
return;
} else {
this.selectChoice(null);
}
if (this.opened()) {
switch (e.which) {
case KEY.UP:
case KEY.DOWN:
this.moveHighlight((e.which === KEY.UP) ? -1 : 1);
killEvent(e);
return;
case KEY.ENTER:
this.selectHighlighted();
killEvent(e);
return;
case KEY.TAB:
this.selectHighlighted({noFocus:true});
this.close();
return;
case KEY.ESC:
this.cancel(e);
killEvent(e);
return;
}
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e)
|| e.which === KEY.BACKSPACE || e.which === KEY.ESC) {
return;
}
if (e.which === KEY.ENTER) {
if (this.opts.openOnEnter === false) {
return;
} else if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
return;
}
}
this.open();
if (e.which === KEY.PAGE_UP || e.which === KEY.PAGE_DOWN) {
// prevent the page from scrolling
killEvent(e);
}
if (e.which === KEY.ENTER) {
// prevent form from being submitted
killEvent(e);
}
}));
this.search.on("keyup", this.bind(function (e) {
this.keydowns = 0;
this.resizeSearch();
})
);
this.search.on("blur", this.bind(function(e) {
this.container.removeClass("select2-container-active");
this.search.removeClass("select2-focused");
this.selectChoice(null);
if (!this.opened()) this.clearSearch();
e.stopImmediatePropagation();
this.opts.element.trigger($.Event("select2-blur"));
}));
this.container.on("click", selector, this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
if ($(e.target).closest(".select2-search-choice").length > 0) {
// clicked inside a select2 search choice, do not open
return;
}
this.selectChoice(null);
this.clearPlaceholder();
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.open();
this.focusSearch();
e.preventDefault();
}));
this.container.on("focus", selector, this.bind(function () {
if (!this.isInterfaceEnabled()) return;
if (!this.container.hasClass("select2-container-active")) {
this.opts.element.trigger($.Event("select2-focus"));
}
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
this.clearPlaceholder();
}));
this.initContainerWidth();
this.opts.element.addClass("select2-offscreen");
// set the placeholder if necessary
this.clearSearch();
},
// multi
enableInterface: function() {
if (this.parent.enableInterface.apply(this, arguments)) {
this.search.prop("disabled", !this.isInterfaceEnabled());
}
},
// multi
initSelection: function () {
var data;
if (this.opts.element.val() === "" && this.opts.element.text() === "") {
this.updateSelection([]);
this.close();
// set the placeholder if necessary
this.clearSearch();
}
if (this.select || this.opts.element.val() !== "") {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(data){
if (data !== undefined && data !== null) {
self.updateSelection(data);
self.close();
// set the placeholder if necessary
self.clearSearch();
}
});
}
},
// multi
clearSearch: function () {
var placeholder = this.getPlaceholder(),
maxWidth = this.getMaxSearchWidth();
if (placeholder !== undefined && this.getVal().length === 0 && this.search.hasClass("select2-focused") === false) {
this.search.val(placeholder).addClass("select2-default");
// stretch the search box to full width of the container so as much of the placeholder is visible as possible
// we could call this.resizeSearch(), but we do not because that requires a sizer and we do not want to create one so early because of a firefox bug, see #944
this.search.width(maxWidth > 0 ? maxWidth : this.container.css("width"));
} else {
this.search.val("").width(10);
}
},
// multi
clearPlaceholder: function () {
if (this.search.hasClass("select2-default")) {
this.search.val("").removeClass("select2-default");
}
},
// multi
opening: function () {
this.clearPlaceholder(); // should be done before super so placeholder is not used to search
this.resizeSearch();
this.parent.opening.apply(this, arguments);
this.focusSearch();
this.updateResults(true);
this.search.focus();
this.opts.element.trigger($.Event("select2-open"));
},
// multi
close: function () {
if (!this.opened()) return;
this.parent.close.apply(this, arguments);
},
// multi
focus: function () {
this.close();
this.search.focus();
},
// multi
isFocused: function () {
return this.search.hasClass("select2-focused");
},
// multi
updateSelection: function (data) {
var ids = [], filtered = [], self = this;
// filter out duplicates
$(data).each(function () {
if (indexOf(self.id(this), ids) < 0) {
ids.push(self.id(this));
filtered.push(this);
}
});
data = filtered;
this.selection.find(".select2-search-choice").remove();
$(data).each(function () {
self.addSelectedChoice(this);
});
self.postprocessResults();
},
// multi
tokenize: function() {
var input = this.search.val();
input = this.opts.tokenizer.call(this, input, this.data(), this.bind(this.onSelect), this.opts);
if (input != null && input != undefined) {
this.search.val(input);
if (input.length > 0) {
this.open();
}
}
},
// multi
onSelect: function (data, options) {
if (!this.triggerSelect(data)) { return; }
this.addSelectedChoice(data);
this.opts.element.trigger({ type: "selected", val: this.id(data), choice: data });
if (this.select || !this.opts.closeOnSelect) this.postprocessResults(data, false, this.opts.closeOnSelect===true);
if (this.opts.closeOnSelect) {
this.close();
this.search.width(10);
} else {
if (this.countSelectableResults()>0) {
this.search.width(10);
this.resizeSearch();
if (this.getMaximumSelectionSize() > 0 && this.val().length >= this.getMaximumSelectionSize()) {
// if we reached max selection size repaint the results so choices
// are replaced with the max selection reached message
this.updateResults(true);
}
this.positionDropdown();
} else {
// if nothing left to select close
this.close();
this.search.width(10);
}
}
// since its not possible to select an element that has already been
// added we do not need to check if this is a new element before firing change
this.triggerChange({ added: data });
if (!options || !options.noFocus)
this.focusSearch();
},
// multi
cancel: function () {
this.close();
this.focusSearch();
},
addSelectedChoice: function (data) {
var enableChoice = !data.locked,
enabledItem = $(
"<li class='select2-search-choice'>" +
" <div></div>" +
" <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a>" +
"</li>"),
disabledItem = $(
"<li class='select2-search-choice select2-locked'>" +
"<div></div>" +
"</li>");
var choice = enableChoice ? enabledItem : disabledItem,
id = this.id(data),
val = this.getVal(),
formatted,
cssClass;
formatted=this.opts.formatSelection(data, choice.find("div"), this.opts.escapeMarkup);
if (formatted != undefined) {
choice.find("div").replaceWith("<div>"+formatted+"</div>");
}
cssClass=this.opts.formatSelectionCssClass(data, choice.find("div"));
if (cssClass != undefined) {
choice.addClass(cssClass);
}
if(enableChoice){
choice.find(".select2-search-choice-close")
.on("mousedown", killEvent)
.on("click dblclick", this.bind(function (e) {
if (!this.isInterfaceEnabled()) return;
$(e.target).closest(".select2-search-choice").fadeOut('fast', this.bind(function(){
this.unselect($(e.target));
this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus");
this.close();
this.focusSearch();
})).dequeue();
killEvent(e);
})).on("focus", this.bind(function () {
if (!this.isInterfaceEnabled()) return;
this.container.addClass("select2-container-active");
this.dropdown.addClass("select2-drop-active");
}));
}
choice.data("select2-data", data);
choice.insertBefore(this.searchContainer);
val.push(id);
this.setVal(val);
},
// multi
unselect: function (selected) {
var val = this.getVal(),
data,
index;
selected = selected.closest(".select2-search-choice");
if (selected.length === 0) {
throw "Invalid argument: " + selected + ". Must be .select2-search-choice";
}
data = selected.data("select2-data");
if (!data) {
// prevent a race condition when the 'x' is clicked really fast repeatedly the event can be queued
// and invoked on an element already removed
return;
}
while((index = indexOf(this.id(data), val)) >= 0) {
val.splice(index, 1);
this.setVal(val);
if (this.select) this.postprocessResults();
}
var evt = $.Event("select2-removing");
evt.val = this.id(data);
evt.choice = data;
this.opts.element.trigger(evt);
if (evt.isDefaultPrevented()) {
return;
}
selected.remove();
this.opts.element.trigger({ type: "select2-removed", val: this.id(data), choice: data });
this.triggerChange({ removed: data });
},
// multi
postprocessResults: function (data, initial, noHighlightUpdate) {
var val = this.getVal(),
choices = this.results.find(".select2-result"),
compound = this.results.find(".select2-result-with-children"),
self = this;
choices.each2(function (i, choice) {
var id = self.id(choice.data("select2-data"));
if (indexOf(id, val) >= 0) {
choice.addClass("select2-selected");
// mark all children of the selected parent as selected
choice.find(".select2-result-selectable").addClass("select2-selected");
}
});
compound.each2(function(i, choice) {
// hide an optgroup if it doesnt have any selectable children
if (!choice.is('.select2-result-selectable')
&& choice.find(".select2-result-selectable:not(.select2-selected)").length === 0) {
choice.addClass("select2-selected");
}
});
if (this.highlight() == -1 && noHighlightUpdate !== false){
self.highlight(0);
}
//If all results are chosen render formatNoMAtches
if(!this.opts.createSearchChoice && !choices.filter('.select2-result:not(.select2-selected)').length > 0){
if(!data || data && !data.more && this.results.find(".select2-no-results").length === 0) {
if (checkFormatter(self.opts.formatNoMatches, "formatNoMatches")) {
this.results.append("<li class='select2-no-results'>" + self.opts.formatNoMatches(self.search.val()) + "</li>");
}
}
}
},
// multi
getMaxSearchWidth: function() {
return this.selection.width() - getSideBorderPadding(this.search);
},
// multi
resizeSearch: function () {
var minimumWidth, left, maxWidth, containerLeft, searchWidth,
sideBorderPadding = getSideBorderPadding(this.search);
minimumWidth = measureTextWidth(this.search) + 10;
left = this.search.offset().left;
maxWidth = this.selection.width();
containerLeft = this.selection.offset().left;
searchWidth = maxWidth - (left - containerLeft) - sideBorderPadding;
if (searchWidth < minimumWidth) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth < 40) {
searchWidth = maxWidth - sideBorderPadding;
}
if (searchWidth <= 0) {
searchWidth = minimumWidth;
}
this.search.width(Math.floor(searchWidth));
},
// multi
getVal: function () {
var val;
if (this.select) {
val = this.select.val();
return val === null ? [] : val;
} else {
val = this.opts.element.val();
return splitVal(val, this.opts.separator);
}
},
// multi
setVal: function (val) {
var unique;
if (this.select) {
this.select.val(val);
} else {
unique = [];
// filter out duplicates
$(val).each(function () {
if (indexOf(this, unique) < 0) unique.push(this);
});
this.opts.element.val(unique.length === 0 ? "" : unique.join(this.opts.separator));
}
},
// multi
buildChangeDetails: function (old, current) {
var current = current.slice(0),
old = old.slice(0);
// remove intersection from each array
for (var i = 0; i < current.length; i++) {
for (var j = 0; j < old.length; j++) {
if (equal(this.opts.id(current[i]), this.opts.id(old[j]))) {
current.splice(i, 1);
if(i>0){
i--;
}
old.splice(j, 1);
j--;
}
}
}
return {added: current, removed: old};
},
// multi
val: function (val, triggerChange) {
var oldData, self=this;
if (arguments.length === 0) {
return this.getVal();
}
oldData=this.data();
if (!oldData.length) oldData=[];
// val is an id. !val is true for [undefined,null,'',0] - 0 is legal
if (!val && val !== 0) {
this.opts.element.val("");
this.updateSelection([]);
this.clearSearch();
if (triggerChange) {
this.triggerChange({added: this.data(), removed: oldData});
}
return;
}
// val is a list of ids
this.setVal(val);
if (this.select) {
this.opts.initSelection(this.select, this.bind(this.updateSelection));
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(oldData, this.data()));
}
} else {
if (this.opts.initSelection === undefined) {
throw new Error("val() cannot be called if initSelection() is not defined");
}
this.opts.initSelection(this.opts.element, function(data){
var ids=$.map(data, self.id);
self.setVal(ids);
self.updateSelection(data);
self.clearSearch();
if (triggerChange) {
self.triggerChange(self.buildChangeDetails(oldData, self.data()));
}
});
}
this.clearSearch();
},
// multi
onSortStart: function() {
if (this.select) {
throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");
}
// collapse search field into 0 width so its container can be collapsed as well
this.search.width(0);
// hide the container
this.searchContainer.hide();
},
// multi
onSortEnd:function() {
var val=[], self=this;
// show search and move it to the end of the list
this.searchContainer.show();
// make sure the search container is the last item in the list
this.searchContainer.appendTo(this.searchContainer.parent());
// since we collapsed the width in dragStarted, we resize it here
this.resizeSearch();
// update selection
this.selection.find(".select2-search-choice").each(function() {
val.push(self.opts.id($(this).data("select2-data")));
});
this.setVal(val);
this.triggerChange();
},
// multi
data: function(values, triggerChange) {
var self=this, ids, old;
if (arguments.length === 0) {
return this.selection
.find(".select2-search-choice")
.map(function() { return $(this).data("select2-data"); })
.get();
} else {
old = this.data();
if (!values) { values = []; }
ids = $.map(values, function(e) { return self.opts.id(e); });
this.setVal(ids);
this.updateSelection(values);
this.clearSearch();
if (triggerChange) {
this.triggerChange(this.buildChangeDetails(old, this.data()));
}
}
}
});
$.fn.select2 = function () {
var args = Array.prototype.slice.call(arguments, 0),
opts,
select2,
method, value, multiple,
allowedMethods = ["val", "destroy", "opened", "open", "close", "focus", "isFocused", "container", "dropdown", "onSortStart", "onSortEnd", "enable", "disable", "readonly", "positionDropdown", "data", "search"],
valueMethods = ["opened", "isFocused", "container", "dropdown"],
propertyMethods = ["val", "data"],
methodsMap = { search: "externalSearch" };
this.each(function () {
if (args.length === 0 || typeof(args[0]) === "object") {
opts = args.length === 0 ? {} : $.extend({}, args[0]);
opts.element = $(this);
if (opts.element.get(0).tagName.toLowerCase() === "select") {
multiple = opts.element.prop("multiple");
} else {
multiple = opts.multiple || false;
if ("tags" in opts) {opts.multiple = multiple = true;}
}
select2 = multiple ? new MultiSelect2() : new SingleSelect2();
select2.init(opts);
} else if (typeof(args[0]) === "string") {
if (indexOf(args[0], allowedMethods) < 0) {
throw "Unknown method: " + args[0];
}
value = undefined;
select2 = $(this).data("select2");
if (select2 === undefined) return;
method=args[0];
if (method === "container") {
value = select2.container;
} else if (method === "dropdown") {
value = select2.dropdown;
} else {
if (methodsMap[method]) method = methodsMap[method];
value = select2[method].apply(select2, args.slice(1));
}
if (indexOf(args[0], valueMethods) >= 0
|| (indexOf(args[0], propertyMethods) && args.length == 1)) {
return false; // abort the iteration, ready to return first matched value
}
} else {
throw "Invalid arguments to select2 plugin: " + args;
}
});
return (value === undefined) ? this : value;
};
// plugin defaults, accessible to users
$.fn.select2.defaults = {
width: "copy",
loadMorePadding: 0,
closeOnSelect: true,
openOnEnter: true,
containerCss: {},
dropdownCss: {},
containerCssClass: "",
dropdownCssClass: "",
formatResult: function(result, container, query, escapeMarkup) {
var markup=[];
markMatch(result.text, query.term, markup, escapeMarkup);
return markup.join("");
},
formatSelection: function (data, container, escapeMarkup) {
return data ? escapeMarkup(data.text) : undefined;
},
sortResults: function (results, container, query) {
return results;
},
formatResultCssClass: function(data) {return undefined;},
formatSelectionCssClass: function(data, container) {return undefined;},
formatNoMatches: function () { return "No matches found"; },
formatInputTooShort: function (input, min) { var n = min - input.length; return "Please enter " + n + " more character" + (n == 1? "" : "s"); },
formatInputTooLong: function (input, max) { var n = input.length - max; return "Please delete " + n + " character" + (n == 1? "" : "s"); },
formatSelectionTooBig: function (limit) { return "You can only select " + limit + " item" + (limit == 1 ? "" : "s"); },
formatLoadMore: function (pageNumber) { return "Loading more results..."; },
formatSearching: function () { return "Searching..."; },
minimumResultsForSearch: 0,
minimumInputLength: 0,
maximumInputLength: null,
maximumSelectionSize: 0,
id: function (e) { return e.id; },
matcher: function(term, text) {
return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
},
separator: ",",
tokenSeparators: [],
tokenizer: defaultTokenizer,
escapeMarkup: defaultEscapeMarkup,
blurOnChange: false,
selectOnBlur: false,
adaptContainerCssClass: function(c) { return c; },
adaptDropdownCssClass: function(c) { return null; },
nextSearchTerm: function(selectedObject, currentSearchTerm) { return undefined; }
};
$.fn.select2.ajaxDefaults = {
transport: $.ajax,
params: {
type: "GET",
cache: false,
dataType: "json"
}
};
// exports
window.Select2 = {
query: {
ajax: ajax,
local: local,
tags: tags
}, util: {
debounce: debounce,
markMatch: markMatch,
escapeMarkup: defaultEscapeMarkup,
stripDiacritics: stripDiacritics
}, "class": {
"abstract": AbstractSelect2,
"single": SingleSelect2,
"multi": MultiSelect2
}
};
}(jQuery));
return module.exports;
}).call(this);
// src/js/aui/select2.js
(typeof window === 'undefined' ? global : window).__dfd5f5c723e08e5f95e38718fe4f73eb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__b2190710f2822b5d7286528d3eaff37f;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Wraps a vanilla Select2 with ADG _style_, as an auiSelect2 method on jQuery objects.
*
* @since 5.2
*/
/**
* We make a copy of the original select2 so that later we might re-specify $.fn.auiSelect2 as $.fn.select2. That
* way, calling code will be able to call $thing.select2() as if they were calling the original library,
* and ADG styling will just magically happen.
*/
var originalSelect2 = _jquery2.default.fn.select2;
// AUI-specific classes
var auiContainer = 'aui-select2-container';
var auiDropdown = 'aui-select2-drop aui-dropdown2 aui-style-default';
var auiHasAvatar = 'aui-has-avatar';
_jquery2.default.fn.auiSelect2 = function (first) {
var updatedArgs;
if (_jquery2.default.isPlainObject(first)) {
var auiOpts = _jquery2.default.extend({}, first);
var auiAvatarClass = auiOpts.hasAvatar ? ' ' + auiHasAvatar : '';
//add our classes in addition to those the caller specified
auiOpts.containerCssClass = auiContainer + auiAvatarClass + (auiOpts.containerCssClass ? ' ' + auiOpts.containerCssClass : '');
auiOpts.dropdownCssClass = auiDropdown + auiAvatarClass + (auiOpts.dropdownCssClass ? ' ' + auiOpts.dropdownCssClass : '');
updatedArgs = Array.prototype.slice.call(arguments, 1);
updatedArgs.unshift(auiOpts);
} else if (!arguments.length) {
updatedArgs = [{
containerCssClass: auiContainer,
dropdownCssClass: auiDropdown
}];
} else {
updatedArgs = arguments;
}
return originalSelect2.apply(this, updatedArgs);
};
return module.exports;
}).call(this);
// src/js-vendor/raf/raf.js
(typeof window === 'undefined' ? global : window).__c814de1f9f57536916ee97e53618b317 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/*
* raf.js
* https://github.com/ngryman/raf.js
*
* original requestAnimationFrame polyfill by Erik Möller
* inspired from paul_irish gist and post
*
* Copyright (c) 2013 ngryman
* Licensed under the MIT license.
*/
(function(window) {
var lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
i = vendors.length;
// try to un-prefix existing raf
while (--i >= 0 && !requestAnimationFrame) {
requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'];
}
// polyfill with setTimeout fallback
// heavily inspired from @darius gist mod: https://gist.github.com/paulirish/1579671#comment-837945
if (!requestAnimationFrame || !cancelAnimationFrame) {
requestAnimationFrame = function(callback) {
var now = Date.now(), nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() {
callback(lastTime = nextTime);
}, nextTime - now);
};
cancelAnimationFrame = clearTimeout;
}
// export to window
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
}(window));
return module.exports;
}).call(this);
// src/js/aui/internal/has-touch.js
(typeof window === 'undefined' ? global : window).__2bddeae7bba6bcfe91954e333e4fbeb4 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var DocumentTouch = window.DocumentTouch;
var hasTouch = 'ontouchstart' in window || DocumentTouch && document instanceof DocumentTouch;
exports.default = hasTouch;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/is-input.js
(typeof window === 'undefined' ? global : window).__5440f08d566da1cac4a925f4a02d99bd = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (el) {
return 'value' in el || el.isContentEditable;
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/internal/mediaQuery.js
(typeof window === 'undefined' ? global : window).__2f005a42739e074aa33083fd59d18ccb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**
* Inspired by matchMedia() polyfill
* https://github.com/paulirish/matchMedia.js/blob/953faa1489284655ed9d6e03bf48d39df70612c4/matchMedia.js
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mediaQuery;
function mediaQuery(mq) {
if (window.matchMedia) {
return window.matchMedia(mq).matches;
}
// fallback support for <=IE9 (remove this code if we don't want to support IE9 anymore)
var style = document.createElement('style');
style.type = 'text/css';
style.id = 'testMedia';
style.innerText = '@media ' + mq + ' { #testMedia { width: 1px; } }';
document.head.appendChild(style);
var info = window.getComputedStyle(style, null);
var testMediaQuery = info.width === '1px';
style.parentNode.removeChild(style);
return testMediaQuery;
};
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/sidebar.js
(typeof window === 'undefined' ? global : window).__810b6deefd6627f937e4a4d2fae0520a = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__dbb945ae8033589d400f8c63e7d01524;
__c814de1f9f57536916ee97e53618b317;
__be3e01199078cdf5ded88dda6a8fbec9;
var _clone = __dcc3fd3e77e47fb48e5c0c44ee208201;
var _clone2 = _interopRequireDefault(_clone);
var _deprecation = __4ddcc788b1704f76a51559fc0e0d2968;
var deprecate = _interopRequireWildcard(_deprecation);
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _hasTouch = __2bddeae7bba6bcfe91954e333e4fbeb4;
var _hasTouch2 = _interopRequireDefault(_hasTouch);
var _isInput = __5440f08d566da1cac4a925f4a02d99bd;
var _isInput2 = _interopRequireDefault(_isInput);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _mediaQuery = __2f005a42739e074aa33083fd59d18ccb;
var _mediaQuery2 = _interopRequireDefault(_mediaQuery);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _uniqueId = __6a8d9be203374eb86b4b050d0244b6f1;
var _uniqueId2 = _interopRequireDefault(_uniqueId);
var _widget = __2d1b5481970dd1547e294d829464e03f;
var _widget2 = _interopRequireDefault(_widget);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SUPPORTS_TRANSITIONS = typeof document.documentElement.style.transition !== 'undefined' || typeof document.documentElement.style.webkitTransition !== 'undefined';
function sidebarOffset(sidebar) {
return sidebar.offset().top;
}
function Sidebar(selector) {
this.$el = (0, _jquery2.default)(selector);
if (!this.$el.length) {
return;
}
this.$body = (0, _jquery2.default)('body');
this.$wrapper = this.$el.children('.aui-sidebar-wrapper');
// Sidebar users should add class="aui-page-sidebar" to the
// <body> in the rendered markup (to prevent any potential flicker),
// so we add it just in case they forgot.
this.$body.addClass('aui-page-sidebar');
this._previousScrollTop = null;
this._previousViewportHeight = null;
this._previousViewportWidth = null;
this._previousOffsetTop = null;
this.submenus = new SubmenuManager();
initializeHandlers(this);
constructAllSubmenus(this);
}
var FORCE_COLLAPSE_WIDTH = 1240;
var EVENT_PREFIX = '_aui-internal-sidebar-';
function namespaceEvents(events) {
return _jquery2.default.map(events.split(' '), function (event) {
return EVENT_PREFIX + event;
}).join(' ');
}
Sidebar.prototype.on = function () {
var events = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var namespacedEvents = namespaceEvents(events);
this.$el.on.apply(this.$el, [namespacedEvents].concat(args));
return this;
};
Sidebar.prototype.off = function () {
var events = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
var namespacedEvents = namespaceEvents(events);
this.$el.off.apply(this.$el, [namespacedEvents].concat(args));
return this;
};
Sidebar.prototype.setHeight = function (scrollTop, viewportHeight, headerHeight) {
var visibleHeaderHeight = Math.max(0, headerHeight - scrollTop);
this.$wrapper.height(viewportHeight - visibleHeaderHeight);
return this;
};
Sidebar.prototype.setPosition = function (scrollTop) {
scrollTop = scrollTop || window.pageYOffset;
this.$wrapper.toggleClass('aui-is-docked', scrollTop > sidebarOffset(this.$el));
return this;
};
Sidebar.prototype.setCollapsedState = function (viewportWidth) {
// Reflow behaviour is implemented as a state machine (hence all
// state transitions are enumerated). The rest of the state machine,
// e.g., entering the expanded narrow (fly-out) state, is implemented
// by the toggle() method.
var transition = { collapsed: {}, expanded: {} };
transition.collapsed.narrow = {
narrow: _jquery2.default.noop,
wide: function wide(s) {
s._expand(viewportWidth, true);
}
};
transition.collapsed.wide = {
narrow: _jquery2.default.noop, // Becomes collapsed narrow (no visual change).
wide: _jquery2.default.noop
};
transition.expanded.narrow = {
narrow: _jquery2.default.noop,
wide: function wide(s) {
s.$body.removeClass('aui-sidebar-collapsed');
s.$el.removeClass('aui-sidebar-fly-out');
}
};
transition.expanded.wide = {
narrow: function narrow(s) {
s._collapse(true);
},
wide: _jquery2.default.noop
};
var collapseState = this.isCollapsed() ? 'collapsed' : 'expanded';
var oldSize = this.isViewportNarrow(this._previousViewportWidth) ? 'narrow' : 'wide';
var newSize = this.isViewportNarrow(viewportWidth) ? 'narrow' : 'wide';
transition[collapseState][oldSize][newSize](this);
return this;
};
Sidebar.prototype._collapse = function (isResponsive) {
if (this.isCollapsed()) {
return this;
}
var startEvent = _jquery2.default.Event(EVENT_PREFIX + 'collapse-start', { isResponsive: isResponsive });
this.$el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return this;
}
this.$body.addClass('aui-sidebar-collapsed');
this.$el.attr('aria-expanded', 'false');
this.$el.removeClass('aui-sidebar-fly-out');
this.$el.find(this.submenuTriggersSelector).attr('tabindex', 0);
(0, _jquery2.default)(this.inlineDialogSelector).attr('responds-to', 'hover');
if (!this.isAnimated()) {
this.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + 'collapse-end', { isResponsive: isResponsive }));
}
return this;
};
Sidebar.prototype.collapse = function () {
return this._collapse(false);
};
Sidebar.prototype._expand = function (viewportWidth, isResponsive) {
var startEvent = _jquery2.default.Event(EVENT_PREFIX + 'expand-start', { isResponsive: isResponsive });
this.$el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return this;
}
var isViewportNarrow = this.isViewportNarrow(viewportWidth);
this.$el.attr('aria-expanded', 'true');
this.$body.toggleClass('aui-sidebar-collapsed', isViewportNarrow);
this.$el.toggleClass('aui-sidebar-fly-out', isViewportNarrow);
this.$el.find(this.submenuTriggersSelector).removeAttr('tabindex');
(0, _jquery2.default)(this.inlineDialogSelector).removeAttr('responds-to');
if (!this.isAnimated()) {
this.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + 'expand-end', { isResponsive: isResponsive }));
}
return this;
};
Sidebar.prototype.expand = function () {
if (this.isCollapsed()) {
this._expand(this._previousViewportWidth, false);
}
return this;
};
Sidebar.prototype.isAnimated = function () {
return SUPPORTS_TRANSITIONS && this.$el.hasClass('aui-is-animated');
};
Sidebar.prototype.isCollapsed = function () {
return this.$el.attr('aria-expanded') === 'false';
};
Sidebar.prototype.isViewportNarrow = function (viewportWidth) {
viewportWidth = viewportWidth === undefined ? this._previousViewportWidth : viewportWidth;
return viewportWidth < FORCE_COLLAPSE_WIDTH;
};
Sidebar.prototype._removeAllTooltips = function () {
// tooltips are orphaned when sidebar is expanded, so if there are any visible on the page we remove them all.
// Can't scope it to the Sidebar (this) because the tooltip div is a direct child of <body>
(0, _jquery2.default)(this.tooltipSelector).remove();
};
Sidebar.prototype.responsiveReflow = function responsiveReflow(isInitialPageLoad, viewportWidth) {
if (isInitialPageLoad) {
if (!this.isCollapsed() && this.isViewportNarrow(viewportWidth)) {
var isAnimated = this.isAnimated();
if (isAnimated) {
this.$el.removeClass('aui-is-animated');
}
// This will trigger the "collapse" event before non-sidebar
// JS code has a chance to bind listeners; they'll need to
// check isCollapsed() if they care about the value at that
// time.
this.collapse();
if (isAnimated) {
// We must trigger a CSS reflow (by accessing
// offsetHeight) otherwise the transition still runs.
// eslint-disable-next-line
this.$el[0].offsetHeight;
this.$el.addClass('aui-is-animated');
}
}
} else if (viewportWidth !== this._previousViewportWidth) {
this.setCollapsedState(viewportWidth);
}
};
Sidebar.prototype.reflow = function reflow(scrollTop, viewportHeight, viewportWidth, scrollHeight) {
scrollTop = scrollTop === undefined ? window.pageYOffset : scrollTop;
viewportHeight = viewportHeight === undefined ? document.documentElement.clientHeight : viewportHeight;
scrollHeight = scrollHeight === undefined ? document.documentElement.scrollHeight : scrollHeight;
viewportWidth = viewportWidth === undefined ? window.innerWidth : viewportWidth;
// Header height needs to be checked because in Stash it changes when the CSS "transform: translate3d" is changed.
// If you called reflow() after this change then nothing happened because the scrollTop and viewportHeight hadn't changed.
var offsetTop = sidebarOffset(this.$el);
var isInitialPageLoad = this._previousViewportWidth === null;
if (!(scrollTop === this._previousScrollTop && viewportHeight === this._previousViewportHeight && offsetTop === this._previousOffsetTop)) {
if (this.isCollapsed() && !isInitialPageLoad && scrollTop !== this._previousScrollTop) {
// hide submenu and tooltips on scroll
hideAllSubmenus();
this._removeAllTooltips();
}
var isTouch = this.$body.hasClass('aui-page-sidebar-touch');
var isTrackpadBounce = scrollTop !== this._previousScrollTop && (scrollTop < 0 || scrollTop + viewportHeight > scrollHeight);
if (!isTouch && (isInitialPageLoad || !isTrackpadBounce)) {
this.setHeight(scrollTop, viewportHeight, offsetTop);
this.setPosition(scrollTop);
}
}
var isResponsive = this.$el.attr('data-aui-responsive') !== 'false';
if (isResponsive) {
this.responsiveReflow(isInitialPageLoad, viewportWidth);
} else {
var isFlyOut = !this.isCollapsed() && this.isViewportNarrow(viewportWidth);
this.$el.toggleClass('aui-sidebar-fly-out', isFlyOut);
}
this._previousScrollTop = scrollTop;
this._previousViewportHeight = viewportHeight;
this._previousViewportWidth = viewportWidth;
this._previousOffsetTop = offsetTop;
return this;
};
Sidebar.prototype.toggle = function () {
if (this.isCollapsed()) {
this.expand();
this._removeAllTooltips();
} else {
this.collapse();
}
return this;
};
/**
* Returns a jQuery selector string for the trigger elements when the
* sidebar is in a collapsed state, useful for delegated event binding.
*
* When using this selector in event handlers, the element ("this") will
* either be an <a> (when the trigger was a tier-one menu item) or an
* element with class "aui-sidebar-group" (for non-tier-one items).
*
* For delegated event binding you should bind to $el and check the value
* of isCollapsed(), e.g.,
*
* sidebar.$el.on('click', sidebar.collapsedTriggersSelector, function (e) {
* if (!sidebar.isCollapsed()) {
* return;
* }
* });
*
* @returns string
*/
Sidebar.prototype.submenuTriggersSelector = '.aui-sidebar-group:not(.aui-sidebar-group-tier-one)';
Sidebar.prototype.collapsedTriggersSelector = [Sidebar.prototype.submenuTriggersSelector, '.aui-sidebar-group.aui-sidebar-group-tier-one > .aui-nav > li > a', '.aui-sidebar-footer > .aui-sidebar-settings-button'].join(', ');
Sidebar.prototype.toggleSelector = '.aui-sidebar-footer > .aui-sidebar-toggle';
Sidebar.prototype.tooltipSelector = '.aui-sidebar-section-tooltip';
Sidebar.prototype.inlineDialogClass = 'aui-sidebar-submenu-dialog';
Sidebar.prototype.inlineDialogSelector = '.' + Sidebar.prototype.inlineDialogClass;
function getAllSubmenuDialogs() {
return document.querySelectorAll(Sidebar.prototype.inlineDialogSelector);
}
function SubmenuManager() {
this.inlineDialog = null;
}
SubmenuManager.prototype.submenu = function ($trigger) {
sidebarSubmenuDeprecationLogger();
return getSubmenu($trigger);
};
SubmenuManager.prototype.hasSubmenu = function ($trigger) {
sidebarSubmenuDeprecationLogger();
return hasSubmenu($trigger);
};
SubmenuManager.prototype.submenuHeadingHeight = function () {
sidebarSubmenuDeprecationLogger();
return 34;
};
SubmenuManager.prototype.isShowing = function () {
sidebarSubmenuDeprecationLogger();
return Sidebar.prototype.isSubmenuVisible();
};
SubmenuManager.prototype.show = function (e, trigger) {
sidebarSubmenuDeprecationLogger();
showSubmenu(trigger);
};
SubmenuManager.prototype.hide = function () {
sidebarSubmenuDeprecationLogger();
hideAllSubmenus();
};
SubmenuManager.prototype.inlineDialogShowHandler = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.inlineDialogHideHandler = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.moveSubmenuToInlineDialog = function () {
sidebarSubmenuDeprecationLogger();
};
SubmenuManager.prototype.restoreSubmenu = function () {
sidebarSubmenuDeprecationLogger();
};
Sidebar.prototype.getVisibleSubmenus = function () {
return Array.prototype.filter.call(getAllSubmenuDialogs(), function (inlineDialog2) {
return inlineDialog2.open;
});
};
Sidebar.prototype.isSubmenuVisible = function () {
return this.getVisibleSubmenus().length > 0;
};
function getSubmenu($trigger) {
return $trigger.is('a') ? $trigger.next('.aui-nav') : $trigger.children('.aui-nav, hr');
}
function getSubmenuInlineDialog(trigger) {
var inlineDialogId = trigger.getAttribute('aria-controls');
return document.getElementById(inlineDialogId);
}
function hasSubmenu($trigger) {
return getSubmenu($trigger).length !== 0;
}
function hideAllSubmenus() {
var allSubmenuDialogs = getAllSubmenuDialogs();
Array.prototype.forEach.call(allSubmenuDialogs, function (inlineDialog2) {
inlineDialog2.open = false;
});
}
function showSubmenu(trigger) {
getSubmenuInlineDialog(trigger).open = true;
}
function constructSubmenu(sidebar, $trigger) {
if ($trigger.data('_aui-sidebar-submenu-constructed')) {
return;
} else {
$trigger.data('_aui-sidebar-submenu-constructed', true);
}
if (!hasSubmenu($trigger)) {
return;
}
var submenuInlineDialog = document.createElement('aui-inline-dialog');
var uniqueId = (0, _uniqueId2.default)('sidebar-submenu');
$trigger.attr('aria-controls', uniqueId);
$trigger.attr('data-aui-trigger', '');
_skate2.default.init($trigger); //Trigger doesn't listen to attribute modification
submenuInlineDialog.setAttribute('id', uniqueId);
submenuInlineDialog.setAttribute('alignment', 'right top');
submenuInlineDialog.setAttribute('aria-hidden', 'true');
if (sidebar.isCollapsed()) {
submenuInlineDialog.setAttribute('responds-to', 'hover');
}
(0, _jquery2.default)(submenuInlineDialog).addClass(Sidebar.prototype.inlineDialogClass);
document.body.appendChild(submenuInlineDialog);
_skate2.default.init(submenuInlineDialog); //Needed so that sidebar.submenus.isShowing() will work on page load
addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog);
return submenuInlineDialog;
}
function addHandlersToSubmenuInlineDialog(sidebar, $trigger, submenuInlineDialog) {
submenuInlineDialog.addEventListener('aui-layer-show', function (e) {
if (!sidebar.isCollapsed()) {
e.preventDefault();
return;
}
inlineDialogShowHandler($trigger, submenuInlineDialog);
});
submenuInlineDialog.addEventListener('aui-layer-hide', function () {
inlineDialogHideHandler($trigger);
});
}
function inlineDialogShowHandler($trigger, submenuInlineDialog) {
$trigger.addClass('active');
submenuInlineDialog.innerHTML = SUBMENU_INLINE_DIALOG_CONTENTS_HTML;
var title = $trigger.is('a') ? $trigger.text() : $trigger.children('.aui-nav-heading').text();
var $container = (0, _jquery2.default)(submenuInlineDialog).find('.aui-navgroup-inner');
$container.children('.aui-nav-heading').attr('title', title).children('strong').text(title);
var $submenu = getSubmenu($trigger);
cloneExpander($submenu).appendTo($container);
/**
* Workaround to show all contents in the expander.
* This function should come from the expander component.
*/
function cloneExpander(element) {
var $clone = (0, _clone2.default)(element);
if ($clone.hasClass('aui-expander-content')) {
$clone.find('.aui-expander-cutoff').remove();
$clone.removeClass('aui-expander-content');
}
return $clone;
}
}
var SUBMENU_INLINE_DIALOG_CONTENTS_HTML = '<div class="aui-inline-dialog-contents">' + '<div class="aui-sidebar-submenu" >' + '<div class="aui-navgroup aui-navgroup-vertical">' + '<div class="aui-navgroup-inner">' + '<div class="aui-nav-heading"><strong></strong></div>' + '</div>' + '</div>' + '</div>' + '</div>';
function inlineDialogHideHandler($trigger) {
$trigger.removeClass('active');
}
function constructAllSubmenus(sidebar) {
(0, _jquery2.default)(sidebar.collapsedTriggersSelector).each(function () {
var $trigger = (0, _jquery2.default)(this);
constructSubmenu(sidebar, $trigger);
});
}
var tipsyOpts = {
trigger: 'manual',
gravity: 'w',
className: 'aui-sidebar-section-tooltip',
title: function title() {
var $item = (0, _jquery2.default)(this);
if ($item.is('a')) {
return $item.attr('title') || $item.find('.aui-nav-item-label').text() || $item.data('tooltip');
} else {
return $item.children('.aui-nav').attr('title') || $item.children('.aui-nav-heading').text();
}
}
};
function showTipsy($trigger) {
$trigger.tipsy(tipsyOpts).tipsy('show');
var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip;
if ($tip) {
// if .aui-sidebar-group does not have a title to display
// Remove "opacity" inline style from Tipsy to allow the our own styles and transitions to be applied
$tip.css({ opacity: '' }).addClass('tooltip-shown');
}
}
function hideTipsy($trigger) {
var $tip = $trigger.data('tipsy') && $trigger.data('tipsy').$tip;
if ($tip) {
var durationStr = $tip.css('transition-duration');
if (durationStr) {
// can be denominated in either s or ms
var timeoutMs = durationStr.indexOf('ms') >= 0 ? parseInt(durationStr.substring(0, durationStr.length - 2), 10) : 1000 * parseInt(durationStr.substring(0, durationStr.length - 1), 10);
// use a timeout because the transitionend event is not reliable (yet),
// more details here: https://bitbucket.atlassian.net/browse/BB-11599
// an example of this at http://labs.silverorange.com/files/webkit-bug/
// further caveats here: https://developer.mozilla.org/en-US/docs/Web/Events/transitionend
// "In the case where a transition is removed before completion,
// such as if the transition-property is removed, then the event will not fire."
setTimeout(function () {
$trigger.tipsy('hide');
}, timeoutMs);
}
$tip.removeClass('tooltip-shown');
}
}
function lazilyInitializeSubmenus(sidebar) {
sidebar.$el.on('mouseenter mouseleave click focus', sidebar.collapsedTriggersSelector, function (e) {
var $trigger = (0, _jquery2.default)(e.target);
constructSubmenu(sidebar, $trigger);
});
}
function initializeHandlers(sidebar) {
var $sidebar = (0, _jquery2.default)('.aui-sidebar');
if (!$sidebar.length) {
return;
}
lazilyInitializeSubmenus(sidebar);
// AUI-2542: only enter touch mode on small screen touchable devices
if (_hasTouch2.default && (0, _mediaQuery2.default)('only screen and (max-device-width:1024px)')) {
(0, _jquery2.default)('body').addClass('aui-page-sidebar-touch');
}
var pendingReflow = null;
var onScrollResizeReflow = function onScrollResizeReflow() {
if (pendingReflow === null) {
pendingReflow = requestAnimationFrame(function () {
sidebar.reflow();
pendingReflow = null;
});
}
};
(0, _jquery2.default)(window).on('scroll resize', onScrollResizeReflow);
sidebar.reflow();
if (sidebar.isAnimated()) {
sidebar.$el.on('transitionend webkitTransitionEnd', function () {
sidebar.$el.trigger(_jquery2.default.Event(EVENT_PREFIX + (sidebar.isCollapsed() ? 'collapse-end' : 'expand-end')));
});
}
sidebar.$el.on('click', '.aui-sidebar-toggle', function (e) {
e.preventDefault();
sidebar.toggle();
});
(0, _jquery2.default)('.aui-page-panel').click(function () {
if (!sidebar.isCollapsed() && sidebar.isViewportNarrow()) {
sidebar.collapse();
}
});
var toggleShortcutHandler = function toggleShortcutHandler(e) {
if (isNormalSquareBracket(e)) {
sidebar.toggle();
}
};
//We use keypress because it captures the actual character that was typed and not the physical key that was pressed.
//This accounts for other keyboard layouts
(0, _jquery2.default)(document).on('keypress', toggleShortcutHandler);
sidebar._remove = function () {
this._removeAllTooltips();
(0, _jquery2.default)(this.inlineDialogSelector).remove();
this.$el.off();
this.$el.remove();
(0, _jquery2.default)(document).off('keypress', toggleShortcutHandler);
(0, _jquery2.default)(window).off('scroll resize', onScrollResizeReflow);
};
sidebar.$el.on('touchend', function (e) {
if (sidebar.isCollapsed()) {
sidebar.expand();
e.preventDefault();
}
});
sidebar.$el.on('mouseenter focus', sidebar.collapsedTriggersSelector, function () {
if (!sidebar.isCollapsed()) {
return;
}
var $trigger = (0, _jquery2.default)(this);
if (!hasSubmenu($trigger)) {
showTipsy($trigger);
}
});
sidebar.$el.on('click blur mouseleave', sidebar.collapsedTriggersSelector, function () {
if (!sidebar.isCollapsed()) {
return;
}
hideTipsy((0, _jquery2.default)(this));
});
sidebar.$el.on('mouseenter focus', sidebar.toggleSelector, function () {
var $trigger = (0, _jquery2.default)(this);
if (sidebar.isCollapsed()) {
$trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.expand.tooltip'));
} else {
$trigger.data('tooltip', AJS.I18n.getText('aui.sidebar.collapse.tooltip'));
}
showTipsy($trigger);
});
sidebar.$el.on('click blur mouseleave', sidebar.toggleSelector, function () {
hideTipsy((0, _jquery2.default)(this));
});
function isNormalTab(e) {
return e.keyCode === _keyCode2.default.TAB && !e.shiftKey && !e.altKey;
}
function isNormalSquareBracket(e) {
return e.which === _keyCode2.default.LEFT_SQUARE_BRACKET && !e.shiftKey && !e.ctrlKey && !e.metaKey && !(0, _isInput2.default)(e.target);
}
function isShiftTab(e) {
return e.keyCode === _keyCode2.default.TAB && e.shiftKey;
}
function isFirstSubmenuItem(item, $submenuDialog) {
return item === $submenuDialog.find(':aui-tabbable')[0];
}
function isLastSubmenuItem(item, $submenuDialog) {
return item === $submenuDialog.find(':aui-tabbable').last()[0];
}
/**
* Force to focus on the first tabbable item in inline dialog.
* Reason: inline dialog will be hidden as soon as the trigger is out of focus (onBlur event)
* This function should come directly from inline dialog component.
*/
function focusFirstItemOfInlineDialog($inlineDialog) {
$inlineDialog.attr('persistent', '');
// don't use :aui-tabbable:first as it will select the first tabbable item in EACH nav group
$inlineDialog.find(':aui-tabbable').first().focus();
// workaround on IE:
// delay the persistence of inline dialog to make sure onBlur event was triggered first
setTimeout(function () {
$inlineDialog.removeAttr('persistent');
}, 100);
}
sidebar.$el.on('keydown', sidebar.collapsedTriggersSelector, function (e) {
if (sidebar.isCollapsed()) {
var triggerEl = e.target;
var submenuInlineDialog = getSubmenuInlineDialog(triggerEl);
if (!submenuInlineDialog) {
return;
}
var $submenuInlineDialog = (0, _jquery2.default)(submenuInlineDialog);
if (isNormalTab(e) && submenuInlineDialog.open) {
e.preventDefault();
focusFirstItemOfInlineDialog($submenuInlineDialog);
$submenuInlineDialog.on('keydown', function (e) {
if (isShiftTab(e) && isFirstSubmenuItem(e.target, $submenuInlineDialog) || isNormalTab(e) && isLastSubmenuItem(e.target, $submenuInlineDialog)) {
triggerEl.focus();
// unbind event and close submenu as the focus is out of the submenu
(0, _jquery2.default)(this).off('keydown');
hideAllSubmenus();
}
});
}
}
});
}
var sidebar = (0, _widget2.default)('sidebar', Sidebar);
(0, _jquery2.default)(function () {
sidebar('.aui-sidebar');
});
var sidebarSubmenuDeprecationLogger = deprecate.getMessageLogger('Sidebar.submenus', {
removeInVersion: '8.0',
sinceVersion: '5.8'
});
(0, _globalize2.default)('sidebar', sidebar);
exports.default = sidebar;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js-vendor/jquery/jquery.tablesorter.js
(typeof window === 'undefined' ? global : window).__f1a3fa76609e6d40a55157a38f5d9723 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
/**!
* TableSorter 2.17.7 - Client-side table sorting with ease!
* @requires jQuery v1.2.6+
*
* Copyright (c) 2007 Christian Bach
* Examples and docs at: http://tablesorter.com
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* @type jQuery
* @name tablesorter
* @cat Plugins/Tablesorter
* @author Christian Bach/[email protected]
* @contributor Rob Garrison/https://github.com/Mottie/tablesorter
*/
/*jshint browser:true, jquery:true, unused:false, expr: true */
/*global console:false, alert:false */
!(function($) {
$.extend({
/*jshint supernew:true */
tablesorter: new function() {
var ts = this;
ts.version = "2.17.7";
ts.parsers = [];
ts.widgets = [];
ts.defaults = {
// *** appearance
theme : 'default', // adds tablesorter-{theme} to the table for styling
widthFixed : false, // adds colgroup to fix widths of columns
showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered.
headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> (class from cssIcon)
onRenderTemplate : null, // function(index, template){ return template; }, (template is a string)
onRenderHeader : null, // function(index){}, (nothing to return)
// *** functionality
cancelSelection : true, // prevent text selection in the header
tabIndex : true, // add tabindex to header for keyboard accessibility
dateFormat : 'mmddyyyy', // other options: "ddmmyyy" or "yyyymmdd"
sortMultiSortKey : 'shiftKey', // key used to select additional columns
sortResetKey : 'ctrlKey', // key used to remove sorting on a column
usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89"
delayInit : false, // if false, the parsed table contents will not update until the first sort
serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used.
// *** sort options
headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc.
ignoreCase : true, // ignore case while sorting
sortForce : null, // column(s) first sorted; always applied
sortList : [], // Initial sort order; applied initially; updated when manually sorted
sortAppend : null, // column(s) sorted last; always applied
sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained
sortInitialOrder : 'asc', // sort direction on first click
sortLocaleCompare: false, // replace equivalent character (accented characters)
sortReset : false, // third click on the header will reset column to default - unsorted
sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns
emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero
stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero
textExtraction : 'basic', // text extraction method/function - function(node, table, cellIndex){}
textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in textExtraction function)
textSorter : null, // choose overall or specific column sorter function(a, b, direction, table, columnIndex) [alt: ts.sortText]
numberSorter : null, // choose overall numeric sorter function(a, b, direction, maxColumnValue)
// *** widget options
widgets: [], // method to add widgets, e.g. widgets: ['zebra']
widgetOptions : {
zebra : [ 'even', 'odd' ] // zebra widget alternating row class names
},
initWidgets : true, // apply widgets on tablesorter initialization
// *** callbacks
initialized : null, // function(table){},
// *** extra css class names
tableClass : '',
cssAsc : '',
cssDesc : '',
cssNone : '',
cssHeader : '',
cssHeaderRow : '',
cssProcessing : '', // processing icon applied to header during sort/filter
cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent
cssIcon : 'tablesorter-icon', // if this class exists, a <i> will be added to the header automatically
cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!)
// *** selectors
selectorHeaders : '> thead th, > thead td',
selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort
selectorRemove : '.remove-me',
// *** advanced
debug : false,
// *** Internal variables
headerList: [],
empties: {},
strings: {},
parsers: []
// deprecated; but retained for backwards compatibility
// widgetZebra: { css: ["even", "odd"] }
};
// internal css classes - these will ALWAYS be added to
// the table and MUST only contain one class name - fixes #381
ts.css = {
table : 'tablesorter',
cssHasChild: 'tablesorter-hasChildRow',
childRow : 'tablesorter-childRow',
header : 'tablesorter-header',
headerRow : 'tablesorter-headerRow',
headerIn : 'tablesorter-header-inner',
icon : 'tablesorter-icon',
info : 'tablesorter-infoOnly',
processing : 'tablesorter-processing',
sortAsc : 'tablesorter-headerAsc',
sortDesc : 'tablesorter-headerDesc',
sortNone : 'tablesorter-headerUnSorted'
};
// labels applied to sortable headers for accessibility (aria) support
ts.language = {
sortAsc : 'Ascending sort applied, ',
sortDesc : 'Descending sort applied, ',
sortNone : 'No sort applied, ',
nextAsc : 'activate to apply an ascending sort',
nextDesc : 'activate to apply a descending sort',
nextNone : 'activate to remove the sort'
};
/* debuging utils */
function log() {
var a = arguments[0],
s = arguments.length > 1 ? Array.prototype.slice.call(arguments) : a;
if (typeof console !== "undefined" && typeof console.log !== "undefined") {
console[ /error/i.test(a) ? 'error' : /warn/i.test(a) ? 'warn' : 'log' ](s);
} else {
alert(s);
}
}
function benchmark(s, d) {
log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)");
}
ts.log = log;
ts.benchmark = benchmark;
// $.isEmptyObject from jQuery v1.4
function isEmptyObject(obj) {
/*jshint forin: false */
for (var name in obj) {
return false;
}
return true;
}
function getElementText(table, node, cellIndex) {
if (!node) { return ""; }
var te, c = table.config,
t = c.textExtraction || '',
text = "";
if (t === "basic") {
// check data-attribute first
text = $(node).attr(c.textAttribute) || node.textContent || node.innerText || $(node).text() || "";
} else {
if (typeof(t) === "function") {
text = t(node, table, cellIndex);
} else if (typeof (te = ts.getColumnData( table, t, cellIndex )) === 'function') {
text = te(node, table, cellIndex);
} else {
// previous "simple" method
text = node.textContent || node.innerText || $(node).text() || "";
}
}
return $.trim(text);
}
function detectParserForColumn(table, rows, rowIndex, cellIndex) {
var cur,
i = ts.parsers.length,
node = false,
nodeValue = '',
keepLooking = true;
while (nodeValue === '' && keepLooking) {
rowIndex++;
if (rows[rowIndex]) {
node = rows[rowIndex].cells[cellIndex];
nodeValue = getElementText(table, node, cellIndex);
if (table.config.debug) {
log('Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': "' + nodeValue + '"');
}
} else {
keepLooking = false;
}
}
while (--i >= 0) {
cur = ts.parsers[i];
// ignore the default text parser because it will always be true
if (cur && cur.id !== 'text' && cur.is && cur.is(nodeValue, table, node)) {
return cur;
}
}
// nothing found, return the generic parser (text)
return ts.getParserById('text');
}
function buildParserCache(table) {
var c = table.config,
// update table bodies in case we start with an empty table
tb = c.$tbodies = c.$table.children('tbody:not(.' + c.cssInfoBlock + ')'),
rows, list, l, i, h, ch, np, p, e, time,
j = 0,
parsersDebug = "",
len = tb.length;
if ( len === 0) {
return c.debug ? log('Warning: *Empty table!* Not building a parser cache') : '';
} else if (c.debug) {
time = new Date();
log('Detecting parsers for each column');
}
list = {
extractors: [],
parsers: []
};
while (j < len) {
rows = tb[j].rows;
if (rows[j]) {
l = c.columns; // rows[j].cells.length;
for (i = 0; i < l; i++) {
h = c.$headers.filter('[data-column="' + i + '"]:last');
// get column indexed table cell
ch = ts.getColumnData( table, c.headers, i );
// get column parser/extractor
e = ts.getParserById( ts.getData(h, ch, 'extractor') );
p = ts.getParserById( ts.getData(h, ch, 'sorter') );
np = ts.getData(h, ch, 'parser') === 'false';
// empty cells behaviour - keeping emptyToBottom for backwards compatibility
c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' );
// text strings behaviour in numerical sorts
c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max';
if (np) {
p = ts.getParserById('no-parser');
}
if (!e) {
// For now, maybe detect someday
e = false;
}
if (!p) {
p = detectParserForColumn(table, rows, -1, i);
}
if (c.debug) {
parsersDebug += "column:" + i + "; extractor:" + e.id + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n";
}
list.parsers[i] = p;
list.extractors[i] = e;
}
}
j += (list.parsers.length) ? len : 1;
}
if (c.debug) {
log(parsersDebug ? parsersDebug : "No parsers detected");
benchmark("Completed detecting parsers", time);
}
c.parsers = list.parsers;
c.extractors = list.extractors;
}
/* utils */
function buildCache(table) {
var cc, t, tx, v, i, j, k, $row, rows, cols, cacheTime,
totalRows, rowData, colMax,
c = table.config,
$tb = c.$table.children('tbody'),
extractors = c.extractors,
parsers = c.parsers;
c.cache = {};
c.totalRows = 0;
// if no parsers found, return - it's an empty table.
if (!parsers) {
return c.debug ? log('Warning: *Empty table!* Not building a cache') : '';
}
if (c.debug) {
cacheTime = new Date();
}
// processing icon
if (c.showProcessing) {
ts.isProcessing(table, true);
}
for (k = 0; k < $tb.length; k++) {
colMax = []; // column max value per tbody
cc = c.cache[k] = {
normalized: [] // array of normalized row data; last entry contains "rowData" above
// colMax: # // added at the end
};
// ignore tbodies with class name from c.cssInfoBlock
if (!$tb.eq(k).hasClass(c.cssInfoBlock)) {
totalRows = ($tb[k] && $tb[k].rows.length) || 0;
for (i = 0; i < totalRows; ++i) {
rowData = {
// order: original row order #
// $row : jQuery Object[]
child: [] // child row text (filter widget)
};
/** Add the table data to main data array */
$row = $($tb[k].rows[i]);
rows = [ new Array(c.columns) ];
cols = [];
// if this is a child row, add it to the last row's children and continue to the next row
// ignore child row class, if it is the first row
if ($row.hasClass(c.cssChildRow) && i !== 0) {
t = cc.normalized.length - 1;
cc.normalized[t][c.columns].$row = cc.normalized[t][c.columns].$row.add($row);
// add "hasChild" class name to parent row
if (!$row.prev().hasClass(c.cssChildRow)) {
$row.prev().addClass(ts.css.cssHasChild);
}
// save child row content (un-parsed!)
rowData.child[t] = $.trim( $row[0].textContent || $row[0].innerText || $row.text() || "" );
// go to the next for loop
continue;
}
rowData.$row = $row;
rowData.order = i; // add original row position to rowCache
for (j = 0; j < c.columns; ++j) {
if (typeof parsers[j] === 'undefined') {
if (c.debug) {
log('No parser found for cell:', $row[0].cells[j], 'does it have a header?');
}
continue;
}
t = getElementText(table, $row[0].cells[j], j);
// do extract before parsing if there is one
if (typeof extractors[j].id === 'undefined') {
tx = t;
} else {
tx = extractors[j].format(t, table, $row[0].cells[j], j);
}
// allow parsing if the string is empty, previously parsing would change it to zero,
// in case the parser needs to extract data from the table cell attributes
v = parsers[j].id === 'no-parser' ? '' : parsers[j].format(tx, table, $row[0].cells[j], j);
cols.push( c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v );
if ((parsers[j].type || '').toLowerCase() === "numeric") {
// determine column max value (ignore sign)
colMax[j] = Math.max(Math.abs(v) || 0, colMax[j] || 0);
}
}
// ensure rowData is always in the same location (after the last column)
cols[c.columns] = rowData;
cc.normalized.push(cols);
}
cc.colMax = colMax;
// total up rows, not including child rows
c.totalRows += cc.normalized.length;
}
}
if (c.showProcessing) {
ts.isProcessing(table); // remove processing icon
}
if (c.debug) {
benchmark("Building cache for " + totalRows + " rows", cacheTime);
}
}
// init flag (true) used by pager plugin to prevent widget application
function appendToTable(table, init) {
var c = table.config,
wo = c.widgetOptions,
b = table.tBodies,
rows = [],
cc = c.cache,
n, totalRows, $bk, $tb,
i, k, appendTime;
// empty table - fixes #206/#346
if (isEmptyObject(cc)) {
// run pager appender in case the table was just emptied
return c.appender ? c.appender(table, rows) :
table.isUpdating ? c.$table.trigger("updateComplete", table) : ''; // Fixes #532
}
if (c.debug) {
appendTime = new Date();
}
for (k = 0; k < b.length; k++) {
$bk = $(b[k]);
if ($bk.length && !$bk.hasClass(c.cssInfoBlock)) {
// get tbody
$tb = ts.processTbody(table, $bk, true);
n = cc[k].normalized;
totalRows = n.length;
for (i = 0; i < totalRows; i++) {
rows.push(n[i][c.columns].$row);
// removeRows used by the pager plugin; don't render if using ajax - fixes #411
if (!c.appender || (c.pager && (!c.pager.removeRows || !wo.pager_removeRows) && !c.pager.ajax)) {
$tb.append(n[i][c.columns].$row);
}
}
// restore tbody
ts.processTbody(table, $tb, false);
}
}
if (c.appender) {
c.appender(table, rows);
}
if (c.debug) {
benchmark("Rebuilt table", appendTime);
}
// apply table widgets; but not before ajax completes
if (!init && !c.appender) { ts.applyWidget(table); }
if (table.isUpdating) {
c.$table.trigger("updateComplete", table);
}
}
function formatSortingOrder(v) {
// look for "d" in "desc" order; return true
return (/^d/i.test(v) || v === 1);
}
function buildHeaders(table) {
var ch, $t,
h, i, t, lock, time,
c = table.config;
c.headerList = [];
c.headerContent = [];
if (c.debug) {
time = new Date();
}
// children tr in tfoot - see issue #196 & #547
c.columns = ts.computeColumnIndex( c.$table.children('thead, tfoot').children('tr') );
// add icon if cssIcon option exists
i = c.cssIcon ? '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' : '';
// redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683
c.$headers = $(table).find(c.selectorHeaders).each(function(index) {
$t = $(this);
// make sure to get header cell & not column indexed cell
ch = ts.getColumnData( table, c.headers, index, true );
// save original header content
c.headerContent[index] = $(this).html();
// set up header template
t = c.headerTemplate.replace(/\{content\}/g, $(this).html()).replace(/\{icon\}/g, i);
if (c.onRenderTemplate) {
h = c.onRenderTemplate.apply($t, [index, t]);
if (h && typeof h === 'string') { t = h; } // only change t if something is returned
}
$(this).html('<div class="' + ts.css.headerIn + '">' + t + '</div>'); // faster than wrapInner
if (c.onRenderHeader) { c.onRenderHeader.apply($t, [index]); }
this.column = parseInt( $(this).attr('data-column'), 10);
this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2];
this.count = -1; // set to -1 because clicking on the header automatically adds one
this.lockedOrder = false;
lock = ts.getData($t, ch, 'lockedOrder') || false;
if (typeof lock !== 'undefined' && lock !== false) {
this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0];
}
$t.addClass(ts.css.header + ' ' + c.cssHeader);
// add cell to headerList
c.headerList[index] = this;
// add to parent in case there are multiple rows
$t.parent().addClass(ts.css.headerRow + ' ' + c.cssHeaderRow).attr('role', 'row');
// allow keyboard cursor to focus on element
if (c.tabIndex) { $t.attr("tabindex", 0); }
}).attr({
scope: 'col',
role : 'columnheader'
});
// enable/disable sorting
updateHeader(table);
if (c.debug) {
benchmark("Built headers:", time);
log(c.$headers);
}
}
function commonUpdate(table, resort, callback) {
var c = table.config;
// remove rows/elements before update
c.$table.find(c.selectorRemove).remove();
// rebuild parsers
buildParserCache(table);
// rebuild the cache map
buildCache(table);
checkResort(c.$table, resort, callback);
}
function updateHeader(table) {
var s, $th, col,
c = table.config;
c.$headers.each(function(index, th){
$th = $(th);
col = ts.getColumnData( table, c.headers, index, true );
// add "sorter-false" class if "parser-false" is set
s = ts.getData( th, col, 'sorter' ) === 'false' || ts.getData( th, col, 'parser' ) === 'false';
th.sortDisabled = s;
$th[ s ? 'addClass' : 'removeClass' ]('sorter-false').attr('aria-disabled', '' + s);
// aria-controls - requires table ID
if (table.id) {
if (s) {
$th.removeAttr('aria-controls');
} else {
$th.attr('aria-controls', table.id);
}
}
});
}
function setHeadersCss(table) {
var f, i, j,
c = table.config,
list = c.sortList,
len = list.length,
none = ts.css.sortNone + ' ' + c.cssNone,
css = [ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc],
aria = ['ascending', 'descending'],
// find the footer
$t = $(table).find('tfoot tr').children().add(c.$extraHeaders).removeClass(css.join(' '));
// remove all header information
c.$headers
.removeClass(css.join(' '))
.addClass(none).attr('aria-sort', 'none');
for (i = 0; i < len; i++) {
// direction = 2 means reset!
if (list[i][1] !== 2) {
// multicolumn sorting updating - choose the :last in case there are nested columns
f = c.$headers.not('.sorter-false').filter('[data-column="' + list[i][0] + '"]' + (len === 1 ? ':last' : '') );
if (f.length) {
for (j = 0; j < f.length; j++) {
if (!f[j].sortDisabled) {
f.eq(j).removeClass(none).addClass(css[list[i][1]]).attr('aria-sort', aria[list[i][1]]);
}
}
// add sorted class to footer & extra headers, if they exist
if ($t.length) {
$t.filter('[data-column="' + list[i][0] + '"]').removeClass(none).addClass(css[list[i][1]]);
}
}
}
}
// add verbose aria labels
c.$headers.not('.sorter-false').each(function(){
var $this = $(this),
nextSort = this.order[(this.count + 1) % (c.sortReset ? 3 : 2)],
txt = $this.text() + ': ' +
ts.language[ $this.hasClass(ts.css.sortAsc) ? 'sortAsc' : $this.hasClass(ts.css.sortDesc) ? 'sortDesc' : 'sortNone' ] +
ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ];
$this.attr('aria-label', txt );
});
}
// automatically add col group, and column sizes if set
function fixColumnWidth(table) {
if (table.config.widthFixed && $(table).find('colgroup').length === 0) {
var colgroup = $('<colgroup>'),
overallWidth = $(table).width();
// only add col for visible columns - fixes #371
$(table.tBodies[0]).find("tr:first").children(":visible").each(function() {
colgroup.append($('<col>').css('width', parseInt(($(this).width()/overallWidth)*1000, 10)/10 + '%'));
});
$(table).prepend(colgroup);
}
}
function updateHeaderSortCount(table, list) {
var s, t, o, col, primary,
c = table.config,
sl = list || c.sortList;
c.sortList = [];
$.each(sl, function(i,v){
// ensure all sortList values are numeric - fixes #127
col = parseInt(v[0], 10);
// make sure header exists
o = c.$headers.filter('[data-column="' + col + '"]:last')[0];
if (o) { // prevents error if sorton array is wrong
// o.count = o.count + 1;
t = ('' + v[1]).match(/^(1|d|s|o|n)/);
t = t ? t[0] : '';
// 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext
switch(t) {
case '1': case 'd': // descending
t = 1;
break;
case 's': // same direction (as primary column)
// if primary sort is set to "s", make it ascending
t = primary || 0;
break;
case 'o':
s = o.order[(primary || 0) % (c.sortReset ? 3 : 2)];
// opposite of primary column; but resets if primary resets
t = s === 0 ? 1 : s === 1 ? 0 : 2;
break;
case 'n':
o.count = o.count + 1;
t = o.order[(o.count) % (c.sortReset ? 3 : 2)];
break;
default: // ascending
t = 0;
break;
}
primary = i === 0 ? t : primary;
s = [ col, parseInt(t, 10) || 0 ];
c.sortList.push(s);
t = $.inArray(s[1], o.order); // fixes issue #167
o.count = t >= 0 ? t : s[1] % (c.sortReset ? 3 : 2);
}
});
}
function getCachedSortType(parsers, i) {
return (parsers && parsers[i]) ? parsers[i].type || '' : '';
}
function initSort(table, cell, event){
if (table.isUpdating) {
// let any updates complete before initializing a sort
return setTimeout(function(){ initSort(table, cell, event); }, 50);
}
var arry, indx, col, order, s,
c = table.config,
key = !event[c.sortMultiSortKey],
$table = c.$table;
// Only call sortStart if sorting is enabled
$table.trigger("sortStart", table);
// get current column sort order
cell.count = event[c.sortResetKey] ? 2 : (cell.count + 1) % (c.sortReset ? 3 : 2);
// reset all sorts on non-current column - issue #30
if (c.sortRestart) {
indx = cell;
c.$headers.each(function() {
// only reset counts on columns that weren't just clicked on and if not included in a multisort
if (this !== indx && (key || !$(this).is('.' + ts.css.sortDesc + ',.' + ts.css.sortAsc))) {
this.count = -1;
}
});
}
// get current column index
indx = cell.column;
// user only wants to sort on one column
if (key) {
// flush the sort list
c.sortList = [];
if (c.sortForce !== null) {
arry = c.sortForce;
for (col = 0; col < arry.length; col++) {
if (arry[col][0] !== indx) {
c.sortList.push(arry[col]);
}
}
}
// add column to sort list
order = cell.order[cell.count];
if (order < 2) {
c.sortList.push([indx, order]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (col = 1; col < cell.colSpan; col++) {
c.sortList.push([indx + col, order]);
}
}
}
// multi column sorting
} else {
// get rid of the sortAppend before adding more - fixes issue #115 & #523
if (c.sortAppend && c.sortList.length > 1) {
for (col = 0; col < c.sortAppend.length; col++) {
s = ts.isValueInArray(c.sortAppend[col][0], c.sortList);
if (s >= 0) {
c.sortList.splice(s,1);
}
}
}
// the user has clicked on an already sorted column
if (ts.isValueInArray(indx, c.sortList) >= 0) {
// reverse the sorting direction
for (col = 0; col < c.sortList.length; col++) {
s = c.sortList[col];
order = c.$headers.filter('[data-column="' + s[0] + '"]:last')[0];
if (s[0] === indx) {
// order.count seems to be incorrect when compared to cell.count
s[1] = order.order[cell.count];
if (s[1] === 2) {
c.sortList.splice(col,1);
order.count = -1;
}
}
}
} else {
// add column to sort list array
order = cell.order[cell.count];
if (order < 2) {
c.sortList.push([indx, order]);
// add other columns if header spans across multiple
if (cell.colSpan > 1) {
for (col = 1; col < cell.colSpan; col++) {
c.sortList.push([indx + col, order]);
}
}
}
}
}
if (c.sortAppend !== null) {
arry = c.sortAppend;
for (col = 0; col < arry.length; col++) {
if (arry[col][0] !== indx) {
c.sortList.push(arry[col]);
}
}
}
// sortBegin event triggered immediately before the sort
$table.trigger("sortBegin", table);
// setTimeout needed so the processing icon shows up
setTimeout(function(){
// set css for headers
setHeadersCss(table);
multisort(table);
appendToTable(table);
$table.trigger("sortEnd", table);
}, 1);
}
// sort multiple columns
function multisort(table) { /*jshint loopfunc:true */
var i, k, num, col, sortTime, colMax,
cache, order, sort, x, y,
dir = 0,
c = table.config,
cts = c.textSorter || '',
sortList = c.sortList,
l = sortList.length,
bl = table.tBodies.length;
if (c.serverSideSorting || isEmptyObject(c.cache)) { // empty table - fixes #206/#346
return;
}
if (c.debug) { sortTime = new Date(); }
for (k = 0; k < bl; k++) {
colMax = c.cache[k].colMax;
cache = c.cache[k].normalized;
cache.sort(function(a, b) {
// cache is undefined here in IE, so don't use it!
for (i = 0; i < l; i++) {
col = sortList[i][0];
order = sortList[i][1];
// sort direction, true = asc, false = desc
dir = order === 0;
if (c.sortStable && a[col] === b[col] && l === 1) {
return a[c.columns].order - b[c.columns].order;
}
// fallback to natural sort since it is more robust
num = /n/i.test(getCachedSortType(c.parsers, col));
if (num && c.strings[col]) {
// sort strings in numerical columns
if (typeof (c.string[c.strings[col]]) === 'boolean') {
num = (dir ? 1 : -1) * (c.string[c.strings[col]] ? -1 : 1);
} else {
num = (c.strings[col]) ? c.string[c.strings[col]] || 0 : 0;
}
// fall back to built-in numeric sort
// var sort = $.tablesorter["sort" + s](table, a[c], b[c], c, colMax[c], dir);
sort = c.numberSorter ? c.numberSorter(a[col], b[col], dir, colMax[col], table) :
ts[ 'sortNumeric' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], num, colMax[col], col, table);
} else {
// set a & b depending on sort direction
x = dir ? a : b;
y = dir ? b : a;
// text sort function
if (typeof(cts) === 'function') {
// custom OVERALL text sorter
sort = cts(x[col], y[col], dir, col, table);
} else if (typeof(cts) === 'object' && cts.hasOwnProperty(col)) {
// custom text sorter for a SPECIFIC COLUMN
sort = cts[col](x[col], y[col], dir, col, table);
} else {
// fall back to natural sort
sort = ts[ 'sortNatural' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], col, table, c);
}
}
if (sort) { return sort; }
}
return a[c.columns].order - b[c.columns].order;
});
}
if (c.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time", sortTime); }
}
function resortComplete($table, callback){
var table = $table[0];
if (table.isUpdating) {
$table.trigger('updateComplete');
}
if ($.isFunction(callback)) {
callback($table[0]);
}
}
function checkResort($table, flag, callback) {
var sl = $table[0].config.sortList;
// don't try to resort if the table is still processing
// this will catch spamming of the updateCell method
if (flag !== false && !$table[0].isProcessing && sl.length) {
$table.trigger("sorton", [sl, function(){
resortComplete($table, callback);
}, true]);
} else {
resortComplete($table, callback);
ts.applyWidget($table[0], false);
}
}
function bindMethods(table){
var c = table.config,
$table = c.$table;
// apply easy methods that trigger bound events
$table
.unbind('sortReset update updateRows updateCell updateAll addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join(c.namespace + ' '))
.bind("sortReset" + c.namespace, function(e, callback){
e.stopPropagation();
c.sortList = [];
setHeadersCss(table);
multisort(table);
appendToTable(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("updateAll" + c.namespace, function(e, resort, callback){
e.stopPropagation();
table.isUpdating = true;
ts.refreshWidgets(table, true, true);
ts.restoreHeaders(table);
buildHeaders(table);
ts.bindEvents(table, c.$headers, true);
bindMethods(table);
commonUpdate(table, resort, callback);
})
.bind("update" + c.namespace + " updateRows" + c.namespace, function(e, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
// update sorting (if enabled/disabled)
updateHeader(table);
commonUpdate(table, resort, callback);
})
.bind("updateCell" + c.namespace, function(e, cell, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
$table.find(c.selectorRemove).remove();
// get position from the dom
var v, t, row, icell,
$tb = $table.find('tbody'),
$cell = $(cell),
// update cache - format: function(s, table, cell, cellIndex)
// no closest in jQuery v1.2.6 - tbdy = $tb.index( $(cell).closest('tbody') ),$row = $(cell).closest('tr');
tbdy = $tb.index( $.fn.closest ? $cell.closest('tbody') : $cell.parents('tbody').filter(':first') ),
$row = $.fn.closest ? $cell.closest('tr') : $cell.parents('tr').filter(':first');
cell = $cell[0]; // in case cell is a jQuery object
// tbody may not exist if update is initialized while tbody is removed for processing
if ($tb.length && tbdy >= 0) {
row = $tb.eq(tbdy).find('tr').index( $row );
icell = $cell.index();
c.cache[tbdy].normalized[row][c.columns].$row = $row;
if (typeof c.extractors[icell].id === 'undefined') {
t = getElementText(table, cell, icell);
} else {
t = c.extractors[icell].format( getElementText(table, cell, icell), table, cell, icell );
}
v = c.parsers[icell].id === 'no-parser' ? '' :
c.parsers[icell].format( t, table, cell, icell );
c.cache[tbdy].normalized[row][icell] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v;
if ((c.parsers[icell].type || '').toLowerCase() === "numeric") {
// update column max value (ignore sign)
c.cache[tbdy].colMax[icell] = Math.max(Math.abs(v) || 0, c.cache[tbdy].colMax[icell] || 0);
}
checkResort($table, resort, callback);
}
})
.bind("addRows" + c.namespace, function(e, $row, resort, callback) {
e.stopPropagation();
table.isUpdating = true;
if (isEmptyObject(c.cache)) {
// empty table, do an update instead - fixes #450
updateHeader(table);
commonUpdate(table, resort, callback);
} else {
$row = $($row).attr('role', 'row'); // make sure we're using a jQuery object
var i, j, l, t, v, rowData, cells,
rows = $row.filter('tr').length,
tbdy = $table.find('tbody').index( $row.parents('tbody').filter(':first') );
// fixes adding rows to an empty table - see issue #179
if (!(c.parsers && c.parsers.length)) {
buildParserCache(table);
}
// add each row
for (i = 0; i < rows; i++) {
l = $row[i].cells.length;
cells = [];
rowData = {
child: [],
$row : $row.eq(i),
order: c.cache[tbdy].normalized.length
};
// add each cell
for (j = 0; j < l; j++) {
if (typeof c.extractors[j].id === 'undefined') {
t = getElementText(table, $row[i].cells[j], j);
} else {
t = c.extractors[j].format( getElementText(table, $row[i].cells[j], j), table, $row[i].cells[j], j );
}
v = c.parsers[j].id === 'no-parser' ? '' :
c.parsers[j].format( t, table, $row[i].cells[j], j );
cells[j] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v;
if ((c.parsers[j].type || '').toLowerCase() === "numeric") {
// update column max value (ignore sign)
c.cache[tbdy].colMax[j] = Math.max(Math.abs(cells[j]) || 0, c.cache[tbdy].colMax[j] || 0);
}
}
// add the row data to the end
cells.push(rowData);
// update cache
c.cache[tbdy].normalized.push(cells);
}
// resort using current settings
checkResort($table, resort, callback);
}
})
.bind("updateComplete" + c.namespace, function(){
table.isUpdating = false;
})
.bind("sorton" + c.namespace, function(e, list, callback, init) {
var c = table.config;
e.stopPropagation();
$table.trigger("sortStart", this);
// update header count index
updateHeaderSortCount(table, list);
// set css for headers
setHeadersCss(table);
// fixes #346
if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); }
$table.trigger("sortBegin", this);
// sort the table and append it to the dom
multisort(table);
appendToTable(table, init);
$table.trigger("sortEnd", this);
ts.applyWidget(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("appendCache" + c.namespace, function(e, callback, init) {
e.stopPropagation();
appendToTable(table, init);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("updateCache" + c.namespace, function(e, callback){
// rebuild parsers
if (!(c.parsers && c.parsers.length)) {
buildParserCache(table);
}
// rebuild the cache map
buildCache(table);
if ($.isFunction(callback)) {
callback(table);
}
})
.bind("applyWidgetId" + c.namespace, function(e, id) {
e.stopPropagation();
ts.getWidgetById(id).format(table, c, c.widgetOptions);
})
.bind("applyWidgets" + c.namespace, function(e, init) {
e.stopPropagation();
// apply widgets
ts.applyWidget(table, init);
})
.bind("refreshWidgets" + c.namespace, function(e, all, dontapply){
e.stopPropagation();
ts.refreshWidgets(table, all, dontapply);
})
.bind("destroy" + c.namespace, function(e, c, cb){
e.stopPropagation();
ts.destroy(table, c, cb);
})
.bind("resetToLoadState" + c.namespace, function(){
// remove all widgets
ts.refreshWidgets(table, true, true);
// restore original settings; this clears out current settings, but does not clear
// values saved to storage.
c = $.extend(true, ts.defaults, c.originalSettings);
table.hasInitialized = false;
// setup the entire table again
ts.setup( table, c );
});
}
/* public methods */
ts.construct = function(settings) {
return this.each(function() {
var table = this,
// merge & extend config options
c = $.extend(true, {}, ts.defaults, settings);
// save initial settings
c.originalSettings = settings;
// create a table from data (build table widget)
if (!table.hasInitialized && ts.buildTable && this.tagName !== 'TABLE') {
// return the table (in case the original target is the table's container)
ts.buildTable(table, c);
} else {
ts.setup(table, c);
}
});
};
ts.setup = function(table, c) {
// if no thead or tbody, or tablesorter is already present, quit
if (!table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true) {
return c.debug ? log('ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized') : '';
}
var k = '',
$table = $(table),
m = $.metadata;
// initialization flag
table.hasInitialized = false;
// table is being processed flag
table.isProcessing = true;
// make sure to store the config object
table.config = c;
// save the settings where they read
$.data(table, "tablesorter", c);
if (c.debug) { $.data( table, 'startoveralltimer', new Date()); }
// removing this in version 3 (only supports jQuery 1.7+)
c.supportsDataObject = (function(version) {
version[0] = parseInt(version[0], 10);
return (version[0] > 1) || (version[0] === 1 && parseInt(version[1], 10) >= 4);
})($.fn.jquery.split("."));
// digit sort text location; keeping max+/- for backwards compatibility
c.string = { 'max': 1, 'min': -1, 'emptyMin': 1, 'emptyMax': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false };
// add table theme class only if there isn't already one there
if (!/tablesorter\-/.test($table.attr('class'))) {
k = (c.theme !== '' ? ' tablesorter-' + c.theme : '');
}
c.table = table;
c.$table = $table
.addClass(ts.css.table + ' ' + c.tableClass + k)
.attr('role', 'grid');
c.$headers = $table.find(c.selectorHeaders);
// give the table a unique id, which will be used in namespace binding
if (!c.namespace) {
c.namespace = '.tablesorter' + Math.random().toString(16).slice(2);
} else {
// make sure namespace starts with a period & doesn't have weird characters
c.namespace = '.' + c.namespace.replace(/\W/g,'');
}
c.$table.children().children('tr').attr('role', 'row');
c.$tbodies = $table.children('tbody:not(.' + c.cssInfoBlock + ')').attr({
'aria-live' : 'polite',
'aria-relevant' : 'all'
});
if (c.$table.find('caption').length) {
c.$table.attr('aria-labelledby', 'theCaption');
}
c.widgetInit = {}; // keep a list of initialized widgets
// change textExtraction via data-attribute
c.textExtraction = c.$table.attr('data-text-extraction') || c.textExtraction || 'basic';
// build headers
buildHeaders(table);
// fixate columns if the users supplies the fixedWidth option
// do this after theme has been applied
fixColumnWidth(table);
// try to auto detect column type, and store in tables config
buildParserCache(table);
// start total row count at zero
c.totalRows = 0;
// build the cache for the tbody cells
// delayInit will delay building the cache until the user starts a sort
if (!c.delayInit) { buildCache(table); }
// bind all header events and methods
ts.bindEvents(table, c.$headers, true);
bindMethods(table);
// get sort list from jQuery data or metadata
// in jQuery < 1.4, an error occurs when calling $table.data()
if (c.supportsDataObject && typeof $table.data().sortlist !== 'undefined') {
c.sortList = $table.data().sortlist;
} else if (m && ($table.metadata() && $table.metadata().sortlist)) {
c.sortList = $table.metadata().sortlist;
}
// apply widget init code
ts.applyWidget(table, true);
// if user has supplied a sort list to constructor
if (c.sortList.length > 0) {
$table.trigger("sorton", [c.sortList, {}, !c.initWidgets, true]);
} else {
setHeadersCss(table);
if (c.initWidgets) {
// apply widget format
ts.applyWidget(table, false);
}
}
// show processesing icon
if (c.showProcessing) {
$table
.unbind('sortBegin' + c.namespace + ' sortEnd' + c.namespace)
.bind('sortBegin' + c.namespace + ' sortEnd' + c.namespace, function(e) {
clearTimeout(c.processTimer);
ts.isProcessing(table);
if (e.type === 'sortBegin') {
c.processTimer = setTimeout(function(){
ts.isProcessing(table, true);
}, 500);
}
});
}
// initialized
table.hasInitialized = true;
table.isProcessing = false;
if (c.debug) {
ts.benchmark("Overall initialization time", $.data( table, 'startoveralltimer'));
}
$table.trigger('tablesorter-initialized', table);
if (typeof c.initialized === 'function') { c.initialized(table); }
};
ts.getColumnData = function(table, obj, indx, getCell){
if (typeof obj === 'undefined' || obj === null) { return; }
table = $(table)[0];
var result, $h, k,
c = table.config;
if (obj[indx]) {
return getCell ? obj[indx] : obj[c.$headers.index( c.$headers.filter('[data-column="' + indx + '"]:last') )];
}
for (k in obj) {
if (typeof k === 'string') {
if (getCell) {
// get header cell
$h = c.$headers.eq(indx).filter(k);
} else {
// get column indexed cell
$h = c.$headers.filter('[data-column="' + indx + '"]:last').filter(k);
}
if ($h.length) {
return obj[k];
}
}
}
return result;
};
// computeTableHeaderCellIndexes from:
// http://www.javascripttoolbox.com/lib/table/examples.php
// http://www.javascripttoolbox.com/temp/table_cellindex.html
ts.computeColumnIndex = function(trs) {
var matrix = [],
lookup = {},
cols = 0, // determine the number of columns
i, j, k, l, $cell, cell, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow;
for (i = 0; i < trs.length; i++) {
cells = trs[i].cells;
for (j = 0; j < cells.length; j++) {
cell = cells[j];
$cell = $(cell);
rowIndex = cell.parentNode.rowIndex;
cellId = rowIndex + "-" + $cell.index();
rowSpan = cell.rowSpan || 1;
colSpan = cell.colSpan || 1;
if (typeof(matrix[rowIndex]) === "undefined") {
matrix[rowIndex] = [];
}
// Find first available column in the first row
for (k = 0; k < matrix[rowIndex].length + 1; k++) {
if (typeof(matrix[rowIndex][k]) === "undefined") {
firstAvailCol = k;
break;
}
}
lookup[cellId] = firstAvailCol;
cols = Math.max(firstAvailCol, cols);
// add data-column
$cell.attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex
for (k = rowIndex; k < rowIndex + rowSpan; k++) {
if (typeof(matrix[k]) === "undefined") {
matrix[k] = [];
}
matrixrow = matrix[k];
for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
matrixrow[l] = "x";
}
}
}
}
// may not be accurate if # header columns !== # tbody columns
return cols + 1; // add one because it's a zero-based index
};
// *** Process table ***
// add processing indicator
ts.isProcessing = function(table, toggle, $ths) {
table = $(table);
var c = table[0].config,
// default to all headers
$h = $ths || table.find('.' + ts.css.header);
if (toggle) {
// don't use sortList if custom $ths used
if (typeof $ths !== 'undefined' && c.sortList.length > 0) {
// get headers from the sortList
$h = $h.filter(function(){
// get data-column from attr to keep compatibility with jQuery 1.2.6
return this.sortDisabled ? false : ts.isValueInArray( parseFloat($(this).attr('data-column')), c.sortList) >= 0;
});
}
table.add($h).addClass(ts.css.processing + ' ' + c.cssProcessing);
} else {
table.add($h).removeClass(ts.css.processing + ' ' + c.cssProcessing);
}
};
// detach tbody but save the position
// don't use tbody because there are portions that look for a tbody index (updateCell)
ts.processTbody = function(table, $tb, getIt){
table = $(table)[0];
var holdr;
if (getIt) {
table.isProcessing = true;
$tb.before('<span class="tablesorter-savemyplace"/>');
holdr = ($.fn.detach) ? $tb.detach() : $tb.remove();
return holdr;
}
holdr = $(table).find('span.tablesorter-savemyplace');
$tb.insertAfter( holdr );
holdr.remove();
table.isProcessing = false;
};
ts.clearTableBody = function(table) {
$(table)[0].config.$tbodies.children().detach();
};
ts.bindEvents = function(table, $headers, core){
table = $(table)[0];
var downTime,
c = table.config;
if (core !== true) {
c.$extraHeaders = c.$extraHeaders ? c.$extraHeaders.add($headers) : $headers;
}
// apply event handling to headers and/or additional headers (stickyheaders, scroller, etc)
$headers
// http://stackoverflow.com/questions/5312849/jquery-find-self;
.find(c.selectorSort).add( $headers.filter(c.selectorSort) )
.unbind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '))
.bind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '), function(e, external) {
var cell, type = e.type;
// only recognize left clicks or enter
if ( ((e.which || e.button) !== 1 && !/sort|keyup/.test(type)) || (type === 'keyup' && e.which !== 13) ) {
return;
}
// ignore long clicks (prevents resizable widget from initializing a sort)
if (type === 'mouseup' && external !== true && (new Date().getTime() - downTime > 250)) { return; }
// set timer on mousedown
if (type === 'mousedown') {
downTime = new Date().getTime();
return /(input|select|button|textarea)/i.test(e.target.tagName) ? '' : !c.cancelSelection;
}
if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); }
// jQuery v1.2.6 doesn't have closest()
cell = $.fn.closest ? $(this).closest('th, td')[0] : /TH|TD/.test(this.tagName) ? this : $(this).parents('th, td')[0];
// reference original table headers and find the same cell
cell = c.$headers[ $headers.index( cell ) ];
if (!cell.sortDisabled) {
initSort(table, cell, e);
}
});
if (c.cancelSelection) {
// cancel selection
$headers
.attr('unselectable', 'on')
.bind('selectstart', false)
.css({
'user-select': 'none',
'MozUserSelect': 'none' // not needed for jQuery 1.8+
});
}
};
// restore headers
ts.restoreHeaders = function(table){
var c = $(table)[0].config;
// don't use c.$headers here in case header cells were swapped
c.$table.find(c.selectorHeaders).each(function(i){
// only restore header cells if it is wrapped
// because this is also used by the updateAll method
if ($(this).find('.' + ts.css.headerIn).length){
$(this).html( c.headerContent[i] );
}
});
};
ts.destroy = function(table, removeClasses, callback){
table = $(table)[0];
if (!table.hasInitialized) { return; }
// remove all widgets
ts.refreshWidgets(table, true, true);
var $t = $(table), c = table.config,
$h = $t.find('thead:first'),
$r = $h.find('tr.' + ts.css.headerRow).removeClass(ts.css.headerRow + ' ' + c.cssHeaderRow),
$f = $t.find('tfoot:first > tr').children('th, td');
if (removeClasses === false && $.inArray('uitheme', c.widgets) >= 0) {
// reapply uitheme classes, in case we want to maintain appearance
$t.trigger('applyWidgetId', ['uitheme']);
$t.trigger('applyWidgetId', ['zebra']);
}
// remove widget added rows, just in case
$h.find('tr').not($r).remove();
// disable tablesorter
$t
.removeData('tablesorter')
.unbind('sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState '.split(' ').join(c.namespace + ' '));
c.$headers.add($f)
.removeClass( [ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone].join(' ') )
.removeAttr('data-column')
.removeAttr('aria-label')
.attr('aria-disabled', 'true');
$r.find(c.selectorSort).unbind('mousedown mouseup keypress '.split(' ').join(c.namespace + ' '));
ts.restoreHeaders(table);
$t.toggleClass(ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false);
// clear flag in case the plugin is initialized again
table.hasInitialized = false;
delete table.config.cache;
if (typeof callback === 'function') {
callback(table);
}
};
// *** sort functions ***
// regex used in natural sort
ts.regex = {
chunk : /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // chunk/tokenize numbers & letters
chunks: /(^\\0|\\0$)/, // replace chunks @ ends
hex: /^0x[0-9a-f]+$/i // hex
};
// Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed)
// this function will only accept strings, or you'll see "TypeError: undefined is not a function"
// I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall
ts.sortNatural = function(a, b) {
if (a === b) { return 0; }
var xN, xD, yN, yD, xF, yF, i, mx,
r = ts.regex;
// first try and sort Hex codes
if (r.hex.test(b)) {
xD = parseInt(a.match(r.hex), 16);
yD = parseInt(b.match(r.hex), 16);
if ( xD < yD ) { return -1; }
if ( xD > yD ) { return 1; }
}
// chunk/tokenize
xN = a.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0');
yN = b.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0');
mx = Math.max(xN.length, yN.length);
// natural sorting through split numeric strings and default strings
for (i = 0; i < mx; i++) {
// find floats not starting with '0', string or 0 if not defined
xF = isNaN(xN[i]) ? xN[i] || 0 : parseFloat(xN[i]) || 0;
yF = isNaN(yN[i]) ? yN[i] || 0 : parseFloat(yN[i]) || 0;
// handle numeric vs string comparison - number < string - (Kyle Adams)
if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; }
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
if (typeof xF !== typeof yF) {
xF += '';
yF += '';
}
if (xF < yF) { return -1; }
if (xF > yF) { return 1; }
}
return 0;
};
ts.sortNaturalAsc = function(a, b, col, table, c) {
if (a === b) { return 0; }
var e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; }
return ts.sortNatural(a, b);
};
ts.sortNaturalDesc = function(a, b, col, table, c) {
if (a === b) { return 0; }
var e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; }
return ts.sortNatural(b, a);
};
// basic alphabetical sort
ts.sortText = function(a, b) {
return a > b ? 1 : (a < b ? -1 : 0);
};
// return text string value by adding up ascii value
// so the text is somewhat sorted when using a digital sort
// this is NOT an alphanumeric sort
ts.getTextValue = function(a, num, mx) {
if (mx) {
// make sure the text value is greater than the max numerical value (mx)
var i, l = a ? a.length : 0, n = mx + num;
for (i = 0; i < l; i++) {
n += a.charCodeAt(i);
}
return num * n;
}
return 0;
};
ts.sortNumericAsc = function(a, b, num, mx, col, table) {
if (a === b) { return 0; }
var c = table.config,
e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; }
if (isNaN(a)) { a = ts.getTextValue(a, num, mx); }
if (isNaN(b)) { b = ts.getTextValue(b, num, mx); }
return a - b;
};
ts.sortNumericDesc = function(a, b, num, mx, col, table) {
if (a === b) { return 0; }
var c = table.config,
e = c.string[ (c.empties[col] || c.emptyTo ) ];
if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; }
if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; }
if (isNaN(a)) { a = ts.getTextValue(a, num, mx); }
if (isNaN(b)) { b = ts.getTextValue(b, num, mx); }
return b - a;
};
ts.sortNumeric = function(a, b) {
return a - b;
};
// used when replacing accented characters during sorting
ts.characterEquivalents = {
"a" : "\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5", // áàâãäąå
"A" : "\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5", // ÁÀÂÃÄĄÅ
"c" : "\u00e7\u0107\u010d", // çćč
"C" : "\u00c7\u0106\u010c", // ÇĆČ
"e" : "\u00e9\u00e8\u00ea\u00eb\u011b\u0119", // éèêëěę
"E" : "\u00c9\u00c8\u00ca\u00cb\u011a\u0118", // ÉÈÊËĚĘ
"i" : "\u00ed\u00ec\u0130\u00ee\u00ef\u0131", // íìİîïı
"I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ
"o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö
"O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ
"ss": "\u00df", // ß (s sharp)
"SS": "\u1e9e", // ẞ (Capital sharp s)
"u" : "\u00fa\u00f9\u00fb\u00fc\u016f", // úùûüů
"U" : "\u00da\u00d9\u00db\u00dc\u016e" // ÚÙÛÜŮ
};
ts.replaceAccents = function(s) {
var a, acc = '[', eq = ts.characterEquivalents;
if (!ts.characterRegex) {
ts.characterRegexArray = {};
for (a in eq) {
if (typeof a === 'string') {
acc += eq[a];
ts.characterRegexArray[a] = new RegExp('[' + eq[a] + ']', 'g');
}
}
ts.characterRegex = new RegExp(acc + ']');
}
if (ts.characterRegex.test(s)) {
for (a in eq) {
if (typeof a === 'string') {
s = s.replace( ts.characterRegexArray[a], a );
}
}
}
return s;
};
// *** utilities ***
ts.isValueInArray = function(column, arry) {
var indx, len = arry.length;
for (indx = 0; indx < len; indx++) {
if (arry[indx][0] === column) {
return indx;
}
}
return -1;
};
ts.addParser = function(parser) {
var i, l = ts.parsers.length, a = true;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === parser.id.toLowerCase()) {
a = false;
}
}
if (a) {
ts.parsers.push(parser);
}
};
ts.getParserById = function(name) {
/*jshint eqeqeq:false */
if (name == 'false') { return false; }
var i, l = ts.parsers.length;
for (i = 0; i < l; i++) {
if (ts.parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) {
return ts.parsers[i];
}
}
return false;
};
ts.addWidget = function(widget) {
ts.widgets.push(widget);
};
ts.hasWidget = function(table, name){
table = $(table);
return table.length && table[0].config && table[0].config.widgetInit[name] || false;
};
ts.getWidgetById = function(name) {
var i, w, l = ts.widgets.length;
for (i = 0; i < l; i++) {
w = ts.widgets[i];
if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) {
return w;
}
}
};
ts.applyWidget = function(table, init) {
table = $(table)[0]; // in case this is called externally
var c = table.config,
wo = c.widgetOptions,
widgets = [],
time, w, wd;
// prevent numerous consecutive widget applications
if (init !== false && table.hasInitialized && (table.isApplyingWidgets || table.isUpdating)) { return; }
if (c.debug) { time = new Date(); }
if (c.widgets.length) {
table.isApplyingWidgets = true;
// ensure unique widget ids
c.widgets = $.grep(c.widgets, function(v, k){
return $.inArray(v, c.widgets) === k;
});
// build widget array & add priority as needed
$.each(c.widgets || [], function(i,n){
wd = ts.getWidgetById(n);
if (wd && wd.id) {
// set priority to 10 if not defined
if (!wd.priority) { wd.priority = 10; }
widgets[i] = wd;
}
});
// sort widgets by priority
widgets.sort(function(a, b){
return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1;
});
// add/update selected widgets
$.each(widgets, function(i,w){
if (w) {
if (init || !(c.widgetInit[w.id])) {
// set init flag first to prevent calling init more than once (e.g. pager)
c.widgetInit[w.id] = true;
if (w.hasOwnProperty('options')) {
wo = table.config.widgetOptions = $.extend( true, {}, w.options, wo );
}
if (w.hasOwnProperty('init')) {
w.init(table, w, c, wo);
}
}
if (!init && w.hasOwnProperty('format')) {
w.format(table, c, wo, false);
}
}
});
}
setTimeout(function(){
table.isApplyingWidgets = false;
}, 0);
if (c.debug) {
w = c.widgets.length;
benchmark("Completed " + (init === true ? "initializing " : "applying ") + w + " widget" + (w !== 1 ? "s" : ""), time);
}
};
ts.refreshWidgets = function(table, doAll, dontapply) {
table = $(table)[0]; // see issue #243
var i, c = table.config,
cw = c.widgets,
w = ts.widgets, l = w.length;
// remove previous widgets
for (i = 0; i < l; i++){
if ( w[i] && w[i].id && (doAll || $.inArray( w[i].id, cw ) < 0) ) {
if (c.debug) { log( 'Refeshing widgets: Removing "' + w[i].id + '"' ); }
// only remove widgets that have been initialized - fixes #442
if (w[i].hasOwnProperty('remove') && c.widgetInit[w[i].id]) {
w[i].remove(table, c, c.widgetOptions);
c.widgetInit[w[i].id] = false;
}
}
}
if (dontapply !== true) {
ts.applyWidget(table, doAll);
}
};
// get sorter, string, empty, etc options for each column from
// jQuery data, metadata, header option or header class name ("sorter-false")
// priority = jQuery data > meta > headers option > header class name
ts.getData = function(h, ch, key) {
var val = '', $h = $(h), m, cl;
if (!$h.length) { return ''; }
m = $.metadata ? $h.metadata() : false;
cl = ' ' + ($h.attr('class') || '');
if (typeof $h.data(key) !== 'undefined' || typeof $h.data(key.toLowerCase()) !== 'undefined'){
// "data-lockedOrder" is assigned to "lockedorder"; but "data-locked-order" is assigned to "lockedOrder"
// "data-sort-initial-order" is assigned to "sortInitialOrder"
val += $h.data(key) || $h.data(key.toLowerCase());
} else if (m && typeof m[key] !== 'undefined') {
val += m[key];
} else if (ch && typeof ch[key] !== 'undefined') {
val += ch[key];
} else if (cl !== ' ' && cl.match(' ' + key + '-')) {
// include sorter class name "sorter-text", etc; now works with "sorter-my-custom-parser"
val = cl.match( new RegExp('\\s' + key + '-([\\w-]+)') )[1] || '';
}
return $.trim(val);
};
ts.formatFloat = function(s, table) {
if (typeof s !== 'string' || s === '') { return s; }
// allow using formatFloat without a table; defaults to US number format
var i,
t = table && table.config ? table.config.usNumberFormat !== false :
typeof table !== "undefined" ? table : true;
if (t) {
// US Format - 1,234,567.89 -> 1234567.89
s = s.replace(/,/g,'');
} else {
// German Format = 1.234.567,89 -> 1234567.89
// French Format = 1 234 567,89 -> 1234567.89
s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.');
}
if(/^\s*\([.\d]+\)/.test(s)) {
// make (#) into a negative number -> (10) = -10
s = s.replace(/^\s*\(([.\d]+)\)/, '-$1');
}
i = parseFloat(s);
// return the text instead of zero
return isNaN(i) ? $.trim(s) : i;
};
ts.isDigit = function(s) {
// replace all unwanted chars and match
return isNaN(s) ? (/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g, '')) : true;
};
}()
});
// make shortcut
var ts = $.tablesorter;
// extend plugin scope
$.fn.extend({
tablesorter: ts.construct
});
// add default parsers
ts.addParser({
id: 'no-parser',
is: function() {
return false;
},
format: function() {
return '';
},
type: 'text'
});
ts.addParser({
id: "text",
is: function() {
return true;
},
format: function(s, table) {
var c = table.config;
if (s) {
s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s );
s = c.sortLocaleCompare ? ts.replaceAccents(s) : s;
}
return s;
},
type: "text"
});
ts.addParser({
id: "digit",
is: function(s) {
return ts.isDigit(s);
},
format: function(s, table) {
var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table);
return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s;
},
type: "numeric"
});
ts.addParser({
id: "currency",
is: function(s) {
return (/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s || '').replace(/[+\-,. ]/g,'')); // £$€¤¥¢
},
format: function(s, table) {
var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table);
return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s;
},
type: "numeric"
});
ts.addParser({
id: "ipAddress",
is: function(s) {
return (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s);
},
format: function(s, table) {
var i, a = s ? s.split(".") : '',
r = "",
l = a.length;
for (i = 0; i < l; i++) {
r += ("00" + a[i]).slice(-3);
}
return s ? ts.formatFloat(r, table) : s;
},
type: "numeric"
});
ts.addParser({
id: "url",
is: function(s) {
return (/^(https?|ftp|file):\/\//).test(s);
},
format: function(s) {
return s ? $.trim(s.replace(/(https?|ftp|file):\/\//, '')) : s;
},
type: "text"
});
ts.addParser({
id: "isoDate",
is: function(s) {
return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || s) : "", table) : s;
},
type: "numeric"
});
ts.addParser({
id: "percent",
is: function(s) {
return (/(\d\s*?%|%\s*?\d)/).test(s) && s.length < 15;
},
format: function(s, table) {
return s ? ts.formatFloat(s.replace(/%/g, ""), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "usLongDate",
is: function(s) {
// two digit years are not allowed cross-browser
// Jan 01, 2013 12:34:56 PM or 01 Jan 2013
return (/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s) || (/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat( (new Date(s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd"
is: function(s) {
// testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included
return (/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/).test((s || '').replace(/\s+/g," ").replace(/[\-.,]/g, "/"));
},
format: function(s, table, cell, cellIndex) {
if (s) {
var c = table.config,
ci = c.$headers.filter('[data-column=' + cellIndex + ']:last'),
format = ci.length && ci[0].dateFormat || ts.getData( ci, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat') || c.dateFormat;
s = s.replace(/\s+/g," ").replace(/[\-.,]/g, "/"); // escaped - because JSHint in Firefox was showing it as an error
if (format === "mmddyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2");
} else if (format === "ddmmyyyy") {
s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1");
} else if (format === "yyyymmdd") {
s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3");
}
}
return s ? ts.formatFloat( (new Date(s).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "time",
is: function(s) {
return (/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s);
},
format: function(s, table) {
return s ? ts.formatFloat( (new Date("2000/01/01 " + s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s;
},
type: "numeric"
});
ts.addParser({
id: "metadata",
is: function() {
return false;
},
format: function(s, table, cell) {
var c = table.config,
p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
return $(cell).metadata()[p];
},
type: "numeric"
});
// add default widgets
ts.addWidget({
id: "zebra",
priority: 90,
format: function(table, c, wo) {
var $tb, $tv, $tr, row, even, time, k, l,
child = new RegExp(c.cssChildRow, 'i'),
b = c.$tbodies;
if (c.debug) {
time = new Date();
}
for (k = 0; k < b.length; k++ ) {
// loop through the visible rows
$tb = b.eq(k);
l = $tb.children('tr').length;
if (l > 1) {
row = 0;
$tv = $tb.children('tr:visible').not(c.selectorRemove);
// revered back to using jQuery each - strangely it's the fastest method
/*jshint loopfunc:true */
$tv.each(function(){
$tr = $(this);
// style children rows the same way the parent row was styled
if (!child.test(this.className)) { row++; }
even = (row % 2 === 0);
$tr.removeClass(wo.zebra[even ? 1 : 0]).addClass(wo.zebra[even ? 0 : 1]);
});
}
}
if (c.debug) {
ts.benchmark("Applying Zebra widget", time);
}
},
remove: function(table, c, wo){
var k, $tb,
b = c.$tbodies,
rmv = (wo.zebra || [ "even", "odd" ]).join(' ');
for (k = 0; k < b.length; k++ ){
$tb = $.tablesorter.processTbody(table, b.eq(k), true); // remove tbody
$tb.children().removeClass(rmv);
$.tablesorter.processTbody(table, $tb, false); // restore tbody
}
}
});
})(jQuery);
return module.exports;
}).call(this);
// src/js/aui/tables-sortable.js
(typeof window === 'undefined' ? global : window).__118945205868b7541cf0a75d6522abd5 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
__f1a3fa76609e6d40a55157a38f5d9723;
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var DEFAULT_SORT_OPTIONS = {
sortMultiSortKey: '',
headers: {},
debug: false,
tabIndex: false
};
function sortTable($table) {
var options = DEFAULT_SORT_OPTIONS;
$table.find('th').each(function (index, header) {
var $header = (0, _jquery2.default)(header);
options.headers[index] = {};
if ($header.hasClass('aui-table-column-unsortable')) {
options.headers[index].sorter = false;
} else {
$header.attr('tabindex', '0');
$header.wrapInner("<span class='aui-table-header-content'/>");
if ($header.hasClass('aui-table-column-issue-key')) {
options.headers[index].sorter = 'issue-key';
}
}
});
$table.tablesorter(options);
}
var tablessortable = {
setup: function setup() {
/*
This parser is used for issue keys in the format <PROJECT_KEY>-<ISSUE_NUMBER>, where <PROJECT_KEY> is a maximum
10 character string with characters(A-Z). Assumes that issue number is no larger than 999,999. e.g. not more
than a million issues.
This pads the issue key to allow for proper string sorting so that the project key is always 10 characters and the
issue number is always 6 digits. e.g. it appends the project key '.' until it is 10 characters long and prepends 0
so that the issue number is 6 digits long. e.g. CONF-102 == CONF......000102. This is to allow proper string sorting.
*/
_jquery2.default.tablesorter.addParser({
id: 'issue-key',
is: function is() {
return false;
},
format: function format(s) {
var keyComponents = s.split('-');
var projectKey = keyComponents[0];
var issueNumber = keyComponents[1];
var PROJECT_KEY_TEMPLATE = '..........';
var ISSUE_NUMBER_TEMPLATE = '000000';
var stringRepresentation = (projectKey + PROJECT_KEY_TEMPLATE).slice(0, PROJECT_KEY_TEMPLATE.length);
stringRepresentation += (ISSUE_NUMBER_TEMPLATE + issueNumber).slice(-ISSUE_NUMBER_TEMPLATE.length);
return stringRepresentation;
},
type: 'text'
});
/*
Text parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is not set
or set to 'text'.
*/
_jquery2.default.tablesorter.addParser({
id: 'textSortAttributeParser',
is: function is(nodeValue, table, node) {
return node.hasAttribute('data-sort-value') && (!node.hasAttribute('data-sort-type') || node.getAttribute('data-sort-type') === 'text');
},
format: function format(nodeValue, table, node, offset) {
return node.getAttribute('data-sort-value');
},
type: 'text'
});
/*
Numeric parser that uses the data-sort-value attribute for sorting if it is set and data-sort-type is set
to 'numeric'.
*/
_jquery2.default.tablesorter.addParser({
id: 'numericSortAttributeParser',
is: function is(nodeValue, table, node) {
return node.getAttribute('data-sort-type') === 'numeric' && node.hasAttribute('data-sort-value');
},
format: function format(nodeValue, table, node, offset) {
return node.getAttribute('data-sort-value');
},
type: 'numeric'
});
(0, _jquery2.default)('.aui-table-sortable').each(function () {
sortTable((0, _jquery2.default)(this));
});
},
setTableSortable: function setTableSortable($table) {
sortTable($table);
}
};
(0, _jquery2.default)(tablessortable.setup);
(0, _globalize2.default)('tablessortable', tablessortable);
exports.default = tablessortable;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui/tipsy.js
(typeof window === 'undefined' ? global : window).__4887de1a729bad7b23da6129072d68ee = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
__dbb945ae8033589d400f8c63e7d01524;
return module.exports;
}).call(this);
// src/js/aui/toggle.js
(typeof window === 'undefined' ? global : window).__f243ae302e1f6512eaf4fb7ada716add = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
__313e15322266d7b6cc6ffb039891d9ce;
__6999efc8461cc8bcf32a985dbca81aa1;
var _attributes = __8f74d35e1223c8eb9f34b79717e74706;
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _enforcer = __65a8b3ca1b55232381cf1e189f6e2c47;
var _enforcer2 = _interopRequireDefault(_enforcer);
var _keyCode = __b925764b9e17cff61f648a86f18e6e25;
var _keyCode2 = _interopRequireDefault(_keyCode);
var _skatejsTemplateHtml = __9b18ba0583cb54ca87cfee562f9dc62a;
var _skatejsTemplateHtml2 = _interopRequireDefault(_skatejsTemplateHtml);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
var _constants = __e378fd259e8cc11973d9809608fe9a5e;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getInput(element) {
return element._input || (element._input = element.querySelector('input'));
}
function removedAttributeHandler(attributeName, element) {
getInput(element).removeAttribute(attributeName);
}
function fallbackAttributeHandler(attributeName, element, change) {
getInput(element).setAttribute(attributeName, change.newValue);
}
function getAttributeHandler(attributeName) {
return {
removed: removedAttributeHandler.bind(this, attributeName),
fallback: fallbackAttributeHandler.bind(this, attributeName)
};
}
var formAttributeHandler = {
removed: function removed(element) {
removedAttributeHandler.call(this, 'form', element);
element._formId = null;
},
fallback: function fallback(element, change) {
fallbackAttributeHandler.call(this, 'form', element, change);
element._formId = change.newValue;
}
};
var idAttributeHandler = {
removed: removedAttributeHandler.bind(undefined, 'id'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('id', '' + change.newValue + _constants.INPUT_SUFFIX);
}
};
var checkedAttributeHandler = {
removed: function removed(element) {
removedAttributeHandler.call(this, 'checked', element);
getInput(element).checked = false;
},
fallback: function fallback(element, change) {
fallbackAttributeHandler.call(this, 'checked', element, change);
getInput(element).checked = true;
}
};
var labelHandler = {
removed: function removed(element) {
getInput(element).removeAttribute('aria-label');
},
fallback: function fallback(element, change) {
getInput(element).setAttribute('aria-label', change.newValue);
}
};
function clickHandler(element, e) {
if (!element.disabled && !element.busy && e.target !== element._input) {
element._input.click();
}
(0, _attributes.setBooleanAttribute)(element, 'checked', getInput(element).checked);
}
function setDisabledForLabels(element, disabled) {
if (!element.id) {
return;
}
Array.prototype.forEach.call(document.querySelectorAll('aui-label[for="' + element.id + '"]'), function (el) {
el.disabled = disabled;
});
}
/**
* Workaround to prevent pressing SPACE on busy state.
* Preventing click event still makes the toggle flip and revert back.
* So on CSS side, the input has "pointer-events: none" on busy state.
*/
function bindEventsToInput(element) {
element._input.addEventListener('keydown', function (e) {
if (element.busy && e.keyCode === _keyCode2.default.SPACE) {
e.preventDefault();
}
});
// prevent toggle can be trigger through SPACE key on Firefox
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
element._input.addEventListener('click', function (e) {
if (element.busy) {
e.preventDefault();
}
});
}
}
(0, _skate2.default)('aui-toggle', {
template: (0, _skatejsTemplateHtml2.default)('<input type="checkbox" class="aui-toggle-input">', '<span class="aui-toggle-view">', '<span class="aui-toggle-tick aui-icon aui-icon-small aui-iconfont-success"></span>', '<span class="aui-toggle-cross aui-icon aui-icon-small aui-iconfont-close-dialog"></span>', '</span>'),
created: function created(element) {
element._input = getInput(element); // avoid using _input in attribute handlers
element._tick = element.querySelector('.aui-toggle-tick');
element._cross = element.querySelector('.aui-toggle-cross');
(0, _jquery2.default)(element._input).tooltip({
title: function title() {
return this.checked ? this.getAttribute('tooltip-on') : this.getAttribute('tooltip-off');
},
gravity: 's',
hoverable: false
});
bindEventsToInput(element);
},
attached: function attached(element) {
(0, _enforcer2.default)(element).attributeExists('label');
},
events: {
click: clickHandler
},
attributes: {
id: idAttributeHandler,
checked: checkedAttributeHandler,
disabled: getAttributeHandler('disabled'),
form: formAttributeHandler,
name: getAttributeHandler('name'),
value: getAttributeHandler('value'),
'tooltip-on': {
value: AJS.I18n.getText('aui.toggle.on'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('tooltip-on', change.newValue || AJS.I18n.getText('aui.toggle.on'));
}
},
'tooltip-off': {
value: AJS.I18n.getText('aui.toggle.off'),
fallback: function fallback(element, change) {
getInput(element).setAttribute('tooltip-off', change.newValue || AJS.I18n.getText('aui.toggle.off'));
}
},
label: labelHandler
},
prototype: {
focus: function focus() {
this._input.focus();
return this;
},
get checked() {
return this._input.checked;
},
set checked(value) {
// Need to explicitly set the property on the checkbox because the
// checkbox's property doesn't change with it's attribute after it
// is clicked.
this._input.checked = value;
return (0, _attributes.setBooleanAttribute)(this, 'checked', value);
},
get disabled() {
return this._input.disabled;
},
set disabled(value) {
return (0, _attributes.setBooleanAttribute)(this, 'disabled', value);
},
get form() {
return document.getElementById(this._formId);
},
set form(value) {
formAttributeHandler.fallback.call(this, this, { newValue: value || null });
return this.form;
},
get name() {
return this._input.name;
},
set name(value) {
this.setAttribute('name', value);
return value;
},
get value() {
return this._input.value;
},
set value(value) {
// Setting the value of an input to null sets it to empty string.
this.setAttribute('value', value === null ? '' : value);
return value;
},
get busy() {
return this._input.getAttribute('aria-busy') === 'true';
},
set busy(value) {
(0, _attributes.setBooleanAttribute)(this, 'busy', value);
if (value) {
this._input.setAttribute('aria-busy', 'true');
this._input.indeterminate = true;
if (this.checked) {
(0, _jquery2.default)(this._input).addClass('indeterminate-checked');
(0, _jquery2.default)(this._tick).spin({ zIndex: null });
} else {
(0, _jquery2.default)(this._cross).spin({ zIndex: null, color: 'black' });
}
} else {
(0, _jquery2.default)(this._input).removeClass('indeterminate-checked');
this._input.indeterminate = false;
this._input.removeAttribute('aria-busy');
(0, _jquery2.default)(this._cross).spinStop();
(0, _jquery2.default)(this._tick).spinStop();
}
setDisabledForLabels(this, !!value);
return value;
}
}
});
return module.exports;
}).call(this);
// src/js/aui/trigger.js
(typeof window === 'undefined' ? global : window).__6575f5dae6f74a5f7933cb7c2b4fcebb = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _jquery = __77629c8e853846530dfdc3ccd3393ab6;
var _jquery2 = _interopRequireDefault(_jquery);
var _amdify = __a94c70e97545519793c3abf603e0b37c;
var _amdify2 = _interopRequireDefault(_amdify);
var _skate = __bb6ec7268c91759bbe10bd46d924551e;
var _skate2 = _interopRequireDefault(_skate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isNestedAnchor(trigger, target) {
var $closestAnchor = (0, _jquery2.default)(target).closest('a[href]', trigger);
return !!$closestAnchor.length && $closestAnchor[0] !== trigger;
}
function findControlled(trigger) {
return document.getElementById(trigger.getAttribute('aria-controls'));
}
function triggerMessage(trigger, e) {
if (trigger.isEnabled()) {
var component = findControlled(trigger);
if (component && component.message) {
component.message(e);
}
}
}
(0, _skate2.default)('data-aui-trigger', {
type: _skate2.default.type.ATTRIBUTE,
events: {
click: function click(trigger, e) {
if (!isNestedAnchor(trigger, e.target)) {
triggerMessage(trigger, e);
e.preventDefault();
}
},
mouseenter: function mouseenter(trigger, e) {
triggerMessage(trigger, e);
},
mouseleave: function mouseleave(trigger, e) {
triggerMessage(trigger, e);
},
focus: function focus(trigger, e) {
triggerMessage(trigger, e);
},
blur: function blur(trigger, e) {
triggerMessage(trigger, e);
}
},
prototype: {
disable: function disable() {
this.setAttribute('aria-disabled', 'true');
},
enable: function enable() {
this.setAttribute('aria-disabled', 'false');
},
isEnabled: function isEnabled() {
return this.getAttribute('aria-disabled') !== 'true';
}
}
});
(0, _amdify2.default)('aui/trigger');
return module.exports;
}).call(this);
// src/js/aui/truncating-progressive-data-set.js
(typeof window === 'undefined' ? global : window).__ca2b25ca788dc66f3403f1141687f275 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _globalize = __77af00e80ac034b223816679459a4692;
var _globalize2 = _interopRequireDefault(_globalize);
var _progressiveDataSet = __bc3aa98a1624c420c64de6459784d4cc;
var _progressiveDataSet2 = _interopRequireDefault(_progressiveDataSet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TruncatingProgressiveDataSet = _progressiveDataSet2.default.extend({
/**
* This is a subclass of ProgressiveDataSet. It differs from the superclass
* in that it works on large data sets where the server truncates results.
*
* Rather than determining whether to request more information based on its cache,
* it uses the size of the response.
*
* @example
* var source = new TruncatingProgressiveDataSet([], {
* model: Backbone.Model.extend({ idAttribute: "username" }),
* queryEndpoint: "/jira/rest/latest/users",
* queryParamKey: "username",
* matcher: function(model, query) {
* return _.startsWith(model.get('username'), query);
* },
* maxResponseSize: 20
* });
* source.on('respond', doStuffWithMatchingResults);
* source.query('john');
*/
initialize: function initialize(models, options) {
this._maxResponseSize = options.maxResponseSize;
_progressiveDataSet2.default.prototype.initialize.call(this, models, options);
},
shouldGetMoreResults: function shouldGetMoreResults(results) {
var response = this.findQueryResponse(this.value);
return !response || response.length === this._maxResponseSize;
},
/**
* Returns the response for the given query.
*
* The default implementation assumes that the endpoint's search algorithm is a prefix
* matcher.
*
* @param query the value to find existing responses
* @return {Object[]} an array of values representing the IDs of the models provided by the response for the given query.
* Null is returned if no response is found.
*/
findQueryResponse: function findQueryResponse(query) {
while (query) {
var response = this.findQueryCache(query);
if (response) {
return response;
}
query = query.substr(0, query.length - 1);
}
return null;
}
});
(0, _globalize2.default)('TruncatingProgressiveDataSet', TruncatingProgressiveDataSet);
exports.default = TruncatingProgressiveDataSet;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui-experimental.js
(typeof window === 'undefined' ? global : window).__150b2bcd52fe83736fc6bc2287e90b75 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
__452d3f8e5d643ab60faf3f564b8276d8;
__e7296db63088f504f190097510a8efb3;
__133851082a1337b5710e5a2aa98258e9;
__bf3c38e4a0e7481b849a297fccf30258;
__3ac567a4ab4b829d5c6e6c81df33cbe8;
__f165ad68f415362651d0d7f733fcdcea;
__7c68b94bd1e7e5a2f72d197f55d1d459;
__bd4ecc7f267c4325495affa1d72b9196;
__7904d2f802801befa81e22aff0bd1fb6;
__ef3494fdb79b0ce378f14c1810d48a68;
__bc3aa98a1624c420c64de6459784d4cc;
__b12fa1032568f0d561e20a44ba70067a;
__d9778e9495b7a4889d0567cf2b8e1182;
__e9e07e92893b0b7f9f3e6e2ffe018c96;
__1e2a7fafeebd870fc623ea9cf84e84eb;
__c7e0d50b6a65bf58a28e1b310881043e;
__dfd5f5c723e08e5f95e38718fe4f73eb;
__810b6deefd6627f937e4a4d2fae0520a;
__313e15322266d7b6cc6ffb039891d9ce;
__118945205868b7541cf0a75d6522abd5;
__4887de1a729bad7b23da6129072d68ee;
__f243ae302e1f6512eaf4fb7ada716add;
__6999efc8461cc8bcf32a985dbca81aa1;
__6575f5dae6f74a5f7933cb7c2b4fcebb;
__ca2b25ca788dc66f3403f1141687f275;
exports.default = window.AJS;
module.exports = exports['default'];
return module.exports;
}).call(this); |
.storybook/config.js | dcwither/react-editable-decorator | import "./styles.css";
import { configure } from "@storybook/react";
// automatically import all files ending in *.stories.js
configure(
require.context("../stories", true, /\.stories\.(js|jsx|ts|tsx|mdx)$/),
module
);
|
src/icons/font/StyleIcon.js | skystebnicki/chamel | import React from 'react';
import PropTypes from 'prop-types';
import FontIcon from '../../FontIcon';
import ThemeService from '../../styles/ChamelThemeService';
/**
* Style button
*
* @param props
* @param context
* @returns {ReactDOM}
* @constructor
*/
const StyleIcon = (props, context) => {
let theme =
context.chamelTheme && context.chamelTheme.fontIcon
? context.chamelTheme.fontIcon
: ThemeService.defaultTheme.fontIcon;
return (
<FontIcon {...props} className={theme.iconStyle}>
{'style'}
</FontIcon>
);
};
/**
* An alternate theme may be passed down by a provider
*/
StyleIcon.contextTypes = {
chamelTheme: PropTypes.object,
};
export default StyleIcon;
|
ajax/libs/react-native-web/0.11.4/exports/TouchableOpacity/index.js | cdnjs/cdnjs | function _extends() { _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; }; return _extends.apply(this, arguments); }
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; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* 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 applyNativeMethods from '../../modules/applyNativeMethods';
import createReactClass from 'create-react-class';
import ensurePositiveDelayProps from '../Touchable/ensurePositiveDelayProps';
import { number } from 'prop-types';
import React from 'react';
import StyleSheet from '../StyleSheet';
import Touchable from '../Touchable';
import TouchableWithoutFeedback from '../TouchableWithoutFeedback';
import View from '../View';
var flattenStyle = StyleSheet.flatten;
var PRESS_RETENTION_OFFSET = {
top: 20,
left: 20,
right: 20,
bottom: 30
};
/**
* A wrapper for making views respond properly to touches.
* On press down, the opacity of the wrapped view is decreased, dimming it.
*
* Opacity is controlled by wrapping the children in a View, which is
* added to the view hiearchy. Be aware that this can affect layout.
*
* Example:
*
* ```
* renderButton: function() {
* return (
* <TouchableOpacity onPress={this._onPressButton}>
* <Image
* style={styles.button}
* source={require('./myButton.png')}
* />
* </TouchableOpacity>
* );
* },
* ```
*/
/* eslint-disable react/prefer-es6-class */
var TouchableOpacity = createReactClass({
displayName: 'TouchableOpacity',
mixins: [Touchable.Mixin],
propTypes: _objectSpread({}, TouchableWithoutFeedback.propTypes, {
/**
* Determines what the opacity of the wrapped view should be when touch is
* active.
*/
activeOpacity: number,
focusedOpacity: number
}),
getDefaultProps: function getDefaultProps() {
return {
activeOpacity: 0.2,
focusedOpacity: 0.7
};
},
getInitialState: function getInitialState() {
return this.touchableGetInitialState();
},
componentDidMount: function componentDidMount() {
ensurePositiveDelayProps(this.props);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
ensurePositiveDelayProps(nextProps);
},
/**
* Animate the touchable to a new opacity.
*/
setOpacityTo: function setOpacityTo(value, duration) {
this.setNativeProps({
style: {
opacity: value,
transitionDuration: duration ? duration / 1000 + "s" : '0s'
}
});
},
/**
* `Touchable.Mixin` self callbacks. The mixin will invoke these if they are
* defined on your component.
*/
touchableHandleActivePressIn: function touchableHandleActivePressIn(e) {
if (e.dispatchConfig.registrationName === 'onResponderGrant') {
this._opacityActive(0);
} else {
this._opacityActive(150);
}
this.props.onPressIn && this.props.onPressIn(e);
},
touchableHandleActivePressOut: function touchableHandleActivePressOut(e) {
this._opacityInactive(250);
this.props.onPressOut && this.props.onPressOut(e);
},
touchableHandlePress: function touchableHandlePress(e) {
this.props.onPress && this.props.onPress(e);
},
touchableHandleLongPress: function touchableHandleLongPress(e) {
this.props.onLongPress && this.props.onLongPress(e);
},
touchableGetPressRectOffset: function touchableGetPressRectOffset() {
return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET;
},
touchableGetHitSlop: function touchableGetHitSlop() {
return this.props.hitSlop;
},
touchableGetHighlightDelayMS: function touchableGetHighlightDelayMS() {
return this.props.delayPressIn || 0;
},
touchableGetLongPressDelayMS: function touchableGetLongPressDelayMS() {
return this.props.delayLongPress === 0 ? 0 : this.props.delayLongPress || 500;
},
touchableGetPressOutDelayMS: function touchableGetPressOutDelayMS() {
return this.props.delayPressOut;
},
_opacityActive: function _opacityActive(duration) {
this.setOpacityTo(this.props.activeOpacity, duration);
},
_opacityInactive: function _opacityInactive(duration) {
this.setOpacityTo(this._getChildStyleOpacityWithDefault(), duration);
},
_opacityFocused: function _opacityFocused() {
this.setOpacityTo(this.props.focusedOpacity);
},
_getChildStyleOpacityWithDefault: function _getChildStyleOpacityWithDefault() {
var childStyle = flattenStyle(this.props.style) || {};
return childStyle.opacity === undefined ? 1 : childStyle.opacity;
},
render: function render() {
var _this$props = this.props,
activeOpacity = _this$props.activeOpacity,
focusedOpacity = _this$props.focusedOpacity,
delayLongPress = _this$props.delayLongPress,
delayPressIn = _this$props.delayPressIn,
delayPressOut = _this$props.delayPressOut,
onLongPress = _this$props.onLongPress,
onPress = _this$props.onPress,
onPressIn = _this$props.onPressIn,
onPressOut = _this$props.onPressOut,
pressRetentionOffset = _this$props.pressRetentionOffset,
other = _objectWithoutPropertiesLoose(_this$props, ["activeOpacity", "focusedOpacity", "delayLongPress", "delayPressIn", "delayPressOut", "onLongPress", "onPress", "onPressIn", "onPressOut", "pressRetentionOffset"]);
return React.createElement(View, _extends({}, other, {
accessible: this.props.accessible !== false,
onKeyDown: this.touchableHandleKeyEvent,
onKeyUp: this.touchableHandleKeyEvent,
onResponderGrant: this.touchableHandleResponderGrant,
onResponderMove: this.touchableHandleResponderMove,
onResponderRelease: this.touchableHandleResponderRelease,
onResponderTerminate: this.touchableHandleResponderTerminate,
onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest,
onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder,
style: [styles.root, !this.props.disabled && styles.actionable, this.props.style]
}), this.props.children, Touchable.renderDebugView({
color: 'blue',
hitSlop: this.props.hitSlop
}));
}
});
var styles = StyleSheet.create({
root: {
transitionProperty: 'opacity',
transitionDuration: '0.15s',
userSelect: 'none'
},
actionable: {
cursor: 'pointer',
touchAction: 'manipulation'
}
});
export default applyNativeMethods(TouchableOpacity); |
lib/yuilib/3.17.2/event-focus/event-focus.js | tlock/moodle | /*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2 ||
// If e.stopPropagation() is called, notify any
// delegate subs from the same container, but break
// once the container changes. This emulates
// delegate() behavior for events like 'click' which
// won't notify delegates higher up the parent axis.
(e.stopped && delegates[i+1] &&
delegates[i+1].container !== notifier.container)) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '3.17.2', {"requires": ["event-synthetic"]});
|
src/Well.js | chilts/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Well = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'well'
};
},
render() {
let classes = this.getBsClassSet();
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default Well;
|
examples/js/custom/pagination/custom-size-per-page.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-console: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn, SizePerPageDropDown } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(70);
export default class CustomSizePerPageDropDown extends React.Component {
constructor(props) {
super(props);
}
onToggleDropDown = (toggleDropDown) => {
// do your stuff here
console.log('toggle dropdown');
toggleDropDown();
}
renderSizePerPageDropDown = (props) => {
return (
<SizePerPageDropDown
className='my-size-per-page'
btnContextual='btn-warning'
variation='dropup'
onClick={ () => this.onToggleDropDown(props.toggleDropDown) }/>
);
}
render() {
const options = {
sizePerPageDropDown: this.renderSizePerPageDropDown
};
return (
<div>
<BootstrapTable
data={ products }
options={ options }
pagination>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
}
|
Examples/UIExplorer/BorderExample.js | mchinyakov/react-native | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
var React = require('react-native');
var {
StyleSheet,
View
} = React;
var styles = StyleSheet.create({
box: {
width: 100,
height: 100,
},
border1: {
borderWidth: 10,
borderColor: 'brown',
},
borderRadius: {
borderWidth: 10,
borderRadius: 10,
borderColor: 'cyan',
},
border2: {
borderWidth: 10,
borderTopColor: 'red',
borderRightColor: 'yellow',
borderBottomColor: 'green',
borderLeftColor: 'blue',
},
border3: {
borderColor: 'purple',
borderTopWidth: 10,
borderRightWidth: 20,
borderBottomWidth: 30,
borderLeftWidth: 40,
},
border4: {
borderTopWidth: 10,
borderTopColor: 'red',
borderRightWidth: 20,
borderRightColor: 'yellow',
borderBottomWidth: 30,
borderBottomColor: 'green',
borderLeftWidth: 40,
borderLeftColor: 'blue',
},
border5: {
borderRadius: 50,
borderTopWidth: 10,
borderTopColor: 'red',
borderRightWidth: 20,
borderRightColor: 'yellow',
borderBottomWidth: 30,
borderBottomColor: 'green',
borderLeftWidth: 40,
borderLeftColor: 'blue',
},
border6: {
borderTopWidth: 10,
borderTopColor: 'red',
borderRightWidth: 20,
borderRightColor: 'yellow',
borderBottomWidth: 30,
borderBottomColor: 'green',
borderLeftWidth: 40,
borderLeftColor: 'blue',
borderTopLeftRadius: 100,
},
border7: {
borderWidth: 10,
borderColor: 'rgba(255,0,0,0.5)',
borderRadius: 30,
overflow: 'hidden',
},
border7_inner: {
backgroundColor: 'blue',
width: 100,
height: 100
},
});
exports.title = 'Border';
exports.description = 'Demonstrates some of the border styles available to Views.';
exports.examples = [
{
title: 'Equal-Width / Same-Color',
description: 'borderWidth & borderColor',
render() {
return <View style={[styles.box, styles.border1]} />;
}
},
{
title: 'Equal-Width / Same-Color',
description: 'borderWidth & borderColor & borderRadius',
render() {
return <View style={[styles.box, styles.borderRadius]} />;
}
},
{
title: 'Equal-Width Borders',
description: 'borderWidth & border*Color',
render() {
return <View style={[styles.box, styles.border2]} />;
}
},
{
title: 'Same-Color Borders',
description: 'border*Width & borderColor',
render() {
return <View style={[styles.box, styles.border3]} />;
}
},
{
title: 'Custom Borders',
description: 'border*Width & border*Color',
render() {
return <View style={[styles.box, styles.border4]} />;
}
},
{
title: 'Custom Borders',
description: 'border*Width & border*Color',
platform: 'ios',
render() {
return <View style={[styles.box, styles.border5]} />;
}
},
{
title: 'Custom Borders',
description: 'border*Width & border*Color',
platform: 'ios',
render() {
return <View style={[styles.box, styles.border6]} />;
}
},
{
title: 'Custom Borders',
description: 'borderRadius & clipping',
platform: 'ios',
render() {
return (
<View style={[styles.box, styles.border7]}>
<View style={styles.border7_inner} />
</View>
);
}
},
];
|
src/svg-icons/image/tag-faces.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTagFaces = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
ImageTagFaces = pure(ImageTagFaces);
ImageTagFaces.displayName = 'ImageTagFaces';
ImageTagFaces.muiName = 'SvgIcon';
export default ImageTagFaces;
|
ajax/libs/yui/3.16.0/datatable-core/datatable-core-coverage.js | kentcdodds/cdnjs | /*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; }
if (!__coverage__['build/datatable-core/datatable-core.js']) {
__coverage__['build/datatable-core/datatable-core.js'] = {"path":"build/datatable-core/datatable-core.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0],"52":[0,0],"53":[0,0],"54":[0,0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0,0],"62":[0,0],"63":[0,0,0],"64":[0,0],"65":[0,0,0],"66":[0,0],"67":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":26},"end":{"line":1,"column":45}}},"2":{"name":"(anonymous_2)","line":38,"loc":{"start":{"line":38,"column":40},"end":{"line":38,"column":52}}},"3":{"name":"(anonymous_3)","line":231,"loc":{"start":{"line":231,"column":15},"end":{"line":231,"column":31}}},"4":{"name":"(anonymous_4)","line":278,"loc":{"start":{"line":278,"column":15},"end":{"line":278,"column":31}}},"5":{"name":"(anonymous_5)","line":344,"loc":{"start":{"line":344,"column":25},"end":{"line":344,"column":38}}},"6":{"name":"(anonymous_6)","line":357,"loc":{"start":{"line":357,"column":22},"end":{"line":357,"column":35}}},"7":{"name":"(anonymous_7)","line":377,"loc":{"start":{"line":377,"column":28},"end":{"line":377,"column":41}}},"8":{"name":"(anonymous_8)","line":406,"loc":{"start":{"line":406,"column":24},"end":{"line":406,"column":41}}},"9":{"name":"(anonymous_9)","line":429,"loc":{"start":{"line":429,"column":16},"end":{"line":429,"column":28}}},"10":{"name":"(anonymous_10)","line":445,"loc":{"start":{"line":445,"column":17},"end":{"line":445,"column":42}}},"11":{"name":"(anonymous_11)","line":468,"loc":{"start":{"line":468,"column":19},"end":{"line":468,"column":38}}},"12":{"name":"(anonymous_12)","line":480,"loc":{"start":{"line":480,"column":20},"end":{"line":480,"column":35}}},"13":{"name":"(anonymous_13)","line":500,"loc":{"start":{"line":500,"column":18},"end":{"line":500,"column":30}}},"14":{"name":"(anonymous_14)","line":526,"loc":{"start":{"line":526,"column":21},"end":{"line":526,"column":33}}},"15":{"name":"(anonymous_15)","line":544,"loc":{"start":{"line":544,"column":15},"end":{"line":544,"column":27}}},"16":{"name":"(anonymous_16)","line":569,"loc":{"start":{"line":569,"column":23},"end":{"line":569,"column":39}}},"17":{"name":"(anonymous_17)","line":607,"loc":{"start":{"line":607,"column":17},"end":{"line":607,"column":35}}},"18":{"name":"(anonymous_18)","line":653,"loc":{"start":{"line":653,"column":19},"end":{"line":653,"column":38}}},"19":{"name":"process","line":656,"loc":{"start":{"line":656,"column":8},"end":{"line":656,"column":31}}},"20":{"name":"(anonymous_20)","line":703,"loc":{"start":{"line":703,"column":17},"end":{"line":703,"column":32}}},"21":{"name":"copyObj","line":709,"loc":{"start":{"line":709,"column":8},"end":{"line":709,"column":28}}},"22":{"name":"genId","line":735,"loc":{"start":{"line":735,"column":8},"end":{"line":735,"column":29}}},"23":{"name":"process","line":749,"loc":{"start":{"line":749,"column":8},"end":{"line":749,"column":39}}},"24":{"name":"(anonymous_24)","line":805,"loc":{"start":{"line":805,"column":19},"end":{"line":805,"column":34}}},"25":{"name":"(anonymous_25)","line":828,"loc":{"start":{"line":828,"column":14},"end":{"line":828,"column":29}}},"26":{"name":"(anonymous_26)","line":866,"loc":{"start":{"line":866,"column":19},"end":{"line":866,"column":34}}},"27":{"name":"(anonymous_27)","line":871,"loc":{"start":{"line":871,"column":21},"end":{"line":871,"column":39}}},"28":{"name":"(anonymous_28)","line":898,"loc":{"start":{"line":898,"column":20},"end":{"line":898,"column":35}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1319,"column":76}},"2":{"start":{"line":11,"column":0},"end":{"line":24,"column":10}},"3":{"start":{"line":38,"column":0},"end":{"line":38,"column":55}},"4":{"start":{"line":40,"column":0},"end":{"line":199,"column":2}},"5":{"start":{"line":201,"column":0},"end":{"line":911,"column":3}},"6":{"start":{"line":232,"column":8},"end":{"line":232,"column":39}},"7":{"start":{"line":234,"column":8},"end":{"line":242,"column":9}},"8":{"start":{"line":235,"column":12},"end":{"line":239,"column":13}},"9":{"start":{"line":236,"column":16},"end":{"line":236,"column":48}},"10":{"start":{"line":238,"column":16},"end":{"line":238,"column":27}},"11":{"start":{"line":241,"column":12},"end":{"line":241,"column":46}},"12":{"start":{"line":244,"column":8},"end":{"line":246,"column":9}},"13":{"start":{"line":245,"column":12},"end":{"line":245,"column":23}},"14":{"start":{"line":248,"column":8},"end":{"line":248,"column":38}},"15":{"start":{"line":250,"column":8},"end":{"line":259,"column":9}},"16":{"start":{"line":251,"column":12},"end":{"line":251,"column":33}},"17":{"start":{"line":252,"column":12},"end":{"line":252,"column":27}},"18":{"start":{"line":254,"column":12},"end":{"line":256,"column":13}},"19":{"start":{"line":255,"column":16},"end":{"line":255,"column":63}},"20":{"start":{"line":258,"column":12},"end":{"line":258,"column":51}},"21":{"start":{"line":261,"column":8},"end":{"line":261,"column":20}},"22":{"start":{"line":279,"column":8},"end":{"line":279,"column":78}},"23":{"start":{"line":281,"column":8},"end":{"line":290,"column":9}},"24":{"start":{"line":282,"column":12},"end":{"line":284,"column":13}},"25":{"start":{"line":283,"column":16},"end":{"line":283,"column":46}},"26":{"start":{"line":287,"column":12},"end":{"line":289,"column":13}},"27":{"start":{"line":288,"column":16},"end":{"line":288,"column":73}},"28":{"start":{"line":292,"column":8},"end":{"line":292,"column":30}},"29":{"start":{"line":345,"column":8},"end":{"line":345,"column":37}},"30":{"start":{"line":358,"column":8},"end":{"line":358,"column":33}},"31":{"start":{"line":360,"column":8},"end":{"line":360,"column":29}},"32":{"start":{"line":362,"column":8},"end":{"line":366,"column":9}},"33":{"start":{"line":365,"column":12},"end":{"line":365,"column":32}},"34":{"start":{"line":378,"column":8},"end":{"line":378,"column":38}},"35":{"start":{"line":380,"column":8},"end":{"line":380,"column":35}},"36":{"start":{"line":382,"column":8},"end":{"line":382,"column":30}},"37":{"start":{"line":384,"column":8},"end":{"line":390,"column":9}},"38":{"start":{"line":385,"column":12},"end":{"line":389,"column":13}},"39":{"start":{"line":386,"column":16},"end":{"line":386,"column":36}},"40":{"start":{"line":388,"column":16},"end":{"line":388,"column":58}},"41":{"start":{"line":407,"column":8},"end":{"line":407,"column":26}},"42":{"start":{"line":409,"column":8},"end":{"line":417,"column":9}},"43":{"start":{"line":410,"column":12},"end":{"line":410,"column":23}},"44":{"start":{"line":412,"column":12},"end":{"line":414,"column":13}},"45":{"start":{"line":413,"column":16},"end":{"line":413,"column":37}},"46":{"start":{"line":415,"column":15},"end":{"line":417,"column":9}},"47":{"start":{"line":416,"column":12},"end":{"line":416,"column":26}},"48":{"start":{"line":419,"column":8},"end":{"line":419,"column":76}},"49":{"start":{"line":430,"column":8},"end":{"line":430,"column":72}},"50":{"start":{"line":449,"column":8},"end":{"line":449,"column":59}},"51":{"start":{"line":469,"column":8},"end":{"line":469,"column":63}},"52":{"start":{"line":487,"column":8},"end":{"line":487,"column":53}},"53":{"start":{"line":501,"column":8},"end":{"line":502,"column":17}},"54":{"start":{"line":505,"column":8},"end":{"line":514,"column":9}},"55":{"start":{"line":507,"column":12},"end":{"line":507,"column":37}},"56":{"start":{"line":509,"column":12},"end":{"line":511,"column":13}},"57":{"start":{"line":510,"column":16},"end":{"line":510,"column":37}},"58":{"start":{"line":513,"column":12},"end":{"line":513,"column":44}},"59":{"start":{"line":516,"column":8},"end":{"line":516,"column":36}},"60":{"start":{"line":527,"column":8},"end":{"line":531,"column":11}},"61":{"start":{"line":545,"column":8},"end":{"line":547,"column":42}},"62":{"start":{"line":549,"column":8},"end":{"line":551,"column":9}},"63":{"start":{"line":550,"column":12},"end":{"line":550,"column":41}},"64":{"start":{"line":553,"column":8},"end":{"line":553,"column":25}},"65":{"start":{"line":570,"column":8},"end":{"line":570,"column":23}},"66":{"start":{"line":572,"column":8},"end":{"line":596,"column":9}},"67":{"start":{"line":573,"column":12},"end":{"line":573,"column":48}},"68":{"start":{"line":575,"column":12},"end":{"line":589,"column":13}},"69":{"start":{"line":576,"column":16},"end":{"line":576,"column":33}},"70":{"start":{"line":578,"column":16},"end":{"line":580,"column":17}},"71":{"start":{"line":579,"column":20},"end":{"line":579,"column":49}},"72":{"start":{"line":584,"column":16},"end":{"line":584,"column":46}},"73":{"start":{"line":586,"column":16},"end":{"line":588,"column":17}},"74":{"start":{"line":587,"column":20},"end":{"line":587,"column":49}},"75":{"start":{"line":595,"column":12},"end":{"line":595,"column":38}},"76":{"start":{"line":608,"column":8},"end":{"line":610,"column":23}},"77":{"start":{"line":614,"column":8},"end":{"line":614,"column":37}},"78":{"start":{"line":620,"column":8},"end":{"line":633,"column":9}},"79":{"start":{"line":621,"column":12},"end":{"line":622,"column":51}},"80":{"start":{"line":624,"column":12},"end":{"line":628,"column":13}},"81":{"start":{"line":625,"column":16},"end":{"line":625,"column":49}},"82":{"start":{"line":626,"column":19},"end":{"line":628,"column":13}},"83":{"start":{"line":627,"column":16},"end":{"line":627,"column":40}},"84":{"start":{"line":630,"column":12},"end":{"line":632,"column":13}},"85":{"start":{"line":631,"column":16},"end":{"line":631,"column":45}},"86":{"start":{"line":635,"column":8},"end":{"line":635,"column":28}},"87":{"start":{"line":637,"column":8},"end":{"line":637,"column":32}},"88":{"start":{"line":639,"column":8},"end":{"line":639,"column":31}},"89":{"start":{"line":654,"column":8},"end":{"line":654,"column":21}},"90":{"start":{"line":656,"column":8},"end":{"line":678,"column":9}},"91":{"start":{"line":657,"column":12},"end":{"line":657,"column":33}},"92":{"start":{"line":659,"column":12},"end":{"line":677,"column":13}},"93":{"start":{"line":660,"column":16},"end":{"line":660,"column":30}},"94":{"start":{"line":661,"column":16},"end":{"line":661,"column":30}},"95":{"start":{"line":668,"column":16},"end":{"line":670,"column":17}},"96":{"start":{"line":669,"column":20},"end":{"line":669,"column":35}},"97":{"start":{"line":672,"column":16},"end":{"line":672,"column":35}},"98":{"start":{"line":674,"column":16},"end":{"line":676,"column":17}},"99":{"start":{"line":675,"column":20},"end":{"line":675,"column":42}},"100":{"start":{"line":680,"column":8},"end":{"line":680,"column":25}},"101":{"start":{"line":682,"column":8},"end":{"line":682,"column":30}},"102":{"start":{"line":704,"column":8},"end":{"line":707,"column":41}},"103":{"start":{"line":709,"column":8},"end":{"line":733,"column":9}},"104":{"start":{"line":710,"column":12},"end":{"line":711,"column":28}},"105":{"start":{"line":713,"column":12},"end":{"line":713,"column":26}},"106":{"start":{"line":714,"column":12},"end":{"line":714,"column":35}},"107":{"start":{"line":716,"column":12},"end":{"line":730,"column":13}},"108":{"start":{"line":717,"column":16},"end":{"line":729,"column":17}},"109":{"start":{"line":718,"column":20},"end":{"line":718,"column":33}},"110":{"start":{"line":720,"column":20},"end":{"line":728,"column":21}},"111":{"start":{"line":721,"column":24},"end":{"line":721,"column":48}},"112":{"start":{"line":722,"column":27},"end":{"line":728,"column":21}},"113":{"start":{"line":723,"column":24},"end":{"line":723,"column":51}},"114":{"start":{"line":725,"column":24},"end":{"line":725,"column":77}},"115":{"start":{"line":727,"column":24},"end":{"line":727,"column":43}},"116":{"start":{"line":732,"column":12},"end":{"line":732,"column":24}},"117":{"start":{"line":735,"column":8},"end":{"line":747,"column":9}},"118":{"start":{"line":738,"column":12},"end":{"line":738,"column":44}},"119":{"start":{"line":740,"column":12},"end":{"line":744,"column":13}},"120":{"start":{"line":741,"column":16},"end":{"line":741,"column":39}},"121":{"start":{"line":743,"column":16},"end":{"line":743,"column":31}},"122":{"start":{"line":746,"column":12},"end":{"line":746,"column":24}},"123":{"start":{"line":749,"column":8},"end":{"line":788,"column":9}},"124":{"start":{"line":750,"column":12},"end":{"line":751,"column":34}},"125":{"start":{"line":753,"column":12},"end":{"line":785,"column":13}},"126":{"start":{"line":754,"column":16},"end":{"line":755,"column":78}},"127":{"start":{"line":757,"column":16},"end":{"line":757,"column":36}},"128":{"start":{"line":760,"column":16},"end":{"line":764,"column":17}},"129":{"start":{"line":763,"column":20},"end":{"line":763,"column":34}},"130":{"start":{"line":765,"column":16},"end":{"line":769,"column":17}},"131":{"start":{"line":768,"column":20},"end":{"line":768,"column":41}},"132":{"start":{"line":771,"column":16},"end":{"line":775,"column":17}},"133":{"start":{"line":772,"column":20},"end":{"line":772,"column":41}},"134":{"start":{"line":774,"column":20},"end":{"line":774,"column":39}},"135":{"start":{"line":780,"column":16},"end":{"line":780,"column":63}},"136":{"start":{"line":782,"column":16},"end":{"line":784,"column":17}},"137":{"start":{"line":783,"column":20},"end":{"line":783,"column":62}},"138":{"start":{"line":787,"column":12},"end":{"line":787,"column":27}},"139":{"start":{"line":790,"column":8},"end":{"line":790,"column":35}},"140":{"start":{"line":806,"column":8},"end":{"line":806,"column":33}},"141":{"start":{"line":808,"column":8},"end":{"line":808,"column":44}},"142":{"start":{"line":829,"column":8},"end":{"line":831,"column":9}},"143":{"start":{"line":830,"column":12},"end":{"line":830,"column":21}},"144":{"start":{"line":833,"column":8},"end":{"line":849,"column":9}},"145":{"start":{"line":834,"column":12},"end":{"line":834,"column":37}},"146":{"start":{"line":840,"column":12},"end":{"line":840,"column":51}},"147":{"start":{"line":845,"column":12},"end":{"line":845,"column":28}},"148":{"start":{"line":846,"column":15},"end":{"line":849,"column":9}},"149":{"start":{"line":848,"column":12},"end":{"line":848,"column":26}},"150":{"start":{"line":851,"column":8},"end":{"line":851,"column":19}},"151":{"start":{"line":867,"column":8},"end":{"line":867,"column":17}},"152":{"start":{"line":869,"column":8},"end":{"line":875,"column":9}},"153":{"start":{"line":870,"column":12},"end":{"line":870,"column":22}},"154":{"start":{"line":871,"column":12},"end":{"line":873,"column":15}},"155":{"start":{"line":872,"column":16},"end":{"line":872,"column":46}},"156":{"start":{"line":874,"column":12},"end":{"line":874,"column":23}},"157":{"start":{"line":877,"column":8},"end":{"line":877,"column":30}},"158":{"start":{"line":879,"column":8},"end":{"line":879,"column":19}},"159":{"start":{"line":899,"column":8},"end":{"line":899,"column":23}},"160":{"start":{"line":902,"column":8},"end":{"line":906,"column":9}},"161":{"start":{"line":903,"column":12},"end":{"line":903,"column":29}},"162":{"start":{"line":904,"column":15},"end":{"line":906,"column":9}},"163":{"start":{"line":905,"column":12},"end":{"line":905,"column":54}},"164":{"start":{"line":908,"column":8},"end":{"line":908,"column":37}}},"branchMap":{"1":{"line":234,"type":"if","locations":[{"start":{"line":234,"column":8},"end":{"line":234,"column":8}},{"start":{"line":234,"column":8},"end":{"line":234,"column":8}}]},"2":{"line":234,"type":"binary-expr","locations":[{"start":{"line":234,"column":12},"end":{"line":234,"column":26}},{"start":{"line":234,"column":30},"end":{"line":234,"column":44}}]},"3":{"line":235,"type":"if","locations":[{"start":{"line":235,"column":12},"end":{"line":235,"column":12}},{"start":{"line":235,"column":12},"end":{"line":235,"column":12}}]},"4":{"line":235,"type":"binary-expr","locations":[{"start":{"line":235,"column":16},"end":{"line":235,"column":20}},{"start":{"line":235,"column":24},"end":{"line":235,"column":34}}]},"5":{"line":244,"type":"if","locations":[{"start":{"line":244,"column":8},"end":{"line":244,"column":8}},{"start":{"line":244,"column":8},"end":{"line":244,"column":8}}]},"6":{"line":250,"type":"if","locations":[{"start":{"line":250,"column":8},"end":{"line":250,"column":8}},{"start":{"line":250,"column":8},"end":{"line":250,"column":8}}]},"7":{"line":250,"type":"binary-expr","locations":[{"start":{"line":250,"column":12},"end":{"line":250,"column":26}},{"start":{"line":250,"column":30},"end":{"line":250,"column":43}}]},"8":{"line":254,"type":"binary-expr","locations":[{"start":{"line":254,"column":47},"end":{"line":254,"column":51}},{"start":{"line":254,"column":55},"end":{"line":254,"column":62}}]},"9":{"line":255,"type":"binary-expr","locations":[{"start":{"line":255,"column":23},"end":{"line":255,"column":36}},{"start":{"line":255,"column":40},"end":{"line":255,"column":62}}]},"10":{"line":258,"type":"binary-expr","locations":[{"start":{"line":258,"column":20},"end":{"line":258,"column":24}},{"start":{"line":258,"column":28},"end":{"line":258,"column":41}},{"start":{"line":258,"column":46},"end":{"line":258,"column":50}}]},"11":{"line":279,"type":"binary-expr","locations":[{"start":{"line":279,"column":21},"end":{"line":279,"column":44}},{"start":{"line":279,"column":48},"end":{"line":279,"column":77}}]},"12":{"line":281,"type":"if","locations":[{"start":{"line":281,"column":8},"end":{"line":281,"column":8}},{"start":{"line":281,"column":8},"end":{"line":281,"column":8}}]},"13":{"line":282,"type":"if","locations":[{"start":{"line":282,"column":12},"end":{"line":282,"column":12}},{"start":{"line":282,"column":12},"end":{"line":282,"column":12}}]},"14":{"line":287,"type":"if","locations":[{"start":{"line":287,"column":12},"end":{"line":287,"column":12}},{"start":{"line":287,"column":12},"end":{"line":287,"column":12}}]},"15":{"line":287,"type":"binary-expr","locations":[{"start":{"line":287,"column":16},"end":{"line":287,"column":23}},{"start":{"line":287,"column":27},"end":{"line":287,"column":36}},{"start":{"line":287,"column":40},"end":{"line":287,"column":59}}]},"16":{"line":292,"type":"binary-expr","locations":[{"start":{"line":292,"column":15},"end":{"line":292,"column":21}},{"start":{"line":292,"column":25},"end":{"line":292,"column":29}}]},"17":{"line":362,"type":"if","locations":[{"start":{"line":362,"column":8},"end":{"line":362,"column":8}},{"start":{"line":362,"column":8},"end":{"line":362,"column":8}}]},"18":{"line":362,"type":"binary-expr","locations":[{"start":{"line":362,"column":12},"end":{"line":362,"column":32}},{"start":{"line":362,"column":36},"end":{"line":362,"column":52}}]},"19":{"line":384,"type":"if","locations":[{"start":{"line":384,"column":8},"end":{"line":384,"column":8}},{"start":{"line":384,"column":8},"end":{"line":384,"column":8}}]},"20":{"line":384,"type":"binary-expr","locations":[{"start":{"line":384,"column":12},"end":{"line":384,"column":32}},{"start":{"line":384,"column":36},"end":{"line":384,"column":40}}]},"21":{"line":385,"type":"if","locations":[{"start":{"line":385,"column":12},"end":{"line":385,"column":12}},{"start":{"line":385,"column":12},"end":{"line":385,"column":12}}]},"22":{"line":409,"type":"if","locations":[{"start":{"line":409,"column":8},"end":{"line":409,"column":8}},{"start":{"line":409,"column":8},"end":{"line":409,"column":8}}]},"23":{"line":415,"type":"if","locations":[{"start":{"line":415,"column":15},"end":{"line":415,"column":15}},{"start":{"line":415,"column":15},"end":{"line":415,"column":15}}]},"24":{"line":449,"type":"cond-expr","locations":[{"start":{"line":449,"column":33},"end":{"line":449,"column":48}},{"start":{"line":449,"column":51},"end":{"line":449,"column":58}}]},"25":{"line":487,"type":"binary-expr","locations":[{"start":{"line":487,"column":15},"end":{"line":487,"column":18}},{"start":{"line":487,"column":23},"end":{"line":487,"column":32}},{"start":{"line":487,"column":36},"end":{"line":487,"column":51}}]},"26":{"line":501,"type":"binary-expr","locations":[{"start":{"line":501,"column":22},"end":{"line":501,"column":41}},{"start":{"line":501,"column":45},"end":{"line":501,"column":47}}]},"27":{"line":505,"type":"if","locations":[{"start":{"line":505,"column":8},"end":{"line":505,"column":8}},{"start":{"line":505,"column":8},"end":{"line":505,"column":8}}]},"28":{"line":505,"type":"binary-expr","locations":[{"start":{"line":505,"column":12},"end":{"line":505,"column":27}},{"start":{"line":505,"column":31},"end":{"line":505,"column":47}}]},"29":{"line":509,"type":"if","locations":[{"start":{"line":509,"column":12},"end":{"line":509,"column":12}},{"start":{"line":509,"column":12},"end":{"line":509,"column":12}}]},"30":{"line":549,"type":"if","locations":[{"start":{"line":549,"column":8},"end":{"line":549,"column":8}},{"start":{"line":549,"column":8},"end":{"line":549,"column":8}}]},"31":{"line":572,"type":"if","locations":[{"start":{"line":572,"column":8},"end":{"line":572,"column":8}},{"start":{"line":572,"column":8},"end":{"line":572,"column":8}}]},"32":{"line":575,"type":"if","locations":[{"start":{"line":575,"column":12},"end":{"line":575,"column":12}},{"start":{"line":575,"column":12},"end":{"line":575,"column":12}}]},"33":{"line":575,"type":"binary-expr","locations":[{"start":{"line":575,"column":16},"end":{"line":575,"column":20}},{"start":{"line":575,"column":24},"end":{"line":575,"column":33}},{"start":{"line":575,"column":37},"end":{"line":575,"column":48}}]},"34":{"line":578,"type":"if","locations":[{"start":{"line":578,"column":16},"end":{"line":578,"column":16}},{"start":{"line":578,"column":16},"end":{"line":578,"column":16}}]},"35":{"line":586,"type":"if","locations":[{"start":{"line":586,"column":16},"end":{"line":586,"column":16}},{"start":{"line":586,"column":16},"end":{"line":586,"column":16}}]},"36":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"37":{"line":621,"type":"binary-expr","locations":[{"start":{"line":621,"column":26},"end":{"line":621,"column":43}},{"start":{"line":621,"column":47},"end":{"line":621,"column":72}},{"start":{"line":622,"column":28},"end":{"line":622,"column":50}}]},"38":{"line":624,"type":"if","locations":[{"start":{"line":624,"column":12},"end":{"line":624,"column":12}},{"start":{"line":624,"column":12},"end":{"line":624,"column":12}}]},"39":{"line":626,"type":"if","locations":[{"start":{"line":626,"column":19},"end":{"line":626,"column":19}},{"start":{"line":626,"column":19},"end":{"line":626,"column":19}}]},"40":{"line":626,"type":"binary-expr","locations":[{"start":{"line":626,"column":23},"end":{"line":626,"column":36}},{"start":{"line":626,"column":40},"end":{"line":626,"column":51}}]},"41":{"line":630,"type":"if","locations":[{"start":{"line":630,"column":12},"end":{"line":630,"column":12}},{"start":{"line":630,"column":12},"end":{"line":630,"column":12}}]},"42":{"line":668,"type":"if","locations":[{"start":{"line":668,"column":16},"end":{"line":668,"column":16}},{"start":{"line":668,"column":16},"end":{"line":668,"column":16}}]},"43":{"line":668,"type":"binary-expr","locations":[{"start":{"line":668,"column":20},"end":{"line":668,"column":23}},{"start":{"line":668,"column":27},"end":{"line":668,"column":36}}]},"44":{"line":674,"type":"if","locations":[{"start":{"line":674,"column":16},"end":{"line":674,"column":16}},{"start":{"line":674,"column":16},"end":{"line":674,"column":16}}]},"45":{"line":717,"type":"if","locations":[{"start":{"line":717,"column":16},"end":{"line":717,"column":16}},{"start":{"line":717,"column":16},"end":{"line":717,"column":16}}]},"46":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":20},"end":{"line":720,"column":20}},{"start":{"line":720,"column":20},"end":{"line":720,"column":20}}]},"47":{"line":722,"type":"if","locations":[{"start":{"line":722,"column":27},"end":{"line":722,"column":27}},{"start":{"line":722,"column":27},"end":{"line":722,"column":27}}]},"48":{"line":725,"type":"cond-expr","locations":[{"start":{"line":725,"column":47},"end":{"line":725,"column":59}},{"start":{"line":725,"column":62},"end":{"line":725,"column":76}}]},"49":{"line":740,"type":"if","locations":[{"start":{"line":740,"column":12},"end":{"line":740,"column":12}},{"start":{"line":740,"column":12},"end":{"line":740,"column":12}}]},"50":{"line":755,"type":"cond-expr","locations":[{"start":{"line":755,"column":42},"end":{"line":755,"column":58}},{"start":{"line":755,"column":61},"end":{"line":755,"column":77}}]},"51":{"line":760,"type":"if","locations":[{"start":{"line":760,"column":16},"end":{"line":760,"column":16}},{"start":{"line":760,"column":16},"end":{"line":760,"column":16}}]},"52":{"line":765,"type":"if","locations":[{"start":{"line":765,"column":16},"end":{"line":765,"column":16}},{"start":{"line":765,"column":16},"end":{"line":765,"column":16}}]},"53":{"line":771,"type":"if","locations":[{"start":{"line":771,"column":16},"end":{"line":771,"column":16}},{"start":{"line":771,"column":16},"end":{"line":771,"column":16}}]},"54":{"line":780,"type":"binary-expr","locations":[{"start":{"line":780,"column":32},"end":{"line":780,"column":40}},{"start":{"line":780,"column":44},"end":{"line":780,"column":51}},{"start":{"line":780,"column":55},"end":{"line":780,"column":61}}]},"55":{"line":782,"type":"if","locations":[{"start":{"line":782,"column":16},"end":{"line":782,"column":16}},{"start":{"line":782,"column":16},"end":{"line":782,"column":16}}]},"56":{"line":790,"type":"binary-expr","locations":[{"start":{"line":790,"column":15},"end":{"line":790,"column":18}},{"start":{"line":790,"column":22},"end":{"line":790,"column":34}}]},"57":{"line":808,"type":"cond-expr","locations":[{"start":{"line":808,"column":30},"end":{"line":808,"column":33}},{"start":{"line":808,"column":36},"end":{"line":808,"column":43}}]},"58":{"line":829,"type":"if","locations":[{"start":{"line":829,"column":8},"end":{"line":829,"column":8}},{"start":{"line":829,"column":8},"end":{"line":829,"column":8}}]},"59":{"line":833,"type":"if","locations":[{"start":{"line":833,"column":8},"end":{"line":833,"column":8}},{"start":{"line":833,"column":8},"end":{"line":833,"column":8}}]},"60":{"line":846,"type":"if","locations":[{"start":{"line":846,"column":15},"end":{"line":846,"column":15}},{"start":{"line":846,"column":15},"end":{"line":846,"column":15}}]},"61":{"line":846,"type":"binary-expr","locations":[{"start":{"line":846,"column":19},"end":{"line":846,"column":23}},{"start":{"line":846,"column":27},"end":{"line":846,"column":36}},{"start":{"line":846,"column":40},"end":{"line":846,"column":51}}]},"62":{"line":869,"type":"if","locations":[{"start":{"line":869,"column":8},"end":{"line":869,"column":8}},{"start":{"line":869,"column":8},"end":{"line":869,"column":8}}]},"63":{"line":869,"type":"binary-expr","locations":[{"start":{"line":869,"column":12},"end":{"line":869,"column":15}},{"start":{"line":869,"column":19},"end":{"line":869,"column":30}},{"start":{"line":869,"column":34},"end":{"line":869,"column":60}}]},"64":{"line":902,"type":"if","locations":[{"start":{"line":902,"column":8},"end":{"line":902,"column":8}},{"start":{"line":902,"column":8},"end":{"line":902,"column":8}}]},"65":{"line":902,"type":"binary-expr","locations":[{"start":{"line":902,"column":12},"end":{"line":902,"column":27}},{"start":{"line":902,"column":31},"end":{"line":902,"column":51}},{"start":{"line":902,"column":55},"end":{"line":902,"column":77}}]},"66":{"line":904,"type":"if","locations":[{"start":{"line":904,"column":15},"end":{"line":904,"column":15}},{"start":{"line":904,"column":15},"end":{"line":904,"column":15}}]},"67":{"line":908,"type":"binary-expr","locations":[{"start":{"line":908,"column":15},"end":{"line":908,"column":25}},{"start":{"line":908,"column":29},"end":{"line":908,"column":36}}]}},"code":["(function () { YUI.add('datatable-core', function (Y, NAME) {","","/**","The core implementation of the `DataTable` and `DataTable.Base` Widgets.","","@module datatable","@submodule datatable-core","@since 3.5.0","**/","","var INVALID = Y.Attribute.INVALID_VALUE,",""," Lang = Y.Lang,"," isFunction = Lang.isFunction,"," isObject = Lang.isObject,"," isArray = Lang.isArray,"," isString = Lang.isString,"," isNumber = Lang.isNumber,",""," toArray = Y.Array,",""," keys = Y.Object.keys,",""," Table;","","/**","_API docs for this extension are included in the DataTable class._","","Class extension providing the core API and structure for the DataTable Widget.","","Use this class extension with Widget or another Base-based superclass to create","the basic DataTable model API and composing class structure.","","@class DataTable.Core","@for DataTable","@since 3.5.0","**/","Table = Y.namespace('DataTable').Core = function () {};","","Table.ATTRS = {"," /**"," Columns to include in the rendered table.",""," If omitted, the attributes on the configured `recordType` or the first item"," in the `data` collection will be used as a source.",""," This attribute takes an array of strings or objects (mixing the two is"," fine). Each string or object is considered a column to be rendered."," Strings are converted to objects, so `columns: ['first', 'last']` becomes"," `columns: [{ key: 'first' }, { key: 'last' }]`.",""," DataTable.Core only concerns itself with a few properties of columns."," These properties are:",""," * `key` - Used to identify the record field/attribute containing content for"," this column. Also used to create a default Model if no `recordType` or"," `data` are provided during construction. If `name` is not specified, this"," is assigned to the `_id` property (with added incrementer if the key is"," used by multiple columns)."," * `children` - Traversed to initialize nested column objects"," * `name` - Used in place of, or in addition to, the `key`. Useful for"," columns that aren't bound to a field/attribute in the record data. This"," is assigned to the `_id` property."," * `id` - For backward compatibility. Implementers can specify the id of"," the header cell. This should be avoided, if possible, to avoid the"," potential for creating DOM elements with duplicate IDs."," * `field` - For backward compatibility. Implementers should use `name`."," * `_id` - Assigned unique-within-this-instance id for a column. By order"," of preference, assumes the value of `name`, `key`, `id`, or `_yuid`."," This is used by the rendering views as well as feature module"," as a means to identify a specific column without ambiguity (such as"," multiple columns using the same `key`."," * `_yuid` - Guid stamp assigned to the column object."," * `_parent` - Assigned to all child columns, referencing their parent"," column.",""," @attribute columns"," @type {Object[]|String[]}"," @default (from `recordType` ATTRS or first item in the `data`)"," @since 3.5.0"," **/"," columns: {"," // TODO: change to setter to clone input array/objects"," validator: isArray,"," setter: '_setColumns',"," getter: '_getColumns'"," },",""," /**"," Model subclass to use as the `model` for the ModelList stored in the `data`"," attribute.",""," If not provided, it will try really hard to figure out what to use. The"," following attempts will be made to set a default value:",""," 1. If the `data` attribute is set with a ModelList instance and its `model`"," property is set, that will be used."," 2. If the `data` attribute is set with a ModelList instance, and its"," `model` property is unset, but it is populated, the `ATTRS` of the"," `constructor of the first item will be used."," 3. If the `data` attribute is set with a non-empty array, a Model subclass"," will be generated using the keys of the first item as its `ATTRS` (see"," the `_createRecordClass` method)."," 4. If the `columns` attribute is set, a Model subclass will be generated"," using the columns defined with a `key`. This is least desirable because"," columns can be duplicated or nested in a way that's not parsable."," 5. If neither `data` nor `columns` is set or populated, a change event"," subscriber will listen for the first to be changed and try all over"," again.",""," @attribute recordType"," @type {Function}"," @default (see description)"," @since 3.5.0"," **/"," recordType: {"," getter: '_getRecordType',"," setter: '_setRecordType'"," },",""," /**"," The collection of data records to display. This attribute is a pass"," through to a `data` property, which is a ModelList instance.",""," If this attribute is passed a ModelList or subclass, it will be assigned to"," the property directly. If an array of objects is passed, a new ModelList"," will be created using the configured `recordType` as its `model` property"," and seeded with the array.",""," Retrieving this attribute will return the ModelList stored in the `data`"," property.",""," @attribute data"," @type {ModelList|Object[]}"," @default `new ModelList()`"," @since 3.5.0"," **/"," data: {"," valueFn: '_initData',"," setter : '_setData',"," lazyAdd: false"," },",""," /**"," Content for the `<table summary=\"ATTRIBUTE VALUE HERE\">`. Values assigned"," to this attribute will be HTML escaped for security.",""," @attribute summary"," @type {String}"," @default '' (empty string)"," @since 3.5.0"," **/"," //summary: {},",""," /**"," HTML content of an optional `<caption>` element to appear above the table."," Leave this config unset or set to a falsy value to remove the caption.",""," @attribute caption"," @type HTML"," @default '' (empty string)"," @since 3.5.0"," **/"," //caption: {},",""," /**"," Deprecated as of 3.5.0. Passes through to the `data` attribute.",""," WARNING: `get('recordset')` will NOT return a Recordset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute recordset"," @type {Object[]|Recordset}"," @deprecated Use the `data` attribute"," @since 3.5.0"," **/"," recordset: {"," setter: '_setRecordset',"," getter: '_getRecordset',"," lazyAdd: false"," },",""," /**"," Deprecated as of 3.5.0. Passes through to the `columns` attribute.",""," WARNING: `get('columnset')` will NOT return a Columnset instance as of"," 3.5.0. This is a break in backward compatibility.",""," @attribute columnset"," @type {Object[]}"," @deprecated Use the `columns` attribute"," @since 3.5.0"," **/"," columnset: {"," setter: '_setColumnset',"," getter: '_getColumnset',"," lazyAdd: false"," }","};","","Y.mix(Table.prototype, {"," // -- Instance properties -------------------------------------------------"," /**"," The ModelList that manages the table's data.",""," @property data"," @type {ModelList}"," @default undefined (initially unset)"," @since 3.5.0"," **/"," //data: null,",""," // -- Public methods ------------------------------------------------------",""," /**"," Gets the column configuration object for the given key, name, or index. For"," nested columns, `name` can be an array of indexes, each identifying the index"," of that column in the respective parent's \"children\" array.",""," If you pass a column object, it will be returned.",""," For columns with keys, you can also fetch the column with"," `instance.get('columns.foo')`.",""," @method getColumn"," @param {String|Number|Number[]} name Key, \"name\", index, or index array to"," identify the column"," @return {Object} the column configuration object"," @since 3.5.0"," **/"," getColumn: function (name) {"," var col, columns, i, len, cols;",""," if (isObject(name) && !isArray(name)) {"," if (name && name._node) {"," col = this.body.getColumn(name);"," } else {"," col = name;"," }"," } else {"," col = this.get('columns.' + name);"," }",""," if (col) {"," return col;"," }",""," columns = this.get('columns');",""," if (isNumber(name) || isArray(name)) {"," name = toArray(name);"," cols = columns;",""," for (i = 0, len = name.length - 1; cols && i < len; ++i) {"," cols = cols[name[i]] && cols[name[i]].children;"," }",""," return (cols && cols[name[i]]) || null;"," }",""," return null;"," },",""," /**"," Returns the Model associated to the record `id`, `clientId`, or index (not"," row index). If none of those yield a Model from the `data` ModelList, the"," arguments will be passed to the `view` instance's `getRecord` method"," if it has one.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or"," identifier for a row or child element"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var record = this.data.getById(seed) || this.data.getByClientId(seed);",""," if (!record) {"," if (isNumber(seed)) {"," record = this.data.item(seed);"," }",""," // TODO: this should be split out to base somehow"," if (!record && this.view && this.view.getRecord) {"," record = this.view.getRecord.apply(this.view, arguments);"," }"," }",""," return record || null;"," },",""," // -- Protected and private properties and methods ------------------------",""," /**"," This tells `Y.Base` that it should create ad-hoc attributes for config"," properties passed to DataTable's constructor. This is useful for setting"," configurations on the DataTable that are intended for the rendering View(s).",""," @property _allowAdHocAttrs"," @type Boolean"," @default true"," @protected"," @since 3.6.0"," **/"," _allowAdHocAttrs: true,",""," /**"," A map of column key to column configuration objects parsed from the"," `columns` attribute.",""," @property _columnMap"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_columnMap: null,",""," /**"," The Node instance of the table containing the data rows. This is set when"," the table is rendered. It may also be set by progressive enhancement,"," though this extension does not provide the logic to parse from source.",""," @property _tableNode"," @type {Node}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_tableNode: null,",""," /**"," Updates the `_columnMap` property in response to changes in the `columns`"," attribute.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," _afterColumnsChange: function (e) {"," this._setColumnMap(e.newVal);"," },",""," /**"," Updates the `modelList` attributes of the rendered views in response to the"," `data` attribute being assigned a new ModelList.",""," @method _afterDataChange"," @param {EventFacade} e the `dataChange` event"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," var modelList = e.newVal;",""," this.data = e.newVal;",""," if (!this.get('columns') && modelList.size()) {"," // TODO: this will cause a re-render twice because the Views are"," // subscribed to columnsChange"," this._initColumns();"," }"," },",""," /**"," Assigns to the new recordType as the model for the data ModelList",""," @method _afterRecordTypeChange"," @param {EventFacade} e recordTypeChange event"," @protected"," @since 3.6.0"," **/"," _afterRecordTypeChange: function (e) {"," var data = this.data.toJSON();",""," this.data.model = e.newVal;",""," this.data.reset(data);",""," if (!this.get('columns') && data) {"," if (data.length) {"," this._initColumns();"," } else {"," this.set('columns', keys(e.newVal.ATTRS));"," }"," }"," },",""," /**"," Creates a Model subclass from an array of attribute names or an object of"," attribute definitions. This is used to generate a class suitable to"," represent the data passed to the `data` attribute if no `recordType` is"," set.",""," @method _createRecordClass"," @param {String[]|Object} attrs Names assigned to the Model subclass's"," `ATTRS` or its entire `ATTRS` definition object"," @return {Model}"," @protected"," @since 3.5.0"," **/"," _createRecordClass: function (attrs) {"," var ATTRS, i, len;",""," if (isArray(attrs)) {"," ATTRS = {};",""," for (i = 0, len = attrs.length; i < len; ++i) {"," ATTRS[attrs[i]] = {};"," }"," } else if (isObject(attrs)) {"," ATTRS = attrs;"," }",""," return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS });"," },",""," /**"," Tears down the instance.",""," @method destructor"," @protected"," @since 3.6.0"," **/"," destructor: function () {"," new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();"," },",""," /**"," The getter for the `columns` attribute. Returns the array of column"," configuration objects if `instance.get('columns')` is called, or the"," specific column object if `instance.get('columns.columnKey')` is called.",""," @method _getColumns"," @param {Object[]} columns The full array of column objects"," @param {String} name The attribute name requested"," (e.g. 'columns' or 'columns.foo');"," @protected"," @since 3.5.0"," **/"," _getColumns: function (columns, name) {"," // Workaround for an attribute oddity (ticket #2529254)"," // getter is expected to return an object if get('columns.foo') is called."," // Note 'columns.' is 8 characters"," return name.length > 8 ? this._columnMap : columns;"," },",""," /**"," Relays the `get()` request for the deprecated `columnset` attribute to the"," `columns` attribute.",""," THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will"," expect a Columnset instance returned from `get('columnset')`.",""," @method _getColumnset"," @param {Object} ignored The current value stored in the `columnset` state"," @param {String} name The attribute name requested"," (e.g. 'columnset' or 'columnset.foo');"," @deprecated This will be removed with the `columnset` attribute in a future"," version."," @protected"," @since 3.5.0"," **/"," _getColumnset: function (_, name) {"," return this.get(name.replace(/^columnset/, 'columns'));"," },",""," /**"," Returns the Model class of the instance's `data` attribute ModelList. If"," not set, returns the explicitly configured value.",""," @method _getRecordType"," @param {Model} val The currently configured value"," @return {Model}"," **/"," _getRecordType: function (val) {"," // Prefer the value stored in the attribute because the attribute"," // change event defaultFn sets e.newVal = this.get('recordType')"," // before notifying the after() subs. But if this getter returns"," // this.data.model, then after() subs would get e.newVal === previous"," // model before _afterRecordTypeChange can set"," // this.data.model = e.newVal"," return val || (this.data && this.data.model);"," },",""," /**"," Initializes the `_columnMap` property from the configured `columns`"," attribute. If `columns` is not set, but there are records in the `data`"," ModelList, use"," `ATTRS` of that class.",""," @method _initColumns"," @protected"," @since 3.5.0"," **/"," _initColumns: function () {"," var columns = this.get('columns') || [],"," item;",""," // Default column definition from the configured recordType"," if (!columns.length && this.data.size()) {"," // TODO: merge superclass attributes up to Model?"," item = this.data.item(0);",""," if (item.toJSON) {"," item = item.toJSON();"," }",""," this.set('columns', keys(item));"," }",""," this._setColumnMap(columns);"," },",""," /**"," Sets up the change event subscriptions to maintain internal state.",""," @method _initCoreEvents"," @protected"," @since 3.6.0"," **/"," _initCoreEvents: function () {"," this._eventHandles.coreAttrChanges = this.after({"," columnsChange : Y.bind('_afterColumnsChange', this),"," recordTypeChange: Y.bind('_afterRecordTypeChange', this),"," dataChange : Y.bind('_afterDataChange', this)"," });"," },",""," /**"," Defaults the `data` attribute to an empty ModelList if not set during"," construction. Uses the configured `recordType` for the ModelList's `model`"," proeprty if set.",""," @method _initData"," @protected"," @return {ModelList}"," @since 3.6.0"," **/"," _initData: function () {"," var recordType = this.get('recordType'),"," // TODO: LazyModelList if recordType doesn't have complex ATTRS"," modelList = new Y.ModelList();",""," if (recordType) {"," modelList.model = recordType;"," }",""," return modelList;"," },",""," /**"," Initializes the instance's `data` property from the value of the `data`"," attribute. If the attribute value is a ModelList, it is assigned directly"," to `this.data`. If it is an array, a ModelList is created, its `model`"," property is set to the configured `recordType` class, and it is seeded with"," the array data. This ModelList is then assigned to `this.data`.",""," @method _initDataProperty"," @param {Array|ModelList|ArrayList} data Collection of data to populate the"," DataTable"," @protected"," @since 3.6.0"," **/"," _initDataProperty: function (data) {"," var recordType;",""," if (!this.data) {"," recordType = this.get('recordType');",""," if (data && data.each && data.toJSON) {"," this.data = data;",""," if (recordType) {"," this.data.model = recordType;"," }"," } else {"," // TODO: customize the ModelList or read the ModelList class"," // from a configuration option?"," this.data = new Y.ModelList();",""," if (recordType) {"," this.data.model = recordType;"," }"," }",""," // TODO: Replace this with an event relay for specific events."," // Using bubbling causes subscription conflicts with the models'"," // aggregated change event and 'change' events from DOM elements"," // inside the table (via Widget UI event)."," this.data.addTarget(this);"," }"," },",""," /**"," Initializes the columns, `recordType` and data ModelList.",""," @method initializer"," @param {Object} config Configuration object passed to constructor"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," var data = config.data,"," columns = config.columns,"," recordType;",""," // Referencing config.data to allow _setData to be more stringent"," // about its behavior"," this._initDataProperty(data);",""," // Default columns from recordType ATTRS if recordType is supplied at"," // construction. If no recordType is supplied, but the data is"," // supplied as a non-empty array, use the keys of the first item"," // as the columns."," if (!columns) {"," recordType = (config.recordType || config.data === this.data) &&"," this.get('recordType');",""," if (recordType) {"," columns = keys(recordType.ATTRS);"," } else if (isArray(data) && data.length) {"," columns = keys(data[0]);"," }",""," if (columns) {"," this.set('columns', columns);"," }"," }",""," this._initColumns();",""," this._eventHandles = {};",""," this._initCoreEvents();"," },",""," /**"," Iterates the array of column configurations to capture all columns with a"," `key` property. An map is built with column keys as the property name and"," the corresponding column object as the associated value. This map is then"," assigned to the instance's `_columnMap` property.",""," @method _setColumnMap"," @param {Object[]|String[]} columns The array of column config objects"," @protected"," @since 3.6.0"," **/"," _setColumnMap: function (columns) {"," var map = {};",""," function process(cols) {"," var i, len, col, key;",""," for (i = 0, len = cols.length; i < len; ++i) {"," col = cols[i];"," key = col.key;",""," // First in wins for multiple columns with the same key"," // because the first call to genId (in _setColumns) will"," // return the same key, which will then be overwritten by the"," // subsequent same-keyed column. So table.getColumn(key) would"," // return the last same-keyed column."," if (key && !map[key]) {"," map[key] = col;"," }"," //TODO: named columns can conflict with keyed columns"," map[col._id] = col;",""," if (col.children) {"," process(col.children);"," }"," }"," }",""," process(columns);",""," this._columnMap = map;"," },",""," /**"," Translates string columns into objects with that string as the value of its"," `key` property.",""," All columns are assigned a `_yuid` stamp and `_id` property corresponding"," to the column's configured `name` or `key` property with any spaces"," replaced with dashes. If the same `name` or `key` appears in multiple"," columns, subsequent appearances will have their `_id` appended with an"," incrementing number (e.g. if column \"foo\" is included in the `columns`"," attribute twice, the first will get `_id` of \"foo\", and the second an `_id`"," of \"foo1\"). Columns that are children of other columns will have the"," `_parent` property added, assigned the column object to which they belong.",""," @method _setColumns"," @param {null|Object[]|String[]} val Array of config objects or strings"," @return {null|Object[]}"," @protected"," **/"," _setColumns: function (val) {"," var keys = {},"," known = [],"," knownCopies = [],"," arrayIndex = Y.Array.indexOf;",""," function copyObj(o) {"," var copy = {},"," key, val, i;",""," known.push(o);"," knownCopies.push(copy);",""," for (key in o) {"," if (o.hasOwnProperty(key)) {"," val = o[key];",""," if (isArray(val)) {"," copy[key] = val.slice();"," } else if (isObject(val, true)) {"," i = arrayIndex(known, val);",""," copy[key] = i === -1 ? copyObj(val) : knownCopies[i];"," } else {"," copy[key] = o[key];"," }"," }"," }",""," return copy;"," }",""," function genId(name) {"," // Sanitize the name for use in generated CSS classes."," // TODO: is there more to do for other uses of _id?"," name = name.replace(/\\s+/, '-');",""," if (keys[name]) {"," name += (keys[name]++);"," } else {"," keys[name] = 1;"," }",""," return name;"," }",""," function process(cols, parent) {"," var columns = [],"," i, len, col, yuid;",""," for (i = 0, len = cols.length; i < len; ++i) {"," columns[i] = // chained assignment"," col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]);",""," yuid = Y.stamp(col);",""," // For backward compatibility"," if (!col.id) {"," // Implementers can shoot themselves in the foot by setting"," // this config property to a non-unique value"," col.id = yuid;"," }"," if (col.field) {"," // Field is now known as \"name\" to avoid confusion with data"," // fields or schema.resultFields"," col.name = col.field;"," }",""," if (parent) {"," col._parent = parent;"," } else {"," delete col._parent;"," }",""," // Unique id based on the column's configured name or key,"," // falling back to the yuid. Duplicates will have a counter"," // added to the end."," col._id = genId(col.name || col.key || col.id);",""," if (isArray(col.children)) {"," col.children = process(col.children, col);"," }"," }",""," return columns;"," }",""," return val && process(val);"," },",""," /**"," Relays attribute assignments of the deprecated `columnset` attribute to the"," `columns` attribute. If a Columnset is object is passed, its basic object"," structure is mined.",""," @method _setColumnset"," @param {Array|Columnset} val The columnset value to relay"," @deprecated This will be removed with the deprecated `columnset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setColumnset: function (val) {"," this.set('columns', val);",""," return isArray(val) ? val : INVALID;"," },",""," /**"," Accepts an object with `each` and `getAttrs` (preferably a ModelList or"," subclass) or an array of data objects. If an array is passes, it will"," create a ModelList to wrap the data. In doing so, it will set the created"," ModelList's `model` property to the class in the `recordType` attribute,"," which will be defaulted if not yet set.",""," If the `data` property is already set with a ModelList, passing an array as"," the value will call the ModelList's `reset()` method with that array rather"," than replacing the stored ModelList wholesale.",""," Any non-ModelList-ish and non-array value is invalid.",""," @method _setData"," @protected"," @since 3.5.0"," **/"," _setData: function (val) {"," if (val === null) {"," val = [];"," }",""," if (isArray(val)) {"," this._initDataProperty();",""," // silent to prevent subscribers to both reset and dataChange"," // from reacting to the change twice."," // TODO: would it be better to return INVALID to silence the"," // dataChange event, or even allow both events?"," this.data.reset(val, { silent: true });",""," // Return the instance ModelList to avoid storing unprocessed"," // data in the state and their vivified Model representations in"," // the instance's data property. Decreases memory consumption."," val = this.data;"," } else if (!val || !val.each || !val.toJSON) {"," // ModelList/ArrayList duck typing"," val = INVALID;"," }",""," return val;"," },",""," /**"," Relays the value assigned to the deprecated `recordset` attribute to the"," `data` attribute. If a Recordset instance is passed, the raw object data"," will be culled from it.",""," @method _setRecordset"," @param {Object[]|Recordset} val The recordset value to relay"," @deprecated This will be removed with the deprecated `recordset` attribute"," in a later version."," @protected"," @since 3.5.0"," **/"," _setRecordset: function (val) {"," var data;",""," if (val && Y.Recordset && val instanceof Y.Recordset) {"," data = [];"," val.each(function (record) {"," data.push(record.get('data'));"," });"," val = data;"," }",""," this.set('data', val);",""," return val;"," },",""," /**"," Accepts a Base subclass (preferably a Model subclass). Alternately, it will"," generate a custom Model subclass from an array of attribute names or an"," object defining attributes and their respective configurations (it is"," assigned as the `ATTRS` of the new class).",""," Any other value is invalid.",""," @method _setRecordType"," @param {Function|String[]|Object} val The Model subclass, array of"," attribute names, or the `ATTRS` definition for a custom model"," subclass"," @return {Function} A Base/Model subclass"," @protected"," @since 3.5.0"," **/"," _setRecordType: function (val) {"," var modelClass;",""," // Duck type based on known/likely consumed APIs"," if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) {"," modelClass = val;"," } else if (isObject(val)) {"," modelClass = this._createRecordClass(val);"," }",""," return modelClass || INVALID;"," }","","});","","","","/**","_This is a documentation entry only_","","Columns are described by object literals with a set of properties.","There is not an actual `DataTable.Column` class.","However, for the purpose of documenting it, this pseudo-class is declared here.","","DataTables accept an array of column definitions in their [columns](DataTable.html#attr_columns)","attribute. Each entry in this array is a column definition which may contain","any combination of the properties listed below.","","There are no mandatory properties though a column will usually have a","[key](#property_key) property to reference the data it is supposed to show.","The [columns](DataTable.html#attr_columns) attribute can accept a plain string","in lieu of an object literal, which is the equivalent of an object with the","[key](#property_key) property set to that string.","","@class DataTable.Column","*/","","/**","Binds the column values to the named property in the [data](DataTable.html#attr_data).","","Optional if [formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","or [cellTemplate](#property_cellTemplate) is used to populate the content.","","It should not be set if [children](#property_children) is set.","","The value is used for the [\\_id](#property__id) property unless the [name](#property_name)","property is also set.",""," { key: 'username' }","","The above column definition can be reduced to this:",""," 'username'","","@property key","@type String"," */","/**","An identifier that can be used to locate a column via","[getColumn](DataTable.html#method_getColumn)","or style columns with class `yui3-datatable-col-NAME` after dropping characters","that are not valid for CSS class names.","","It defaults to the [key](#property_key).","","The value is used for the [\\_id](#property__id) property.",""," { name: 'fullname', formatter: ... }","","@property name","@type String","*/","/**","An alias for [name](#property_name) for backward compatibility.",""," { field: 'fullname', formatter: ... }","","@property field","@type String","*/","/**","Overrides the default unique id assigned `<th id=\"HERE\">`.","","__Use this with caution__, since it can result in","duplicate ids in the DOM.",""," {"," name: 'checkAll',"," id: 'check-all',"," label: ..."," formatter: ..."," }","","@property id","@type String"," */","/**","HTML to populate the header `<th>` for the column.","It defaults to the value of the [key](#property_key) property or the text","`Column n` where _n_ is an ordinal number.",""," { key: 'MfgvaPrtNum', label: 'Part Number' }","","@property label","@type {String}"," */","/**","Used to create stacked headers.","","Child columns may also contain `children`. There is no limit","to the depth of nesting.","","Columns configured with `children` are for display only and","<strong>should not</strong> be configured with a [key](#property_key).","Configurations relating to the display of data, such as","[formatter](#property_formatter), [nodeFormatter](#property_nodeFormatter),","[emptyCellValue](#property_emptyCellValue), etc. are ignored.",""," { label: 'Name', children: ["," { key: 'firstName', label: 'First`},"," { key: 'lastName', label: 'Last`}"," ]}","","@property children","@type Array","*/","/**","Assigns the value `<th abbr=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," abbr : 'Forecast'"," }","","@property abbr","@type String"," */","/**","Assigns the value `<th title=\"HERE\">`.",""," {"," key : 'forecast',"," label: '1yr Target Forecast',"," title: 'Target Forecast for the Next 12 Months'"," }","","@property title","@type String"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.HeaderView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.HeaderView` to render the header cell","for this column. This is necessary when more control is","needed over the markup for the header itself, rather than","its content.","","Use the [label](#property_label) configuration if you don't need to","customize the `<th>` iteself.","","Implementers are strongly encouraged to preserve at least","the `{id}` and `{_id}` placeholders in the custom value.",""," {"," headerTemplate:"," '<th id=\"{id}\" ' +"," 'title=\"Unread\" ' +"," 'class=\"{className}\" ' +"," '{_id}>●</th>'"," }","","@property headerTemplate","@type HTML"," */","/**","Overrides the default [CELL_TEMPLATE](DataTable.BodyView.html#property_CELL_TEMPLATE)","used by `Y.DataTable.BodyView` to render the data cells","for this column. This is necessary when more control is","needed over the markup for the `<td>` itself, rather than","its content.",""," {"," key: 'id',"," cellTemplate:"," '<td class=\"{className}\">' +"," '<input type=\"checkbox\" ' +"," 'id=\"{content}\">' +"," '</td>'"," }","","","@property cellTemplate","@type String"," */","/**","String or function used to translate the raw record data for each cell in a","given column into a format better suited to display.","","If it is a string, it will initially be assumed to be the name of one of the","formatting functions in","[Y.DataTable.BodyView.Formatters](DataTable.BodyView.Formatters.html).","If one such formatting function exists, it will be used.","","If no such named formatter is found, it will be assumed to be a template","string and will be expanded. The placeholders can contain the key to any","field in the record or the placeholder `{value}` which represents the value","of the current field.","","If the value is a function, it will be assumed to be a formatting function.","A formatting function receives a single argument, an object with the following properties:","","* __value__ The raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__ The Model data for this row in simple object format.","* __record__ The Model for this row.","* __column__ The column configuration object.","* __className__ A string of class names to add `<td class=\"HERE\">` in addition to"," the column class and any classes in the column's className configuration.","* __rowIndex__ The index of the current Model in the ModelList."," Typically correlates to the row index as well.","* __rowClass__ A string of css classes to add `<tr class=\"HERE\"><td....`"," This is useful to avoid the need for nodeFormatters to add classes to the containing row.","","The formatter function may return a string value that will be used for the cell","contents or it may change the value of the `value`, `className` or `rowClass`","properties which well then be used to format the cell. If the value for the cell","is returned in the `value` property of the input argument, no value should be returned.",""," {"," key: 'name',"," formatter: 'link', // named formatter"," linkFrom: 'website' // extra column property for link formatter"," },"," {"," key: 'cost',"," formatter: '${value}' // formatter template string"," //formatter: '${cost}' // same result but less portable"," },"," {"," name: 'Name', // column does not have associated field value"," // thus, it uses name instead of key"," formatter: '{firstName} {lastName}' // template references other fields"," },"," {"," key: 'price',"," formatter: function (o) { // function both returns a string to show"," if (o.value > 3) { // and a className to apply to the cell"," o.className += 'expensive';"," }",""," return '$' + o.value.toFixed(2);"," }"," },","@property formatter","@type String || Function","","*/","/**","Used to customize the content of the data cells for this column.","","`nodeFormatter` is significantly slower than [formatter](#property_formatter)","and should be avoided if possible. Unlike [formatter](#property_formatter),","`nodeFormatter` has access to the `<td>` element and its ancestors.","","The function provided is expected to fill in the `<td>` element itself.","__Node formatters should return `false`__ except in certain conditions as described","in the users guide.","","The function receives a single object","argument with the following properties:","","* __td__\tThe `<td>` Node for this cell.","* __cell__\tIf the cell `<td> contains an element with class `yui3-datatable-liner,"," this will refer to that Node. Otherwise, it is equivalent to `td` (default behavior).","* __value__\tThe raw value from the record Model to populate this cell."," Equivalent to `o.record.get(o.column.key)` or `o.data[o.column.key]`.","* __data__\tThe Model data for this row in simple object format.","* __record__\tThe Model for this row.","* __column__\tThe column configuration object.","* __rowIndex__\tThe index of the current Model in the ModelList."," _Typically_ correlates to the row index as well.","","@example"," nodeFormatter: function (o) {"," if (o.value < o.data.quota) {"," o.td.setAttribute('rowspan', 2);"," o.td.setAttribute('data-term-id', this.record.get('id'));",""," o.td.ancestor().insert("," '<tr><td colspan\"3\">' +"," '<button class=\"term\">terminate</button>' +"," '</td></tr>',"," 'after');"," }",""," o.cell.setHTML(o.value);"," return false;"," }","","@property nodeFormatter","@type Function","*/","/**","Provides the default value to populate the cell if the data","for that cell is `undefined`, `null`, or an empty string.",""," {"," key: 'price',"," emptyCellValue: '???'"," }","","@property emptyCellValue","@type {String} depending on the setting of allowHTML"," */","/**","Skips the security step of HTML escaping the value for cells","in this column.","","This is also necessary if [emptyCellValue](#property_emptyCellValue)","is set with an HTML string.","`nodeFormatter`s ignore this configuration. If using a","`nodeFormatter`, it is recommended to use","[Y.Escape.html()](Escape.html#method_html)","on any user supplied content that is to be displayed.",""," {"," key: 'preview',"," allowHTML: true"," }","","@property allowHTML","@type Boolean","*/","/**","A string of CSS classes that will be added to the `<td>`'s","`class` attribute.","","Note, all cells will automatically have a class in the","form of \"yui3-datatable-col-XXX\" added to the `<td>`, where","XXX is the column's configured `name`, `key`, or `id` (in","that order of preference) sanitized from invalid characters.",""," {"," key: 'symbol',"," className: 'no-hide'"," }","","@property className","@type String","*/","/**","(__read-only__) The unique identifier assigned","to each column. This is used for the `id` if not set, and","the `_id` if none of [name](#property_name),","[field](#property_field), [key](#property_key), or [id](#property_id) are","set.","","@property _yuid","@type String","@protected"," */","/**","(__read-only__) A unique-to-this-instance name","used extensively in the rendering process. It is also used","to create the column's classname, as the input name","`table.getColumn(HERE)`, and in the column header's","`<th data-yui3-col-id=\"HERE\">`.","","The value is populated by the first of [name](#property_name),","[field](#property_field), [key](#property_key), [id](#property_id),"," or [_yuid](#property__yuid) to have a value. If that value","has already been used (such as when multiple columns have","the same `key`), an incrementer is added to the end. For","example, two columns with `key: \"id\"` will have `_id`s of","\"id\" and \"id2\". `table.getColumn(\"id\")` will return the","first column, and `table.getColumn(\"id2\")` will return the","second.","","@property _id","@type String","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _colspan","@type Integer","@protected"," */","/**","(__read-only__) Used by","`Y.DataTable.HeaderView` when building stacked column","headers.","","@property _rowspan","@type Integer","@protected"," */","/**","(__read-only__) Assigned to all columns in a","column's `children` collection. References the parent","column object.","","@property _parent","@type DataTable.Column","@protected"," */","/**","(__read-only__) Array of the `id`s of the","column and all parent columns. Used by","`Y.DataTable.BodyView` to populate `<td headers=\"THIS\">`","when a cell references more than one header.","","@property _headers","@type Array","@protected","*/","","","}, '3.16.0', {\"requires\": [\"escape\", \"model-list\", \"node-event-delegate\"]});","","}());"]};
}
var __cov_adU3eEuYYFqBLZ6_IZplXQ = __coverage__['build/datatable-core/datatable-core.js'];
__cov_adU3eEuYYFqBLZ6_IZplXQ.s['1']++;YUI.add('datatable-core',function(Y,NAME){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['1']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['2']++;var INVALID=Y.Attribute.INVALID_VALUE,Lang=Y.Lang,isFunction=Lang.isFunction,isObject=Lang.isObject,isArray=Lang.isArray,isString=Lang.isString,isNumber=Lang.isNumber,toArray=Y.Array,keys=Y.Object.keys,Table;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['3']++;Table=Y.namespace('DataTable').Core=function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['2']++;};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['4']++;Table.ATTRS={columns:{validator:isArray,setter:'_setColumns',getter:'_getColumns'},recordType:{getter:'_getRecordType',setter:'_setRecordType'},data:{valueFn:'_initData',setter:'_setData',lazyAdd:false},recordset:{setter:'_setRecordset',getter:'_getRecordset',lazyAdd:false},columnset:{setter:'_setColumnset',getter:'_getColumnset',lazyAdd:false}};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['5']++;Y.mix(Table.prototype,{getColumn:function(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['3']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['6']++;var col,columns,i,len,cols;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['7']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][0]++,isObject(name))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['2'][1]++,!isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['8']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][0]++,name)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['4'][1]++,name._node)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['9']++;col=this.body.getColumn(name);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['3'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['10']++;col=name;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['1'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['11']++;col=this.get('columns.'+name);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['12']++;if(col){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['13']++;return col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['5'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['14']++;columns=this.get('columns');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['15']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][0]++,isNumber(name))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['7'][1]++,isArray(name))){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['16']++;name=toArray(name);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['17']++;cols=columns;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['18']++;for(i=0,len=name.length-1;(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['8'][1]++,i<len);++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['19']++;cols=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][0]++,cols[name[i]])&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['9'][1]++,cols[name[i]].children);}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['20']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][0]++,cols)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][1]++,cols[name[i]])||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['10'][2]++,null);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['6'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['21']++;return null;},getRecord:function(seed){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['4']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['22']++;var record=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][0]++,this.data.getById(seed))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['11'][1]++,this.data.getByClientId(seed));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['23']++;if(!record){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['24']++;if(isNumber(seed)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['25']++;record=this.data.item(seed);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['13'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['26']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][0]++,!record)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][1]++,this.view)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['15'][2]++,this.view.getRecord)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['27']++;record=this.view.getRecord.apply(this.view,arguments);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['14'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['12'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['28']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][0]++,record)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['16'][1]++,null);},_allowAdHocAttrs:true,_afterColumnsChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['5']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['29']++;this._setColumnMap(e.newVal);},_afterDataChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['6']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['30']++;var modelList=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['31']++;this.data=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['32']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['18'][1]++,modelList.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['33']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['17'][1]++;}},_afterRecordTypeChange:function(e){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['7']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['34']++;var data=this.data.toJSON();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['35']++;this.data.model=e.newVal;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['36']++;this.data.reset(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['37']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][0]++,!this.get('columns'))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['20'][1]++,data)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['38']++;if(data.length){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['39']++;this._initColumns();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['21'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['40']++;this.set('columns',keys(e.newVal.ATTRS));}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['19'][1]++;}},_createRecordClass:function(attrs){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['8']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['41']++;var ATTRS,i,len;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['42']++;if(isArray(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['43']++;ATTRS={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['44']++;for(i=0,len=attrs.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['45']++;ATTRS[attrs[i]]={};}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['22'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['46']++;if(isObject(attrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['47']++;ATTRS=attrs;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['23'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['48']++;return Y.Base.create('record',Y.Model,[],null,{ATTRS:ATTRS});},destructor:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['9']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['49']++;new Y.EventHandle(Y.Object.values(this._eventHandles)).detach();},_getColumns:function(columns,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['10']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['50']++;return name.length>8?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][0]++,this._columnMap):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['24'][1]++,columns);},_getColumnset:function(_,name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['11']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['51']++;return this.get(name.replace(/^columnset/,'columns'));},_getRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['12']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['52']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][0]++,val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][1]++,this.data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['25'][2]++,this.data.model);},_initColumns:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['13']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['53']++;var columns=(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][0]++,this.get('columns'))||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['26'][1]++,[]),item;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['54']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][0]++,!columns.length)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['28'][1]++,this.data.size())){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['55']++;item=this.data.item(0);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['56']++;if(item.toJSON){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['57']++;item=item.toJSON();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['29'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['58']++;this.set('columns',keys(item));}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['27'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['59']++;this._setColumnMap(columns);},_initCoreEvents:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['14']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['60']++;this._eventHandles.coreAttrChanges=this.after({columnsChange:Y.bind('_afterColumnsChange',this),recordTypeChange:Y.bind('_afterRecordTypeChange',this),dataChange:Y.bind('_afterDataChange',this)});},_initData:function(){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['15']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['61']++;var recordType=this.get('recordType'),modelList=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['62']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['63']++;modelList.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['30'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['64']++;return modelList;},_initDataProperty:function(data){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['16']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['65']++;var recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['66']++;if(!this.data){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['67']++;recordType=this.get('recordType');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['68']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][0]++,data)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][1]++,data.each)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['33'][2]++,data.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['69']++;this.data=data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['70']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['71']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['34'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['32'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['72']++;this.data=new Y.ModelList();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['73']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['74']++;this.data.model=recordType;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['35'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['75']++;this.data.addTarget(this);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['31'][1]++;}},initializer:function(config){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['17']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['76']++;var data=config.data,columns=config.columns,recordType;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['77']++;this._initDataProperty(data);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['78']++;if(!columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['79']++;recordType=((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][0]++,config.recordType)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][1]++,config.data===this.data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['37'][2]++,this.get('recordType'));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['80']++;if(recordType){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['81']++;columns=keys(recordType.ATTRS);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['38'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['82']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][0]++,isArray(data))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['40'][1]++,data.length)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['83']++;columns=keys(data[0]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['39'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['84']++;if(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['85']++;this.set('columns',columns);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['41'][1]++;}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['36'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['86']++;this._initColumns();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['87']++;this._eventHandles={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['88']++;this._initCoreEvents();},_setColumnMap:function(columns){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['18']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['89']++;var map={};__cov_adU3eEuYYFqBLZ6_IZplXQ.s['90']++;function process(cols){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['19']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['91']++;var i,len,col,key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['92']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['93']++;col=cols[i];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['94']++;key=col.key;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['95']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][0]++,key)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['43'][1]++,!map[key])){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['96']++;map[key]=col;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['42'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['97']++;map[col._id]=col;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['98']++;if(col.children){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['99']++;process(col.children);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['44'][1]++;}}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['100']++;process(columns);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['101']++;this._columnMap=map;},_setColumns:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['20']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['102']++;var keys={},known=[],knownCopies=[],arrayIndex=Y.Array.indexOf;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['103']++;function copyObj(o){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['21']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['104']++;var copy={},key,val,i;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['105']++;known.push(o);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['106']++;knownCopies.push(copy);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['107']++;for(key in o){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['108']++;if(o.hasOwnProperty(key)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['109']++;val=o[key];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['110']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['111']++;copy[key]=val.slice();}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['46'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['112']++;if(isObject(val,true)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['113']++;i=arrayIndex(known,val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['114']++;copy[key]=i===-1?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][0]++,copyObj(val)):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['48'][1]++,knownCopies[i]);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['47'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['115']++;copy[key]=o[key];}}}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['45'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['116']++;return copy;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['117']++;function genId(name){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['22']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['118']++;name=name.replace(/\s+/,'-');__cov_adU3eEuYYFqBLZ6_IZplXQ.s['119']++;if(keys[name]){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['120']++;name+=keys[name]++;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['49'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['121']++;keys[name]=1;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['122']++;return name;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['123']++;function process(cols,parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['23']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['124']++;var columns=[],i,len,col,yuid;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['125']++;for(i=0,len=cols.length;i<len;++i){__cov_adU3eEuYYFqBLZ6_IZplXQ.s['126']++;columns[i]=col=isString(cols[i])?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][0]++,{key:cols[i]}):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['50'][1]++,copyObj(cols[i]));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['127']++;yuid=Y.stamp(col);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['128']++;if(!col.id){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['129']++;col.id=yuid;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['51'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['130']++;if(col.field){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['131']++;col.name=col.field;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['52'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['132']++;if(parent){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['133']++;col._parent=parent;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['53'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['134']++;delete col._parent;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['135']++;col._id=genId((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][0]++,col.name)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][1]++,col.key)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['54'][2]++,col.id));__cov_adU3eEuYYFqBLZ6_IZplXQ.s['136']++;if(isArray(col.children)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['137']++;col.children=process(col.children,col);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['55'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['138']++;return columns;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['139']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['56'][1]++,process(val));},_setColumnset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['24']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['140']++;this.set('columns',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['141']++;return isArray(val)?(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][0]++,val):(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['57'][1]++,INVALID);},_setData:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['25']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['142']++;if(val===null){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['143']++;val=[];}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['58'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['144']++;if(isArray(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['145']++;this._initDataProperty();__cov_adU3eEuYYFqBLZ6_IZplXQ.s['146']++;this.data.reset(val,{silent:true});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['147']++;val=this.data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['59'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['148']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][0]++,!val)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][1]++,!val.each)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['61'][2]++,!val.toJSON)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['149']++;val=INVALID;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['60'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['150']++;return val;},_setRecordset:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['26']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['151']++;var data;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['152']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][0]++,val)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][1]++,Y.Recordset)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['63'][2]++,val instanceof Y.Recordset)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['153']++;data=[];__cov_adU3eEuYYFqBLZ6_IZplXQ.s['154']++;val.each(function(record){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['27']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['155']++;data.push(record.get('data'));});__cov_adU3eEuYYFqBLZ6_IZplXQ.s['156']++;val=data;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['62'][1]++;}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['157']++;this.set('data',val);__cov_adU3eEuYYFqBLZ6_IZplXQ.s['158']++;return val;},_setRecordType:function(val){__cov_adU3eEuYYFqBLZ6_IZplXQ.f['28']++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['159']++;var modelClass;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['160']++;if((__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][0]++,isFunction(val))&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][1]++,val.prototype.toJSON)&&(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['65'][2]++,val.prototype.setAttrs)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['161']++;modelClass=val;}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['64'][1]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['162']++;if(isObject(val)){__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][0]++;__cov_adU3eEuYYFqBLZ6_IZplXQ.s['163']++;modelClass=this._createRecordClass(val);}else{__cov_adU3eEuYYFqBLZ6_IZplXQ.b['66'][1]++;}}__cov_adU3eEuYYFqBLZ6_IZplXQ.s['164']++;return(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['67'][0]++,modelClass)||(__cov_adU3eEuYYFqBLZ6_IZplXQ.b['67'][1]++,INVALID);}});},'3.16.0',{'requires':['escape','model-list','node-event-delegate']});
|
src/index.js | tabazevedo/styletron-connect | import React from 'react';
import PropTypes from 'prop-types';
import { getStylesProp } from './internals';
const connectStyles = (Component, styles, key = 'styles') => {
const StyledElement = (props, { styletron }) => {
return React.createElement(Component, {
...props,
[key]: getStylesProp(styles, styletron, props),
});
};
if (Component.displayName || Component.name)
StyledElement.displayName = `Styled:${Component.displayName ||
Component.name}`;
StyledElement.contextTypes = {
styletron: PropTypes.object.isRequired,
};
return StyledElement;
};
export default connectStyles;
|
src/svg-icons/image/looks-one.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooksOne = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14h-2V9h-2V7h4v10z"/>
</SvgIcon>
);
ImageLooksOne = pure(ImageLooksOne);
ImageLooksOne.displayName = 'ImageLooksOne';
export default ImageLooksOne;
|
app/components/about/Team.js | jendela/jendela | import React from 'react'
import Title from '../template/Title'
import Colors from '../../constants/JendelaColors'
import Youtube from '../template/Youtube'
import Author from './Author'
const authors = [
{
avatar: "alsa.png",
name: "Alsasian Atmopawiro",
title: "Software Engineer",
location: "Paris, Perancis",
twitter: "alsa",
linkedin: "https://id.linkedin.com/in/alsasian"
},
{
avatar: "cyndy.png",
name: "Cyndy Messah",
title: "Visual Designer",
location: "Singapura",
twitter: "cyndymessah",
linkedin: "https://sg.linkedin.com/in/cyndymessah"
},
{
avatar: "ikhsan.png",
name: "Ikhsan Assaat",
title: "Software Engineer",
location: "London, Inggris",
twitter: "ixnixnixn",
linkedin: "https://uk.linkedin.com/in/ikhsanassaat"
},
{
avatar: "yoel.png",
name: "Yoel Sumitro",
title: "UX Designer",
location: "Nuremberg, Jerman",
twitter: "yoel_krisnanda",
linkedin: "https://de.linkedin.com/in/yoelsumitro"
},
]
class AuthorSection extends React.Component {
render() {
return (
<section className="row">
<div className="small-12 columns">
<h3 style={{color: "#368baf", marginBottom: "1em"}}>Tim Jendela</h3>
</div>
{authors.map((author, idx) => {
return (
<div className="small-6 medium-6 large-3 columns" key={idx}>
<Author
avatar={author.avatar}
name={author.name}
title={author.title}
location={author.location}
twitter={author.twitter}
linkedin={author.linkedin} />
</div>
)
})}
</section>
)
}
}
class Team extends React.Component {
render() {
return (
<div className="row">
<div className="small-12 columns">
<Title
iconPath="img/icon-jendela-info.png"
text="Tentang Jendela"
color="#2d4771" />
<div className="row" style={{marginTop: '1em', marginBottom: '1em'}}>
<div className="large-12 columns">
<img src="img/jendela-banner.png" />
</div>
</div>
<div className="row">
<div className="large-12 columns">
<h5 style={{color: "#368baf"}}>Jendela adalah sebuah inisiatif untuk meningkatkan transparansi pelayanan publik dan melawan praktek suap dengan cara mengajak partisipasi masyarakat untuk menceritakan pengalaman mereka di portal ini.</h5>
<p>Setiap orang bisa memberikan penilaian dan ulasan atas layanan publik yang diterimanya seperti proses pembuatan KTP, Kartu Keluarga, SIM, dll. Bahkan, masyarakat juga bisa melaporkan praktek korupsi yang dialaminya secara anonim.</p>
<p>Kemudian, Jendela akan mengkompilasi semua data yang diterima dan menampilkannya dalam bentuk visualisasi data. Visualisasi data dan ulasan lengkap tentang pelayanan public ini bisa digunakan bagi:</p>
<ol>
<li>Masyarakat umum untuk melihat kualitas layanan publik di daerahnya</li>
<li>Para kepala daerah dan pejabat publik untuk mengawasi layanan publik di daerahnya dan melakukan aksi akan setiap praktek suap yang dilaporkan oleh masyarakat</li>
</ol>
<p>Nantinya kami berharap dengan adanya transparansi data maka layanan publik bisa ditingkatkan.</p>
</div>
</div>
<br />
<Youtube videoID="gg_wcLIH4RA" />
<br />
<AuthorSection />
</div>
</div>
)
}
}
export default Team
|
packages/material-ui-icons/src/FormatTextdirectionLToROutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M9 4v4c-1.1 0-2-.9-2-2s.9-2 2-2m8-2H9C6.79 2 5 3.79 5 6s1.79 4 4 4v5h2V4h2v11h2V4h2V2zm0 12v3H5v2h12v3l4-4-4-4z" /></g></React.Fragment>
, 'FormatTextdirectionLToROutlined');
|
app/classifier/drawing-tools/components/DetailsSubTaskForm/DetailsSubTaskForm.spec.js | amyrebecca/Panoptes-Front-End | /* eslint
func-names: 0,
import/no-extraneous-dependencies: ["error", { "devDependencies": true }]
prefer-arrow-callback: 0,
"react/jsx-boolean-value": ["error", "always"]
*/
import React from 'react';
import PropTypes from 'prop-types';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import { DetailsSubTaskForm } from './DetailsSubTaskForm';
import tasks from '../../../tasks';
const store = {
subscribe: () => { },
dispatch: () => { },
getState: () => ({
translations: {
languages: {},
locale: 'en',
strings: { workflow: {}}
},
userInterface: { theme: 'light' }
})
};
const mockReduxStore = {
context: { store },
childContextTypes: { store: PropTypes.object.isRequired }
};
const toolProps = {
annotations: [],
color: "#00ff00",
containerRect: {},
details: [{
_key: 0.41412246953808407,
answers: [{ label: 'yes' }, { label: 'no' }],
help: "",
question: "Is this fragmentary?",
required: false,
type: "multiple"
}],
disabled: false,
mark: {
_inProgress: false,
_key: 0.4139859318882131,
details: [{ value: [] }],
frame: 0,
tool: 0,
x: 547.92529296875,
y: 62.75926208496094
},
onChange: sinon.stub().callsFake(() => {}),
scale: {},
selected: true,
size: "large",
taskKey: "T0"
};
const translations = {
languages: {},
locale: 'en',
strings: { workflow: {}}
}
describe('DetailsSubTaskForm', function() {
describe('render', function() {
let wrapper;
before(function () {
wrapper = shallow(<DetailsSubTaskForm tasks={tasks} translations={translations} toolProps={toolProps} />, mockReduxStore);
});
it('should render without crashing', function () {
expect(wrapper).to.be.ok;
});
});
});
|
demos/demo/src/components/Menu/index.js | idream3/cerebral | import React from 'react'
import {connect} from 'cerebral/react'
import {state} from 'cerebral/tags'
import translations from '../../common/computed/translations'
const MENUS = [
{
name: 'Work',
entries: [
{name: 'Today', icon: 'fa-clock-o', url: '#/'},
{name: 'Report', icon: 'fa-bar-chart', url: '#/report'}
]
},
{
name: 'Manage',
entries: [
{name: 'Clients', icon: 'fa-users', url: '#/clients'},
{name: 'Projects', icon: 'fa-folder', url: '#/projects'},
{name: 'Tasks', icon: 'fa-tasks', url: '#/tasks'}
]
}
]
export default connect({
selectedView: state`app.$selectedView`,
t: translations
},
function Navbar ({selectedView, t}) {
return (
<div className='column is-2'>
<aside className='menu'>
{MENUS.map(menu => (
<div key={menu.name}>
<p className='menu-label'>{t[menu.name]}</p>
<ul className='menu-list'>
{menu.entries.map(entry => (
<li key={entry.name}>
<a className={`${selectedView === entry.name ? 'is-active' : ''}`}
href={`${entry.url}`}>
<span className='icon is-small'>
<i className={`fa ${entry.icon}`} />
</span>
{t[entry.name]}
</a>
</li>
))}
</ul>
</div>
))}
</aside>
</div>
)
}
)
|
test/ProgressBarSpec.js | dongtong/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ProgressBar from '../src/ProgressBar';
import {shouldWarn} from './helpers';
const getProgressBarNode = wrapper => {
return React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(wrapper, 'progress-bar'));
};
describe('ProgressBar', () => {
it('Should output a progress bar with wrapper', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bprogress\b/));
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar\b/));
assert.equal(getProgressBarNode(instance).getAttribute('role'), 'progressbar');
});
it('Should have the default class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='default' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-default\b/));
});
it('Should have the primary class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='primary' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-primary\b/));
});
it('Should have the success class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='success' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-success\b/));
});
it('Should have the warning class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='warning' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-warning\b/));
});
it('Should default to min:0, max:100', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar now={5} />
);
let bar = getProgressBarNode(instance);
assert.equal(bar.getAttribute('aria-valuemin'), '0');
assert.equal(bar.getAttribute('aria-valuemax'), '100');
});
it('Should have 0% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(getProgressBarNode(instance).style.width, '0%');
});
it('Should have 10% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={1} />
);
assert.equal(getProgressBarNode(instance).style.width, '10%');
});
it('Should have 100% computed width', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={10} />
);
assert.equal(getProgressBarNode(instance).style.width, '100%');
});
it('Should have 50% computed width with non-zero min', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} />
);
assert.equal(getProgressBarNode(instance).style.width, '50%');
});
it('Should not have label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' />
);
assert.equal(React.findDOMNode(instance).innerText, '');
});
it('Should have label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary'
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
assert.equal(React.findDOMNode(instance).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have screen reader only label', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' srOnly
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
assert.equal(React.findDOMNode(srLabel).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have a label that is a React component', () => {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'special-label'));
});
it('Should have screen reader only label that wraps a React component', () => {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} srOnly />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
let component = ReactTestUtils.findRenderedDOMComponentWithClass(srLabel, 'special-label');
assert.ok(component);
});
it('Should show striped bar', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} striped />
);
assert.ok(React.findDOMNode(instance).firstChild.className.match(/\bprogress-bar-striped\b/));
});
it('Should show animated striped bar', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} active />
);
const barClassName = React.findDOMNode(instance).firstChild.className;
assert.ok(barClassName.match(/\bprogress-bar-striped\b/));
assert.ok(barClassName.match(/\bactive\b/));
});
it('Should show stacked bars', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar key={1} now={50} />
<ProgressBar key={2} now={30} />
</ProgressBar>
);
let wrapper = React.findDOMNode(instance);
let bar1 = wrapper.firstChild;
let bar2 = wrapper.lastChild;
assert.ok(wrapper.className.match(/\bprogress\b/));
assert.ok(bar1.className.match(/\bprogress-bar\b/));
assert.equal(bar1.style.width, '50%');
assert.ok(bar2.className.match(/\bprogress-bar\b/));
assert.equal(bar2.style.width, '30%');
});
it('Should render active and striped children in stacked bar too', () => {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar active key={1} now={50} />
<ProgressBar striped key={2} now={30} />
</ProgressBar>
);
let wrapper = React.findDOMNode(instance);
let bar1 = wrapper.firstChild;
let bar2 = wrapper.lastChild;
assert.ok(wrapper.className.match(/\bprogress\b/));
assert.ok(bar1.className.match(/\bprogress-bar\b/));
assert.ok(bar1.className.match(/\bactive\b/));
assert.ok(bar1.className.match(/\bprogress-bar-striped\b/));
assert.ok(bar2.className.match(/\bprogress-bar\b/));
assert.ok(bar2.className.match(/\bprogress-bar-striped\b/));
assert.notOk(bar2.className.match(/\bactive\b/));
});
it('allows only ProgressBar in children', () => {
ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar key={1} />
<div />
<ProgressBar key={2} />
</ProgressBar>
);
shouldWarn('Failed propType');
});
});
|