path
stringlengths
5
300
repo_name
stringlengths
6
76
content
stringlengths
26
1.05M
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
juagarciaga/samcell
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
__mocksd__/react-intl.js
juanda99/arasaac-frontend
// ./__mocks__/react-intl.js import React from 'react' const Intl = require.requireActual('react-intl') // Here goes intl context injected into component, feel free to extend const intl = { formatMessage: ({ defaultMessage }) => defaultMessage, formatDate: ({ defaultMessage }) => defaultMessage, formatTime: ({ defaultMessage }) => defaultMessage, formatRelative: ({ defaultMessage }) => defaultMessage, formatNumber: ({ defaultMessage }) => defaultMessage, formatPlural: ({ defaultMessage }) => defaultMessage, formatHTMLMessage: ({ defaultMessage }) => defaultMessage, now: ({ defaultMessage }) => defaultMessage } Intl.injectIntl = (Node) => (props) => <Node {...props} intl={intl} /> module.exports = Intl
src/Pagination.js
dozoisch/react-bootstrap
import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import PaginationButton from './PaginationButton'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; const propTypes = { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, /** * When `true`, will display the first and the last button page */ boundaryLinks: React.PropTypes.bool, /** * When `true`, will display the default node value ('&hellip;'). * Otherwise, will display provided node (when specified). */ ellipsis: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.node, ]), /** * When `true`, will display the default node value ('&laquo;'). * Otherwise, will display provided node (when specified). */ first: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.node, ]), /** * When `true`, will display the default node value ('&raquo;'). * Otherwise, will display provided node (when specified). */ last: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.node, ]), /** * When `true`, will display the default node value ('&lsaquo;'). * Otherwise, will display provided node (when specified). */ prev: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.node, ]), /** * When `true`, will display the default node value ('&rsaquo;'). * Otherwise, will display provided node (when specified). */ next: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.node, ]), onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: elementType, }; const defaultProps = { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false, }; class Pagination extends React.Component { renderPageButtons( activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps ) { const pageButtons = []; let startPage; let endPage; let hasHiddenPagesAfter; if (maxButtons) { let hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10); startPage = hiddenPagesBefore > 2 ? hiddenPagesBefore : 1; hasHiddenPagesAfter = startPage + maxButtons < items; if (!hasHiddenPagesAfter) { endPage = items; startPage = items - maxButtons + 1; if (startPage < 1) { startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for (let pagenumber = startPage; pagenumber <= endPage; pagenumber++) { pageButtons.push( <PaginationButton {...buttonProps} key={pagenumber} eventKey={pagenumber} active={pagenumber === activePage} > {pagenumber} </PaginationButton> ); } if (boundaryLinks && ellipsis && startPage !== 1) { pageButtons.unshift( <PaginationButton key="ellipsisFirst" disabled componentClass={buttonProps.componentClass} > <span aria-label="More"> {ellipsis === true ? '\u2026' : ellipsis} </span> </PaginationButton> ); pageButtons.unshift( <PaginationButton {...buttonProps} key={1} eventKey={1} active={false} > 1 </PaginationButton> ); } if (maxButtons && hasHiddenPagesAfter && ellipsis) { pageButtons.push( <PaginationButton key="ellipsis" disabled componentClass={buttonProps.componentClass} > <span aria-label="More"> {ellipsis === true ? '\u2026' : ellipsis} </span> </PaginationButton> ); if (boundaryLinks && endPage !== items) { pageButtons.push( <PaginationButton {...buttonProps} key={items} eventKey={items} active={false} > {items} </PaginationButton> ); } } return pageButtons; } render() { const { activePage, items, maxButtons, boundaryLinks, ellipsis, first, last, prev, next, onSelect, buttonComponentClass, className, ...props, } = this.props; const [bsProps, elementProps] = splitBsProps(props); const classes = getClassSet(bsProps); const buttonProps = { onSelect, componentClass: buttonComponentClass, }; return ( <ul {...elementProps} className={classNames(className, classes)} > {first && ( <PaginationButton {...buttonProps} eventKey={1} disabled={activePage === 1} > <span aria-label="First"> {first === true ? '\u00ab' : first} </span> </PaginationButton> )} {prev && ( <PaginationButton {...buttonProps} eventKey={activePage - 1} disabled={activePage === 1} > <span aria-label="Previous"> {prev === true ? '\u2039' : prev} </span> </PaginationButton> )} {this.renderPageButtons( activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps )} {next && ( <PaginationButton {...buttonProps} eventKey={activePage + 1} disabled={activePage >= items} > <span aria-label="Next"> {next === true ? '\u203a' : next} </span> </PaginationButton> )} {last && ( <PaginationButton {...buttonProps} eventKey={items} disabled={activePage >= items} > <span aria-label="Last"> {last === true ? '\u00bb' : last} </span> </PaginationButton> )} </ul> ); } } Pagination.propTypes = propTypes; Pagination.defaultProps = defaultProps; export default bsClass('pagination', Pagination);
ajax/libs/react-instantsearch/3.2.0/Dom.js
holtkamp/cdnjs
/*! ReactInstantSearch 3.2.0 | © Algolia, inc. | https://community.algolia.com/instantsearch.js/react/ */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["Dom"] = factory(require("react"), require("react-dom")); else root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Dom"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_105__, __WEBPACK_EXTERNAL_MODULE_373__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Panel = exports.Toggle = exports.Stats = exports.SortBy = exports.SearchBox = exports.ScrollTo = exports.ClearAll = exports.RefinementList = exports.StarRating = exports.RangeSlider = exports.RangeInput = exports.PoweredBy = exports.Pagination = exports.MultiRange = exports.Menu = exports.InfiniteHits = exports.HitsPerPage = exports.Hits = exports.Snippet = exports.Highlight = exports.HierarchicalMenu = exports.CurrentRefinements = exports.Configure = exports.InstantSearch = undefined; var _Configure = __webpack_require__(107); Object.defineProperty(exports, 'Configure', { enumerable: true, get: function get() { return _interopRequireDefault(_Configure).default; } }); var _CurrentRefinements = __webpack_require__(172); Object.defineProperty(exports, 'CurrentRefinements', { enumerable: true, get: function get() { return _interopRequireDefault(_CurrentRefinements).default; } }); var _HierarchicalMenu = __webpack_require__(179); Object.defineProperty(exports, 'HierarchicalMenu', { enumerable: true, get: function get() { return _interopRequireDefault(_HierarchicalMenu).default; } }); var _Highlight = __webpack_require__(325); Object.defineProperty(exports, 'Highlight', { enumerable: true, get: function get() { return _interopRequireDefault(_Highlight).default; } }); var _Snippet = __webpack_require__(331); Object.defineProperty(exports, 'Snippet', { enumerable: true, get: function get() { return _interopRequireDefault(_Snippet).default; } }); var _Hits = __webpack_require__(333); Object.defineProperty(exports, 'Hits', { enumerable: true, get: function get() { return _interopRequireDefault(_Hits).default; } }); var _HitsPerPage = __webpack_require__(336); Object.defineProperty(exports, 'HitsPerPage', { enumerable: true, get: function get() { return _interopRequireDefault(_HitsPerPage).default; } }); var _InfiniteHits = __webpack_require__(340); Object.defineProperty(exports, 'InfiniteHits', { enumerable: true, get: function get() { return _interopRequireDefault(_InfiniteHits).default; } }); var _Menu = __webpack_require__(343); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_Menu).default; } }); var _MultiRange = __webpack_require__(346); Object.defineProperty(exports, 'MultiRange', { enumerable: true, get: function get() { return _interopRequireDefault(_MultiRange).default; } }); var _Pagination = __webpack_require__(349); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_Pagination).default; } }); var _PoweredBy = __webpack_require__(356); Object.defineProperty(exports, 'PoweredBy', { enumerable: true, get: function get() { return _interopRequireDefault(_PoweredBy).default; } }); var _RangeInput = __webpack_require__(359); Object.defineProperty(exports, 'RangeInput', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeInput).default; } }); var _RangeSlider = __webpack_require__(362); Object.defineProperty(exports, 'RangeSlider', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeSlider).default; } }); var _StarRating = __webpack_require__(363); Object.defineProperty(exports, 'StarRating', { enumerable: true, get: function get() { return _interopRequireDefault(_StarRating).default; } }); var _RefinementList = __webpack_require__(365); Object.defineProperty(exports, 'RefinementList', { enumerable: true, get: function get() { return _interopRequireDefault(_RefinementList).default; } }); var _ClearAll = __webpack_require__(368); Object.defineProperty(exports, 'ClearAll', { enumerable: true, get: function get() { return _interopRequireDefault(_ClearAll).default; } }); var _ScrollTo = __webpack_require__(370); Object.defineProperty(exports, 'ScrollTo', { enumerable: true, get: function get() { return _interopRequireDefault(_ScrollTo).default; } }); var _SearchBox = __webpack_require__(374); Object.defineProperty(exports, 'SearchBox', { enumerable: true, get: function get() { return _interopRequireDefault(_SearchBox).default; } }); var _SortBy = __webpack_require__(376); Object.defineProperty(exports, 'SortBy', { enumerable: true, get: function get() { return _interopRequireDefault(_SortBy).default; } }); var _Stats = __webpack_require__(379); Object.defineProperty(exports, 'Stats', { enumerable: true, get: function get() { return _interopRequireDefault(_Stats).default; } }); var _Toggle = __webpack_require__(382); Object.defineProperty(exports, 'Toggle', { enumerable: true, get: function get() { return _interopRequireDefault(_Toggle).default; } }); var _Panel = __webpack_require__(385); Object.defineProperty(exports, 'Panel', { enumerable: true, get: function get() { return _interopRequireDefault(_Panel).default; } }); var _createInstantSearch = __webpack_require__(387); var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch); var _algoliasearch = __webpack_require__(392); var _algoliasearch2 = _interopRequireDefault(_algoliasearch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstantSearch = (0, _createInstantSearch2.default)(_algoliasearch2.default, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); exports.InstantSearch = InstantSearch; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(2); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(92); var _has3 = _interopRequireDefault(_has2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.default = createConnector; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = (0, _has3.default)(connectorDesc, 'refine'); var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters'); var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata'); var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState'); var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits(Connector, _Component); function Connector(props, context) { _classCallCheck(this, Connector); var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; _this.state = { props: _this.getProvidedProps(props) }; _this.unsubscribe = store.subscribe(function () { _this.setState({ props: _this.getProvidedProps(_this.props) }); }); var getSearchParameters = hasSearchParameters ? function (searchParameters) { return connectorDesc.getSearchParameters(searchParameters, _this.props, store.getState().widgets); } : null; var getMetadata = hasMetadata ? function (nextWidgetsState) { return connectorDesc.getMetadata(_this.props, nextWidgetsState); } : null; var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) { return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState); } : null; if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget({ getSearchParameters: getSearchParameters, getMetadata: getMetadata, transitionState: transitionState }); } return _this; } _createClass(Connector, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!(0, _isEqual3.default)(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); if (hasCleanUp) { var newState = connectorDesc.cleanUp(this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onInternalStateUpdate(newState); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props); } }, { key: 'render', value: function render() { var _this2 = this; if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues, searchForFacetValues: function searchForFacetValues(facetName, query) { if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.'); } _this2.searchForFacetValues(facetName, query); } } : {}; return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: _react.PropTypes.object.isRequired }, _initialiseProps = function _initialiseProps() { var _this3 = this; this.getProvidedProps = function (props) { var store = _this3.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues; var searchState = { results: results, searching: searching, error: error }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate(connectorDesc.refine.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState(connectorDesc.refine.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { return connectorDesc.cleanUp.apply(connectorDesc, arguments); }; }, _temp; }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(3); /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } module.exports = isEqual; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(4), isObjectLike = __webpack_require__(72); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), equalArrays = __webpack_require__(49), equalByTag = __webpack_require__(55), equalObjects = __webpack_require__(59), getTag = __webpack_require__(87), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isTypedArray = __webpack_require__(77); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6), stackClear = __webpack_require__(14), stackDelete = __webpack_require__(15), stackGet = __webpack_require__(16), stackHas = __webpack_require__(17), stackSet = __webpack_require__(18); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(7), listCacheDelete = __webpack_require__(8), listCacheGet = __webpack_require__(11), listCacheHas = __webpack_require__(12), listCacheSet = __webpack_require__(13); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 7 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }, /* 15 */ /***/ function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }, /* 16 */ /***/ function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }, /* 17 */ /***/ function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6), Map = __webpack_require__(19), MapCache = __webpack_require__(34); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(21), getValue = __webpack_require__(33); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(22), isMasked = __webpack_require__(30), isObject = __webpack_require__(29), toSource = __webpack_require__(32); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObject = __webpack_require__(29); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), getRawTag = __webpack_require__(27), objectToString = __webpack_require__(28); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(26); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 26 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 28 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 29 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(31); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 32 */ /***/ function(module, exports) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }, /* 33 */ /***/ function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(35), mapCacheDelete = __webpack_require__(43), mapCacheGet = __webpack_require__(46), mapCacheHas = __webpack_require__(47), mapCacheSet = __webpack_require__(48); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(36), ListCache = __webpack_require__(6), Map = __webpack_require__(19); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(37), hashDelete = __webpack_require__(39), hashGet = __webpack_require__(40), hashHas = __webpack_require__(41), hashSet = __webpack_require__(42); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 39 */ /***/ function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(45); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arraySome = __webpack_require__(53), cacheHas = __webpack_require__(54); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(34), setCacheAdd = __webpack_require__(51), setCacheHas = __webpack_require__(52); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }, /* 51 */ /***/ function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }, /* 52 */ /***/ function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }, /* 53 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 54 */ /***/ function(module, exports) { /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } module.exports = cacheHas; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), Uint8Array = __webpack_require__(56), eq = __webpack_require__(10), equalArrays = __webpack_require__(49), mapToArray = __webpack_require__(57), setToArray = __webpack_require__(58); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 57 */ /***/ function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 58 */ /***/ function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(60); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(61), getSymbols = __webpack_require__(64), keys = __webpack_require__(67); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), isArray = __webpack_require__(63); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }, /* 62 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 63 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(65), stubArray = __webpack_require__(66); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }, /* 65 */ /***/ function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 66 */ /***/ function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(68), baseKeys = __webpack_require__(82), isArrayLike = __webpack_require__(86); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(69), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isIndex = __webpack_require__(76), isTypedArray = __webpack_require__(77); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }, /* 69 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(71), isObjectLike = __webpack_require__(72); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }, /* 72 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(25), stubFalse = __webpack_require__(75); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(74)(module))) /***/ }, /* 74 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 75 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 76 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(78), baseUnary = __webpack_require__(80), nodeUtil = __webpack_require__(81); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isLength = __webpack_require__(79), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }, /* 79 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 80 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(26); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(74)(module))) /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(83), nativeKeys = __webpack_require__(84); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }, /* 83 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(85); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 85 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(22), isLength = __webpack_require__(79); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(88), Map = __webpack_require__(19), Promise = __webpack_require__(89), Set = __webpack_require__(90), WeakMap = __webpack_require__(91), baseGetTag = __webpack_require__(23), toSource = __webpack_require__(32); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(93), hasPath = __webpack_require__(94); /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } module.exports = has; /***/ }, /* 93 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } module.exports = baseHas; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isIndex = __webpack_require__(76), isLength = __webpack_require__(79), toKey = __webpack_require__(104); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(63), isKey = __webpack_require__(96), stringToPath = __webpack_require__(98), toString = __webpack_require__(101); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(63), isSymbol = __webpack_require__(97); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(99); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(100); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(34); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(102); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), arrayMap = __webpack_require__(103), isArray = __webpack_require__(63), isSymbol = __webpack_require__(97); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 103 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(97); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 105 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_105__; /***/ }, /* 106 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.shallowEqual = shallowEqual; exports.isSpecialClick = isSpecialClick; exports.capitalize = capitalize; exports.assertFacetDefined = assertFacetDefined; exports.getDisplayName = getDisplayName; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); } function capitalize(key) { return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1); } function assertFacetDefined(searchParameters, searchResults, facet) { var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet); var wasReceived = Boolean(searchResults.getFacetByName(facet)); if (searchResults.nbHits > 0 && wasRequested && !wasReceived) { // eslint-disable-next-line no-console console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.'); } } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } var resolved = Promise.resolve(); var defer = exports.defer = function defer(f) { resolved.then(f); }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectConfigure = __webpack_require__(108); var _connectConfigure2 = _interopRequireDefault(_connectConfigure); var _Configure = __webpack_require__(171); var _Configure2 = _interopRequireDefault(_Configure); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * * import {Configure} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure distinct={1} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectConfigure2.default)(_Configure2.default); /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys2 = __webpack_require__(67); var _keys3 = _interopRequireDefault(_keys2); var _difference2 = __webpack_require__(109); var _difference3 = _interopRequireDefault(_difference2); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var namespace = 'configure'; exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = (0, _omit3.default)(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var items = (0, _omit3.default)(props, 'children'); var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : []; this._props = props; return _extends({}, nextSearchState, _defineProperty({}, namespace, _extends({}, (0, _omit3.default)(nextSearchState[namespace], nonPresentKeys), items))); }, cleanUp: function cleanUp(props, searchState) { var configureKeys = searchState[namespace] ? Object.keys(searchState[namespace]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = searchState[namespace][item]; } return acc; }, {}); return (0, _isEmpty3.default)(configureState) ? (0, _omit3.default)(searchState, namespace) : _extends({}, searchState, _defineProperty({}, namespace, configureState)); } }); /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(110), baseFlatten = __webpack_require__(117), baseRest = __webpack_require__(119), isArrayLikeObject = __webpack_require__(128); /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); module.exports = difference; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arrayIncludes = __webpack_require__(111), arrayIncludesWith = __webpack_require__(116), arrayMap = __webpack_require__(103), baseUnary = __webpack_require__(80), cacheHas = __webpack_require__(54); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(113), baseIsNaN = __webpack_require__(114), strictIndexOf = __webpack_require__(115); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }, /* 113 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 114 */ /***/ function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }, /* 115 */ /***/ function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }, /* 116 */ /***/ function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), isFlattenable = __webpack_require__(118); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), isArguments = __webpack_require__(70), isArray = __webpack_require__(63); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120), overRest = __webpack_require__(121), setToString = __webpack_require__(123); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }, /* 120 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }, /* 122 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(124), shortOut = __webpack_require__(127); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(125), defineProperty = __webpack_require__(126), identity = __webpack_require__(120); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }, /* 125 */ /***/ function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 127 */ /***/ function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(86), isObjectLike = __webpack_require__(72); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(82), getTag = __webpack_require__(87), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isArrayLike = __webpack_require__(86), isBuffer = __webpack_require__(73), isPrototype = __webpack_require__(83), isTypedArray = __webpack_require__(77); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseClone = __webpack_require__(131), baseUnset = __webpack_require__(162), castPath = __webpack_require__(95), copyObject = __webpack_require__(136), customOmitClone = __webpack_require__(167), flatRest = __webpack_require__(169), getAllKeysIn = __webpack_require__(147); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); module.exports = omit; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), arrayEach = __webpack_require__(132), assignValue = __webpack_require__(133), baseAssign = __webpack_require__(135), baseAssignIn = __webpack_require__(137), cloneBuffer = __webpack_require__(141), copyArray = __webpack_require__(142), copySymbols = __webpack_require__(143), copySymbolsIn = __webpack_require__(144), getAllKeys = __webpack_require__(60), getAllKeysIn = __webpack_require__(147), getTag = __webpack_require__(87), initCloneArray = __webpack_require__(148), initCloneByTag = __webpack_require__(149), initCloneObject = __webpack_require__(160), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isObject = __webpack_require__(29), keys = __webpack_require__(67); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }, /* 132 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), eq = __webpack_require__(10); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(126); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keys = __webpack_require__(67); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(133), baseAssignValue = __webpack_require__(134); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keysIn = __webpack_require__(138); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(68), baseKeysIn = __webpack_require__(139), isArrayLike = __webpack_require__(86); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29), isPrototype = __webpack_require__(83), nativeKeysIn = __webpack_require__(140); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }, /* 140 */ /***/ function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(25); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(74)(module))) /***/ }, /* 142 */ /***/ function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), getSymbols = __webpack_require__(64); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), getSymbolsIn = __webpack_require__(145); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), getPrototype = __webpack_require__(146), getSymbols = __webpack_require__(64), stubArray = __webpack_require__(66); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(85); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(61), getSymbolsIn = __webpack_require__(145), keysIn = __webpack_require__(138); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }, /* 148 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150), cloneDataView = __webpack_require__(151), cloneMap = __webpack_require__(152), cloneRegExp = __webpack_require__(155), cloneSet = __webpack_require__(156), cloneSymbol = __webpack_require__(158), cloneTypedArray = __webpack_require__(159); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(56); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(153), arrayReduce = __webpack_require__(154), mapToArray = __webpack_require__(57); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } module.exports = cloneMap; /***/ }, /* 153 */ /***/ function(module, exports) { /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } module.exports = addMapEntry; /***/ }, /* 154 */ /***/ function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }, /* 155 */ /***/ function(module, exports) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(157), arrayReduce = __webpack_require__(154), setToArray = __webpack_require__(58); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } module.exports = cloneSet; /***/ }, /* 157 */ /***/ function(module, exports) { /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } module.exports = addSetEntry; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), getPrototype = __webpack_require__(146), isPrototype = __webpack_require__(83); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), last = __webpack_require__(163), parent = __webpack_require__(164), toKey = __webpack_require__(104); /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } module.exports = baseUnset; /***/ }, /* 163 */ /***/ function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165), baseSlice = __webpack_require__(166); /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } module.exports = parent; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), toKey = __webpack_require__(104); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 166 */ /***/ function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(168); /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } module.exports = customOmitClone; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), getPrototype = __webpack_require__(146), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var flatten = __webpack_require__(170), overRest = __webpack_require__(121), setToString = __webpack_require__(123); /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } module.exports = flatRest; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(117); /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } module.exports = flatten; /***/ }, /* 171 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { return null; }; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(173); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _CurrentRefinements = __webpack_require__(174); var _CurrentRefinements2 = _interopRequireDefault(_CurrentRefinements); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The CurrentRefinements widget displays the list of currently applied filters. * * It allows the user to selectively remove them. * @name CurrentRefinements * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-CurrentRefinements__root - the root div of the widget * @themeKey ais-CurrentRefinements__items - the container of the filters * @themeKey ais-CurrentRefinements__item - a single filter * @themeKey ais-CurrentRefinements__itemLabel - the label of a filter * @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter * @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CurrentRefinements /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_CurrentRefinements2.default); /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _react = __webpack_require__(105); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values. * @providedPropType {function} query - the search query */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { return typeof meta.items !== 'undefined' ? res.concat(meta.items) : res; }, []); var query = props.clearsQuery && searchResults.results ? searchResults.results.query : undefined; return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0, query: query }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; searchState = props.clearsQuery && searchState.query ? _extends({}, searchState, { query: '' }) : searchState; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('CurrentRefinements'); var CurrentRefinements = function (_Component) { _inherits(CurrentRefinements, _Component); function CurrentRefinements() { _classCallCheck(this, CurrentRefinements); return _possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments)); } _createClass(CurrentRefinements, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, translate = _props.translate, items = _props.items, refine = _props.refine, canRefine = _props.canRefine; return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), _react2.default.createElement( 'div', cx('items'), items.map(function (item) { return _react2.default.createElement( 'div', _extends({ key: item.label }, cx('item', item.items && 'itemParent')), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), item.items ? item.items.map(function (nestedItem) { return _react2.default.createElement( 'div', _extends({ key: nestedItem.label }, cx('item')), _react2.default.createElement( 'span', cx('itemLabel'), nestedItem.label ), _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, nestedItem.value) }), translate('clearFilter', nestedItem) ) ); }) : _react2.default.createElement( 'button', _extends({}, cx('itemClear'), { onClick: refine.bind(null, item.value) }), translate('clearFilter', item) ) ); }) ) ); } }]); return CurrentRefinements; }(_react.Component); CurrentRefinements.propTypes = { translate: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string })).isRequired, refine: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, transformItems: _react.PropTypes.func }; CurrentRefinements.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ clearFilter: '✕' })(CurrentRefinements); /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); var _has3 = _interopRequireDefault(_has2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = translatable; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); var _propTypes = __webpack_require__(176); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function translatable(defaultTranslations) { return function (Composed) { function Translatable(props) { var translations = props.translations, otherProps = _objectWithoutProperties(props, ['translations']); var translate = function translate(key) { for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } var translation = translations && (0, _has3.default)(translations, key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { return translation.apply(undefined, params); } return translation; }; return _react2.default.createElement(Composed, _extends({ translate: translate }, otherProps)); } Translatable.displayName = 'Translatable(' + (0, _utils.getDisplayName)(Composed) + ')'; Translatable.propTypes = { translations: (0, _propTypes.withKeysPropType)(Object.keys(defaultTranslations)) }; return Translatable; }; } /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined; var _react = __webpack_require__(105); var configManagerPropType = exports.configManagerPropType = _react.PropTypes.shape({ register: _react.PropTypes.func.isRequired, swap: _react.PropTypes.func.isRequired, unregister: _react.PropTypes.func.isRequired }); var stateManagerPropType = exports.stateManagerPropType = _react.PropTypes.shape({ createURL: _react.PropTypes.func.isRequired, setState: _react.PropTypes.func.isRequired, getState: _react.PropTypes.func.isRequired, unlisten: _react.PropTypes.func.isRequired }); var withKeysPropType = exports.withKeysPropType = function withKeysPropType(keys) { return function (props, propName, componentName) { var prop = props[propName]; if (prop) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var key = _step.value; if (keys.indexOf(key) === -1) { return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.')); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } return undefined; }; }; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNames; var _classnames = __webpack_require__(178); var _classnames2 = _interopRequireDefault(_classnames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var prefix = 'ais'; function classNames(block) { return function () { for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } return { className: (0, _classnames2.default)(elements.filter(function (element) { return element !== undefined && element !== false; }).map(function (element) { return prefix + '-' + block + '__' + element; })) }; }; } /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHierarchicalMenu = __webpack_require__(180); var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu); var _HierarchicalMenu = __webpack_require__(321); var _HierarchicalMenu2 = _interopRequireDefault(_HierarchicalMenu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The hierarchical menu lets the user browse attributes using a tree-like structure. * * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * * @name HierarchicalMenu * @kind widget * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HierarchicalMenu__root - Container of the widget * @themeKey ais-HierarchicalMenu__items - Container of the items * @themeKey ais-HierarchicalMenu__item - Id for a single list item * @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list * @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed * @themeKey HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected * @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count * @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry * @themeKey ais-HierarchicalMenu__itemCount - the count of the entry * @themeKey ais-HierarchicalMenu__itemItems - id representing a children * @themeKey ais-HierarchicalMenu__showMore - container for the show more button * @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement * @translationKey showMore - Label value of the button which toggles the number of items * @example * import React from 'react'; * import { * InstantSearch, * HierarchicalMenu, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HierarchicalMenu * id="categories" * key="categories" * attributes={[ * 'category', * 'sub_category', * 'sub_sub_category', * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHierarchicalMenu2.default)(_HierarchicalMenu2.default); /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getId = undefined; var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _algoliasearchHelper = __webpack_require__(181); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var getId = exports.getId = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var subState = searchState[namespace]; if (subState[id] === '') { return null; } return subState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return null; } function getValue(path, props, searchState) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue(value, limit, props, searchState) { return value.slice(0, limit).map(function (v) { return { label: v.name, value: getValue(v.path, props, searchState), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, limit, props, searchState) }; }); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax. * @propType {number} [limitMin=10] - The maximum number of items displayed. * @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: _react.PropTypes.string, rootPath: _react.PropTypes.string, showParentLevel: _react.PropTypes.bool, defaultRefinement: _react.PropTypes.string, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId(props); var results = searchResults.results; var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, limit, props, searchState) : []; return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: getCurrentRefinement(props, searchState), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement || '')))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var id = getId(props); var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); var currentRefinement = getCurrentRefinement(props, searchState); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var rootAttribute = props.attributes[0]; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); return { id: id, items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, currentRefinement: currentRefinement }] }; } }); /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var AlgoliaSearchHelper = __webpack_require__(182); var SearchParameters = __webpack_require__(183); var SearchResults = __webpack_require__(246); /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new AlgoliaSearchHelper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = __webpack_require__(320); /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = __webpack_require__(305); module.exports = algoliasearchHelper; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SearchParameters = __webpack_require__(183); var SearchResults = __webpack_require__(246); var DerivedHelper = __webpack_require__(298); var requestBuilder = __webpack_require__(304); var util = __webpack_require__(299); var events = __webpack_require__(303); var flatten = __webpack_require__(170); var forEach = __webpack_require__(192); var isEmpty = __webpack_require__(129); var map = __webpack_require__(210); var url = __webpack_require__(305); var version = __webpack_require__(320); /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when the search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line else client.addAlgoliaAgent('JS Helper ' + version); this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occcurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occured it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder._getQueries(tempState.index, tempState); if (cb) { return this.client.search( queries, function(err, content) { if (err) cb(err, null, tempState); else cb(err, new SearchResults(tempState, content.results), tempState); } ); } return this.client.search(queries).then(function(content) { return { content: new SearchResults(tempState, content.results), state: tempState, _originalResponse: content }; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {objet} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query insde the engine */ /** * Search for facet values based on an query and the name of a facetted attribute. This * triggers a search and will retrun a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} query the string query for the search * @param {string} facet the name of the facetted attribute * @return {promise<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query) { var state = this.state; var index = this.client.initIndex(this.state.index); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, this.state); return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) { content.facetHits = forEach(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this.state = this.state.setPage(0).setQuery(q); this._change(); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this.state = this.state.setPage(0).clearRefinements(name); this._change(); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this.state = this.state.setPage(0).clearTags(); this._change(); return this; }; /** * Adds a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value); this._change(); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Adds a filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).addFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a facetted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).addExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this.state = this.state.setPage(0).addTagRefinement(tag); this._change(); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optionnals, triggering different behaviors: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value); this._change(); return this; }; /** * Removes a disjunctive filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet); this._change(); return this; }; /** * Removes a filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this.state = this.state.setPage(0).removeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a facetted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).removeExcludeRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this.state = this.state.setPage(0).removeTagRefinement(tag); this._change(); return this; }; /** * Adds or removes an exclusion filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a facetted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this.state = this.state.setPage(0).toggleTagRefinement(tag); this._change(); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this.state = this.state.setPage(page); this._change(); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this.state = this.state.setPage(0).setIndex(name); this._change(); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { var newState = this.state.setPage(0).setQueryParameter(parameter, value); if (this.state === newState) return this; this.state = newState; this._change(); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this.state = new SearchParameters(newState); this._change(); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optionnal filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optionnal parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific facetted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for facetting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten(derivedQueries)); var queryId = this._queryId++; this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId)); }; /** * Transform the responses as sent by the server and transform them into a user * usable objet that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {Error} err error if any, null otherwise * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._lastQueryIdReceived = queryId; if (err) { this.emit('error', err); return; } var results = content.results; forEach(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function() { this.emit('change', this.state, this.lastResults); }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent) newClient.addAlgoliaAgent('JS Helper ' + version); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `results` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the facetting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ module.exports = AlgoliaSearchHelper; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var keys = __webpack_require__(67); var intersection = __webpack_require__(184); var forOwn = __webpack_require__(187); var forEach = __webpack_require__(192); var filter = __webpack_require__(195); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var omit = __webpack_require__(130); var indexOf = __webpack_require__(214); var isNaN = __webpack_require__(218); var isArray = __webpack_require__(63); var isEmpty = __webpack_require__(129); var isEqual = __webpack_require__(2); var isUndefined = __webpack_require__(220); var isString = __webpack_require__(221); var isFunction = __webpack_require__(22); var find = __webpack_require__(222); var trim = __webpack_require__(225); var defaults = __webpack_require__(233); var merge = __webpack_require__(238); var valToNumber = __webpack_require__(243); var filterState = __webpack_require__(244); var RefinementList = __webpack_require__(245); /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find(array, function(currentValue) { return isEqual(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * seperated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFiters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each facetted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach(numberKeys, function(k) { var value = partialState[k]; if (isString(value)) { var parsedValue = parseFloat(value); numbers[k] = isNaN(parsedValue) ? value : parsedValue; } }); if (partialState.numericRefinements) { var numericRefinements = {}; forEach(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach(operators, function(values, operator) { var parsedValues = map(values, function(v) { if (isArray(v)) { return map(v, function(vPrime) { if (isString(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) facetting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive facetting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive facetting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge({}, this.numericRefinements); mod[attribute] = merge({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for facetting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute of the record * @param {string} operator applied * @return {number} value of the refinement */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optionnal string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(this.numericRefinements, attribute); } else if (isFunction(attribute)) { return reduce(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach(operators, function(values, operator) { var outValues = []; forEach(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty(outValues)) operatorList[operator] = outValues; }); if (!isEmpty(operatorList)) memo[key] = operatorList; return memo; }, {}); } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the facetting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the facetted attribute. * @method * @param {string} facet name of the attribute used for facetting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for facetting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleRefinement: function toggleRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value, optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for facetting * @param {string} [value] optionnal value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for facetting * @param {string} value optionnal, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined(value) && isUndefined(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined(this.numericRefinements[attribute][operator]); if (isUndefined(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber(value); var isAttributeValueDefined = !isUndefined( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection( keys(this.numericRefinements), this.disjunctiveFacets ); return keys(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for facetting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map(this.hierarchicalFacets, 'name'), keys(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter(this.disjunctiveFacets, function(f) { return indexOf(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn(this, function(paramValue, paramName) { if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys(params); forEach(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map(path, trim); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ module.exports = SearchParameters; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIntersection = __webpack_require__(185), baseRest = __webpack_require__(119), castArrayLikeObject = __webpack_require__(186); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arrayIncludes = __webpack_require__(111), arrayIncludesWith = __webpack_require__(116), arrayMap = __webpack_require__(103), baseUnary = __webpack_require__(80), cacheHas = __webpack_require__(54); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(128); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = castArrayLikeObject; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188), castFunction = __webpack_require__(191); /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, castFunction(iteratee)); } module.exports = forOwn; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(189), keys = __webpack_require__(67); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(190); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 190 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120); /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = castFunction; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(132), baseEach = __webpack_require__(193), castFunction = __webpack_require__(191), isArray = __webpack_require__(63); /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, castFunction(iteratee)); } module.exports = forEach; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188), createBaseEach = __webpack_require__(194); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(86); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(65), baseFilter = __webpack_require__(196), baseIteratee = __webpack_require__(197), isArray = __webpack_require__(63); /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, baseIteratee(predicate, 3)); } module.exports = filter; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(193); /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } module.exports = baseFilter; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(198), baseMatchesProperty = __webpack_require__(203), identity = __webpack_require__(120), isArray = __webpack_require__(63), property = __webpack_require__(207); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(199), getMatchData = __webpack_require__(200), matchesStrictComparable = __webpack_require__(202); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), baseIsEqual = __webpack_require__(3); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(201), keys = __webpack_require__(67); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 202 */ /***/ function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(3), get = __webpack_require__(204), hasIn = __webpack_require__(205), isKey = __webpack_require__(96), isStrictComparable = __webpack_require__(201), matchesStrictComparable = __webpack_require__(202), toKey = __webpack_require__(104); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(206), hasPath = __webpack_require__(94); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 206 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(208), basePropertyDeep = __webpack_require__(209), isKey = __webpack_require__(96), toKey = __webpack_require__(104); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 208 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), baseMap = __webpack_require__(211), isArray = __webpack_require__(63); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee, 3)); } module.exports = map; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(193), isArrayLike = __webpack_require__(86); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(154), baseEach = __webpack_require__(193), baseIteratee = __webpack_require__(197), baseReduce = __webpack_require__(213), isArray = __webpack_require__(63); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach); } module.exports = reduce; /***/ }, /* 213 */ /***/ function(module, exports) { /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } module.exports = baseReduce; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112), toInteger = __webpack_require__(215); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } module.exports = indexOf; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(216); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(217); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29), isSymbol = __webpack_require__(97); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(219); /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } module.exports = isNaN; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var numberTag = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } module.exports = isNumber; /***/ }, /* 220 */ /***/ function(module, exports) { /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isArray = __webpack_require__(63), isObjectLike = __webpack_require__(72); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } module.exports = isString; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var createFind = __webpack_require__(223), findIndex = __webpack_require__(224); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); module.exports = find; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(197), isArrayLike = __webpack_require__(86), keys = __webpack_require__(67); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } module.exports = createFind; /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(113), baseIteratee = __webpack_require__(197), toInteger = __webpack_require__(215); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, baseIteratee(predicate, 3), index); } module.exports = findIndex; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(102), castSlice = __webpack_require__(226), charsEndIndex = __webpack_require__(227), charsStartIndex = __webpack_require__(228), stringToArray = __webpack_require__(229), toString = __webpack_require__(101); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } module.exports = trim; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(166); /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } module.exports = castSlice; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsEndIndex; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } module.exports = charsStartIndex; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var asciiToArray = __webpack_require__(230), hasUnicode = __webpack_require__(231), unicodeToArray = __webpack_require__(232); /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } module.exports = stringToArray; /***/ }, /* 230 */ /***/ function(module, exports) { /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } module.exports = asciiToArray; /***/ }, /* 231 */ /***/ function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } module.exports = hasUnicode; /***/ }, /* 232 */ /***/ function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } module.exports = unicodeToArray; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), assignInWith = __webpack_require__(234), baseRest = __webpack_require__(119), customDefaultsAssignIn = __webpack_require__(237); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, customDefaultsAssignIn); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), createAssigner = __webpack_require__(235), keysIn = __webpack_require__(138); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), isIterateeCall = __webpack_require__(236); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10), isArrayLike = __webpack_require__(86), isIndex = __webpack_require__(76), isObject = __webpack_require__(29); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = customDefaultsAssignIn; /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(239), createAssigner = __webpack_require__(235); /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); module.exports = merge; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), assignMergeValue = __webpack_require__(240), baseFor = __webpack_require__(189), baseMergeDeep = __webpack_require__(241), isObject = __webpack_require__(29), keysIn = __webpack_require__(138); /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } module.exports = baseMerge; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), eq = __webpack_require__(10); /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignMergeValue; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(240), cloneBuffer = __webpack_require__(141), cloneTypedArray = __webpack_require__(159), copyArray = __webpack_require__(142), initCloneObject = __webpack_require__(160), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isArrayLikeObject = __webpack_require__(128), isBuffer = __webpack_require__(73), isFunction = __webpack_require__(22), isObject = __webpack_require__(29), isPlainObject = __webpack_require__(168), isTypedArray = __webpack_require__(77), toPlainObject = __webpack_require__(242); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } module.exports = baseMergeDeep; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keysIn = __webpack_require__(138); /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } module.exports = toPlainObject; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var map = __webpack_require__(210); var isArray = __webpack_require__(63); var isNumber = __webpack_require__(219); var isString = __webpack_require__(221); function valToNumber(v) { if (isNumber(v)) { return v; } else if (isString(v)) { return parseFloat(v); } else if (isArray(v)) { return map(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } module.exports = valToNumber; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var filter = __webpack_require__(195); var map = __webpack_require__(210); var isEmpty = __webpack_require__(129); var indexOf = __webpack_require__(214); function filterState(state, filters) { var partialState = {}; var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf(attributes, '*') === -1) { forEach(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } module.exports = filterState; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var isUndefined = __webpack_require__(220); var isString = __webpack_require__(221); var isFunction = __webpack_require__(22); var isEmpty = __webpack_require__(129); var defaults = __webpack_require__(233); var reduce = __webpack_require__(212); var filter = __webpack_require__(195); var omit = __webpack_require__(130); var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated prefinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * behaviors can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optionnal parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined(attribute)) { return {}; } else if (isString(attribute)) { return omit(refinementList, attribute); } else if (isFunction(attribute)) { return reduce(refinementList, function(memo, values, key) { var facetList = filter(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty(facetList)) memo[key] = facetList; return memo; }, {}); } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = __webpack_require__(214); var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; module.exports = lib; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var compact = __webpack_require__(247); var indexOf = __webpack_require__(214); var findIndex = __webpack_require__(224); var get = __webpack_require__(204); var sumBy = __webpack_require__(248); var find = __webpack_require__(222); var includes = __webpack_require__(250); var map = __webpack_require__(210); var orderBy = __webpack_require__(253); var defaults = __webpack_require__(233); var merge = __webpack_require__(238); var isArray = __webpack_require__(63); var isFunction = __webpack_require__(22); var partial = __webpack_require__(258); var partialRight = __webpack_require__(290); var formatSort = __webpack_require__(291); var generateHierarchicalTree = __webpack_require__(294); /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the facetting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objets matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} value the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric fitlers. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach(result.facets, function(facetResults, dfacet) { var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state)); this.facets = compact(this.facets); this.disjunctiveFacets = compact(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the attribute facetted * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find(this.facets, predicate) || find(this.disjunctiveFacets, predicate) || find(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the facetted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find(results.facets, predicate); if (!facet) return []; return map(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map(node.data, partial(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (isArray(facetValues)) { return orderBy(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight(orderBy, order[0], order[1]), facetValues); } else if (isFunction(options.sortBy)) { if (isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the facetted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach(state.facetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach(state.facetsExcludes, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach(state.numericRefinements, function(operators, attributeName) { forEach(operators, function(values, operator) { forEach(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var count = get(facet, 'data[' + name + ']'); var exhaustive = get(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find(facet.data, {name: splitted[i]}); } var count = get(facet, 'count'); var exhaustive = get(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } module.exports = SearchResults; /***/ }, /* 247 */ /***/ function(module, exports) { /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } module.exports = compact; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(197), baseSum = __webpack_require__(249); /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, baseIteratee(iteratee, 2)) : 0; } module.exports = sumBy; /***/ }, /* 249 */ /***/ function(module, exports) { /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } module.exports = baseSum; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112), isArrayLike = __webpack_require__(86), isString = __webpack_require__(221), toInteger = __webpack_require__(215), values = __webpack_require__(251); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(252), keys = __webpack_require__(67); /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } module.exports = values; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } module.exports = baseValues; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { var baseOrderBy = __webpack_require__(254), isArray = __webpack_require__(63); /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } module.exports = orderBy; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), baseMap = __webpack_require__(211), baseSortBy = __webpack_require__(255), baseUnary = __webpack_require__(80), compareMultiple = __webpack_require__(256), identity = __webpack_require__(120); /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } module.exports = baseOrderBy; /***/ }, /* 255 */ /***/ function(module, exports) { /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } module.exports = baseSortBy; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(257); /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } module.exports = compareMultiple; /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(97); /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } module.exports = compareAscending; /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; module.exports = partial; /***/ }, /* 259 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(260), createBind = __webpack_require__(262), createCurry = __webpack_require__(264), createHybrid = __webpack_require__(265), createPartial = __webpack_require__(288), getData = __webpack_require__(273), mergeData = __webpack_require__(289), setData = __webpack_require__(280), setWrapToString = __webpack_require__(281), toInteger = __webpack_require__(215); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } module.exports = createWrap; /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120), metaMap = __webpack_require__(261); /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; module.exports = baseSetData; /***/ }, /* 261 */ /***/ function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(91); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }, /* 262 */ /***/ function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(263), root = __webpack_require__(25); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } module.exports = createBind; /***/ }, /* 263 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), isObject = __webpack_require__(29); /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } module.exports = createCtor; /***/ }, /* 264 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), createCtor = __webpack_require__(263), createHybrid = __webpack_require__(265), createRecurry = __webpack_require__(269), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287), root = __webpack_require__(25); /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } module.exports = createCurry; /***/ }, /* 265 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(266), composeArgsRight = __webpack_require__(267), countHolders = __webpack_require__(268), createCtor = __webpack_require__(263), createRecurry = __webpack_require__(269), getHolder = __webpack_require__(285), reorder = __webpack_require__(286), replaceHolders = __webpack_require__(287), root = __webpack_require__(25); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_ARY_FLAG = 128, WRAP_FLIP_FLAG = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } module.exports = createHybrid; /***/ }, /* 266 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } module.exports = composeArgs; /***/ }, /* 267 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } module.exports = composeArgsRight; /***/ }, /* 268 */ /***/ function(module, exports) { /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } module.exports = countHolders; /***/ }, /* 269 */ /***/ function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(270), setData = __webpack_require__(280), setWrapToString = __webpack_require__(281); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } module.exports = createRecurry; /***/ }, /* 270 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), getData = __webpack_require__(273), getFuncName = __webpack_require__(275), lodash = __webpack_require__(277); /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } module.exports = isLaziable; /***/ }, /* 271 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), baseLodash = __webpack_require__(272); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; module.exports = LazyWrapper; /***/ }, /* 272 */ /***/ function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }, /* 273 */ /***/ function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(261), noop = __webpack_require__(274); /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; module.exports = getData; /***/ }, /* 274 */ /***/ function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 275 */ /***/ function(module, exports, __webpack_require__) { var realNames = __webpack_require__(276); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } module.exports = getFuncName; /***/ }, /* 276 */ /***/ function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }, /* 277 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), LodashWrapper = __webpack_require__(278), baseLodash = __webpack_require__(272), isArray = __webpack_require__(63), isObjectLike = __webpack_require__(72), wrapperClone = __webpack_require__(279); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; module.exports = lodash; /***/ }, /* 278 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), baseLodash = __webpack_require__(272); /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; module.exports = LodashWrapper; /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), LodashWrapper = __webpack_require__(278), copyArray = __webpack_require__(142); /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } module.exports = wrapperClone; /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(260), shortOut = __webpack_require__(127); /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); module.exports = setData; /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(282), insertWrapDetails = __webpack_require__(283), setToString = __webpack_require__(123), updateWrapDetails = __webpack_require__(284); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } module.exports = setWrapToString; /***/ }, /* 282 */ /***/ function(module, exports) { /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } module.exports = getWrapDetails; /***/ }, /* 283 */ /***/ function(module, exports) { /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } module.exports = insertWrapDetails; /***/ }, /* 284 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(132), arrayIncludes = __webpack_require__(111); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } module.exports = updateWrapDetails; /***/ }, /* 285 */ /***/ function(module, exports) { /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } module.exports = getHolder; /***/ }, /* 286 */ /***/ function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(142), isIndex = __webpack_require__(76); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } module.exports = reorder; /***/ }, /* 287 */ /***/ function(module, exports) { /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } module.exports = replaceHolders; /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), createCtor = __webpack_require__(263), root = __webpack_require__(25); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } module.exports = createPartial; /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(266), composeArgsRight = __webpack_require__(267), replaceHolders = __webpack_require__(287); /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } module.exports = mergeData; /***/ }, /* 290 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; module.exports = partialRight; /***/ }, /* 291 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var reduce = __webpack_require__(212); var find = __webpack_require__(222); var startsWith = __webpack_require__(292); /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ module.exports = function formatSort(sortBy, defaults) { return reduce(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find(defaults, function(predicate) { return startsWith(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /***/ }, /* 292 */ /***/ function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(293), baseToString = __webpack_require__(102), toInteger = __webpack_require__(215), toString = __webpack_require__(101); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } module.exports = startsWith; /***/ }, /* 293 */ /***/ function(module, exports) { /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } module.exports = baseClamp; /***/ }, /* 294 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = generateTrees; var last = __webpack_require__(163); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var orderBy = __webpack_require__(253); var trim = __webpack_require__(225); var find = __webpack_require__(222); var pickBy = __webpack_require__(295); var prepareHierarchicalFacetSortBy = __webpack_require__(291); function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy( map( pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim(last(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /***/ }, /* 295 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), basePickBy = __webpack_require__(296), getAllKeysIn = __webpack_require__(147); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = baseIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } module.exports = pickBy; /***/ }, /* 296 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165), baseSet = __webpack_require__(297), castPath = __webpack_require__(95); /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } module.exports = basePickBy; /***/ }, /* 297 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(133), castPath = __webpack_require__(95), isIndex = __webpack_require__(76), isObject = __webpack_require__(29), toKey = __webpack_require__(104); /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } module.exports = baseSet; /***/ }, /* 298 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var util = __webpack_require__(299); var events = __webpack_require__(303); /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; module.exports = DerivedHelper; /***/ }, /* 299 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = ({"NODE_ENV":"production"}).NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(301); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(302); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(300))) /***/ }, /* 300 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 301 */ /***/ function(module, exports) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }, /* 302 */ /***/ function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }, /* 303 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }, /* 304 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var merge = __webpack_require__(238); var isArray = __webpack_require__(63); var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach(state.numericRefinements, function(operators, attribute) { forEach(operators, function(values, operator) { if (facetName !== attribute) { forEach(values, function(value) { if (isArray(value)) { var vs = map(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach(state.facetsRefinements, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach(state.facetsExcludes, function(facetValues, facetName) { forEach(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var queries = merge(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), { facetQuery: query, facetName: facetName }); return queries; } }; module.exports = requestBuilder; /***/ }, /* 305 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var shortener = __webpack_require__(306); var SearchParameters = __webpack_require__(183); var qs = __webpack_require__(310); var bind = __webpack_require__(315); var forEach = __webpack_require__(192); var pick = __webpack_require__(316); var map = __webpack_require__(210); var mapKeys = __webpack_require__(318); var mapValues = __webpack_require__(319); var isString = __webpack_require__(221); var isPlainObject = __webpack_require__(168); var isArray = __webpack_require__(63); var invert = __webpack_require__(307); var encode = __webpack_require__(312).encode; function recursiveEncode(input) { if (isPlainObject(input)) { return mapValues(input, recursiveEncode); } if (isArray(input)) { return map(input, recursiveEncode); } if (isString(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ exports.getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var partialStateWithPrefix = qs.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState); return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ exports.getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert(mapping); var foreignConfig = {}; var config = qs.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ exports.getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (moreAttributes) { var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = qs.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return qs.stringify(encodedState, {encode: safe, sort: sort}); }; /***/ }, /* 306 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var invert = __webpack_require__(307); var keys = __webpack_require__(67); var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert(keys2Short); module.exports = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; /***/ }, /* 307 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(125), createInverter = __webpack_require__(308), identity = __webpack_require__(120); /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); module.exports = invert; /***/ }, /* 308 */ /***/ function(module, exports, __webpack_require__) { var baseInverter = __webpack_require__(309); /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } module.exports = createInverter; /***/ }, /* 309 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188); /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } module.exports = baseInverter; /***/ }, /* 310 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var stringify = __webpack_require__(311); var parse = __webpack_require__(314); var formats = __webpack_require__(313); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }, /* 311 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(312); var formats = __webpack_require__(313); var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder ? encoder(prefix) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { return [formatter(encoder(prefix)) + '=' + formatter(encoder(obj))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts || {}; var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = encode ? (typeof options.encoder === 'function' ? options.encoder : defaults.encoder) : null; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; if (typeof options.format === 'undefined') { options.format = formats.default; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter )); } return keys.join(delimiter); }; /***/ }, /* 312 */ /***/ function(module, exports) { 'use strict'; var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); exports.arrayToObject = function (source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function (target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { target[source] = true; } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (Object.prototype.hasOwnProperty.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function (str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D || // - c === 0x2E || // . c === 0x5F || // _ c === 0x7E || // ~ (c >= 0x30 && c <= 0x39) || // 0-9 (c >= 0x41 && c <= 0x5A) || // a-z (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function (obj, references) { if (typeof obj !== 'object' || obj === null) { return obj; } var refs = references || []; var lookup = refs.indexOf(obj); if (lookup !== -1) { return refs[lookup]; } refs.push(obj); if (Array.isArray(obj)) { var compacted = []; for (var i = 0; i < obj.length; ++i) { if (obj[i] && typeof obj[i] === 'object') { compacted.push(exports.compact(obj[i], refs)); } else if (typeof obj[i] !== 'undefined') { compacted.push(obj[i]); } } return compacted; } var keys = Object.keys(obj); keys.forEach(function (key) { obj[key] = exports.compact(obj[key], refs); }); return obj; }; exports.isRegExp = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function (obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; /***/ }, /* 313 */ /***/ function(module, exports) { 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; /***/ }, /* 314 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(312); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseValues(str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; var key, val; if (pos === -1) { key = options.decoder(part); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos)); val = options.decoder(part.slice(pos + 1)); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function parseObject(chain, val, options) { if (!chain.length) { return val; } var root = chain.shift(); var obj; if (root === '[]') { obj = []; obj = obj.concat(parseObject(chain, val, options)); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = parseObject(chain, val, options); } else { obj[cleanRoot] = parseObject(chain, val, options); } } return obj; }; var parseKeys = function parseKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^\.\[]+)/g, '[$1]') : givenKey; // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Stash the parent if it exists var keys = []; if (segment[1]) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, segment[1])) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].replace(/\[|\]/g, ''))) { if (!options.allowPrototypes) { continue; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; module.exports = function (str, opts) { var options = opts || {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; /***/ }, /* 315 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_PARTIAL_FLAG = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; module.exports = bind; /***/ }, /* 316 */ /***/ function(module, exports, __webpack_require__) { var basePick = __webpack_require__(317), flatRest = __webpack_require__(169); /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); module.exports = pick; /***/ }, /* 317 */ /***/ function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(296), hasIn = __webpack_require__(205); /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } module.exports = basePick; /***/ }, /* 318 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), baseForOwn = __webpack_require__(188), baseIteratee = __webpack_require__(197); /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } module.exports = mapKeys; /***/ }, /* 319 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), baseForOwn = __webpack_require__(188), baseIteratee = __webpack_require__(197); /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } module.exports = mapValues; /***/ }, /* 320 */ /***/ function(module, exports) { 'use strict'; module.exports = '2.18.0'; /***/ }, /* 321 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); var _pick3 = _interopRequireDefault(_pick2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(324); var _Link2 = _interopRequireDefault(_Link); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('HierarchicalMenu'); var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.string, count: _react.PropTypes.number.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var HierarchicalMenu = function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, createURL = _this$props.createURL, refine = _this$props.refine; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel'), item.label ), ' ', _react2.default.createElement( 'span', cx('itemCount'), item.count ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(HierarchicalMenu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine']))); } }]); return HierarchicalMenu; }(_react.Component); HierarchicalMenu.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, items: itemsPropType, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; HierarchicalMenu.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /***/ }, /* 322 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _SearchBox = __webpack_require__(323); var _SearchBox2 = _interopRequireDefault(_SearchBox); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var itemsPropType = _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.any, label: _react.PropTypes.string.isRequired, items: function items() { return itemsPropType.apply(undefined, arguments); } })); var List = function (_Component) { _inherits(List, _Component); function List() { _classCallCheck(this, List); var _this = _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this)); _this.defaultProps = { isFromSearch: false }; _this.onShowMoreClick = function () { _this.setState(function (state) { return { extended: !state.extended }; }); }; _this.getLimit = function () { var _this$props = _this.props, limitMin = _this$props.limitMin, limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.renderItem = function (item) { var items = item.items && _react2.default.createElement( 'div', _this.props.cx('itemItems'), item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }) ); return _react2.default.createElement( 'div', _extends({ key: item.key || item.label }, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')), _this.props.renderItem(item), items ); }; _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props, showMore = _props.showMore, translate = _props.translate, cx = _props.cx; var extended = this.state.extended; var disabled = this.props.limitMin >= this.props.items.length; if (!showMore) { return null; } return _react2.default.createElement( 'button', _extends({ disabled: disabled }, cx('showMore', disabled && 'showMoreDisabled'), { onClick: this.onShowMoreClick }), translate('showMore', extended) ); } }, { key: 'renderSearchBox', value: function renderSearchBox() { var _this2 = this; var _props2 = this.props, cx = _props2.cx, searchForItems = _props2.searchForItems, isFromSearch = _props2.isFromSearch, translate = _props2.translate, items = _props2.items, selectItem = _props2.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? _react2.default.createElement( 'div', cx('noResults'), translate('noResults') ) : null; return _react2.default.createElement( 'div', cx('SearchBox'), _react2.default.createElement(_SearchBox2.default, { currentRefinement: isFromSearch ? this.state.query : '', refine: function refine(value) { _this2.setState({ query: value }); searchForItems(value); }, focusShortcuts: [], translate: translate, onSubmit: function onSubmit(e) { e.preventDefault(); e.stopPropagation(); if (isFromSearch) { selectItem(items[0]); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, cx = _props3.cx, items = _props3.items, withSearchBox = _props3.withSearchBox, canRefine = _props3.canRefine; var searchBox = withSearchBox ? this.renderSearchBox() : null; if (items.length === 0) { return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), searchBox ); } // Always limit the number of items we show on screen, since the actual // number of retrieved items might vary with the `maxValuesPerFacet` config // option. var limit = this.getLimit(); return _react2.default.createElement( 'div', cx('root', !this.props.canRefine && 'noRefinement'), searchBox, _react2.default.createElement( 'div', cx('items'), items.slice(0, limit).map(function (item) { return _this3.renderItem(item); }) ), this.renderShowMore() ); } }]); return List; }(_react.Component); List.propTypes = { cx: _react.PropTypes.func.isRequired, // Only required with showMore. translate: _react.PropTypes.func, items: itemsPropType, renderItem: _react.PropTypes.func.isRequired, selectItem: _react.PropTypes.func, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, limit: _react.PropTypes.number, show: _react.PropTypes.func, searchForItems: _react.PropTypes.func, withSearchBox: _react.PropTypes.bool, isFromSearch: _react.PropTypes.bool, canRefine: _react.PropTypes.bool }; exports.default = List; /***/ }, /* 323 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('SearchBox'); var SearchBox = function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { _classCallCheck(this, SearchBox); var _this = _possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this)); _this.getQuery = function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }; _this.setQuery = function (val) { var _this$props = _this.props, refine = _this$props.refine, searchAsYouType = _this$props.searchAsYouType; if (searchAsYouType) { refine(val); } else { _this.setState({ query: val }); } }; _this.onInputMount = function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }; _this.onKeyDown = function (e) { if (!_this.props.focusShortcuts) { return; } var shortcuts = _this.props.focusShortcuts.map(function (key) { return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key; }); var elt = e.target || e.srcElement; var tagName = elt.tagName; if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') { // already in an input return; } var which = e.which || e.keyCode; if (shortcuts.indexOf(which) === -1) { // not the right shortcut return; } _this.input.focus(); e.stopPropagation(); e.preventDefault(); }; _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); var _this$props2 = _this.props, refine = _this$props2.refine, searchAsYouType = _this$props2.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (e) { _this.setQuery(e.target.value); }; _this.onReset = function () { _this.setQuery(''); _this.input.focus(); }; _this.state = { query: props.searchAsYouType ? null : props.currentRefinement }; return _this; } _createClass(SearchBox, [{ key: 'componentDidMount', value: function componentDidMount() { document.addEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { document.removeEventListener('keydown', this.onKeyDown); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Reset query when the searchParameters query has changed. // This is kind of an anti-pattern (props in state), but it works here // since we know for sure that searchParameters having changed means a // new search has been triggered. if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: nextProps.currentRefinement }); } } // From https://github.com/algolia/autocomplete.js/pull/86 }, { key: 'render', value: function render() { var _props = this.props, translate = _props.translate, autoFocus = _props.autoFocus; var query = this.getQuery(); /* eslint-disable max-len */ return _react2.default.createElement( 'form', _extends({ noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset }, cx('root')), _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } }, _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-search-13', viewBox: '0 0 40 40' }, _react2.default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z', fillRule: 'evenodd' }) ), _react2.default.createElement( 'symbol', { xmlns: 'http://www.w3.org/2000/svg', id: 'sbx-icon-clear-3', viewBox: '0 0 20 20' }, _react2.default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z', fillRule: 'evenodd' }) ) ), _react2.default.createElement( 'div', _extends({ role: 'search' }, cx('wrapper')), _react2.default.createElement('input', _extends({ ref: this.onInputMount, type: 'search', placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: 'off', required: true, value: query, onChange: this.onChange }, cx('input'))), _react2.default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')), _react2.default.createElement( 'svg', { role: 'img' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ) ), _react2.default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }), _react2.default.createElement( 'svg', { role: 'img' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ) ) ) ); /* eslint-enable */ } }]); return SearchBox; }(_react.Component); SearchBox.propTypes = { currentRefinement: _react.PropTypes.string, refine: _react.PropTypes.func.isRequired, translate: _react.PropTypes.func.isRequired, focusShortcuts: _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number])), autoFocus: _react.PropTypes.bool, searchAsYouType: _react.PropTypes.bool, onSubmit: _react.PropTypes.func, // For testing purposes __inputRef: _react.PropTypes.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true }; exports.default = (0, _translatable2.default)({ submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); /***/ }, /* 324 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Link = function (_Component) { _inherits(Link, _Component); function Link() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Link); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) { if ((0, _utils.isSpecialClick)(e)) { return; } _this.props.onClick(); e.preventDefault(); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Link, [{ key: 'render', value: function render() { return _react2.default.createElement('a', _extends({}, (0, _omit3.default)(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(_react.Component); Link.propTypes = { onClick: _react.PropTypes.func.isRequired }; exports.default = Link; /***/ }, /* 325 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(326); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Highlight = __webpack_require__(329); var _Highlight2 = _interopRequireDefault(_Highlight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Highlight * @kind widget * @propType {string} attributeName - the location of the highlighted attribute in the hit * @propType {object} hit - the hit object containing the highlighted attribute * @example * import React from 'react'; * * import {InstantSearch, connectHits, Highlight} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Highlight attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Highlight2.default); /***/ }, /* 326 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _highlight = __webpack_require__(327); var _highlight2 = _interopRequireDefault(_highlight); var _highlightTags = __webpack_require__(328); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName, hit = _ref.hit, highlightProperty = _ref.highlightProperty; return (0, _highlight2.default)({ attributeName: attributeName, hit: hit, preTag: _highlightTags2.default.highlightPreTag, postTag: _highlightTags2.default.highlightPostTag, highlightProperty: highlightProperty }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`. * @example * const CustomHighlight = connectHighlight(({highlight, attributeName, hit, highlightProperty) => { * const parsedHit = highlight({attributeName, hit, highlightProperty}); * return parsedHit.map(part => { * if(part.isHighlighted) return <em>{part.value}</em>; * return part.value: * }); * }); */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /***/ }, /* 327 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(204); var _get3 = _interopRequireDefault(_get2); exports.default = parseAlgoliaHit; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attributeName - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseAlgoliaHit(_ref) { var _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag, highlightProperty = _ref.highlightProperty, attributeName = _ref.attributeName, hit = _ref.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName); var highlightedValue = !highlightObject ? '' : highlightObject.value; return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue }); } /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref2) { var preTag = _ref2.preTag, postTag = _ref2.postTag, highlightedValue = _ref2.highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { (function () { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); })(); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } /***/ }, /* 328 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var timestamp = Date.now().toString(); exports.default = { highlightPreTag: "<ais-highlight-" + timestamp + ">", highlightPostTag: "</ais-highlight-" + timestamp + ">" }; /***/ }, /* 329 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = Highlight; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(330); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlight(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_highlightResult' }, props)); } Highlight.propTypes = { hit: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired }; /***/ }, /* 330 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Highlighter; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlighter(_ref) { var hit = _ref.hit, attributeName = _ref.attributeName, highlight = _ref.highlight, highlightProperty = _ref.highlightProperty; var parsedHighlightedValue = highlight({ hit: hit, attributeName: attributeName, highlightProperty: highlightProperty }); var reactHighlighted = parsedHighlightedValue.map(function (v, i) { var key = "split-" + i + "-" + v.value; if (!v.isHighlighted) { return _react2.default.createElement( "span", { key: key, className: "ais-Highlight__nonHighlighted" }, v.value ); } return _react2.default.createElement( "em", { key: key, className: "ais-Highlight__highlighted" }, v.value ); }); return _react2.default.createElement( "span", { className: "ais-Highlight" }, reactHighlighted ); } Highlighter.propTypes = { hit: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired, highlightProperty: _react2.default.PropTypes.string.isRequired }; /***/ }, /* 331 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(326); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Snippet = __webpack_require__(332); var _Snippet2 = _interopRequireDefault(_Snippet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Renders any attribute from an hit into its highlighted snippet form when relevant. * * Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide. * @name Snippet * @kind widget * @propType {string} attributeName - the location of the highlighted snippet attribute in the hit * @propType {object} hit - the hit object containing the highlighted snippet attribute * @example * import React from 'react'; * * import {InstantSearch, connectHits, Snippet} from 'InstantSearch'; * * const CustomHits = connectHits(hits => { * return hits.map((hit) => <p><Snippet attributeName="description" hit={hit}/></p>); * }); * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHighlight2.default)(_Snippet2.default); /***/ }, /* 332 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = Snippet; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(330); var _Highlighter2 = _interopRequireDefault(_Highlighter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Snippet(props) { return _react2.default.createElement(_Highlighter2.default, _extends({ highlightProperty: '_snippetResult' }, props)); } Snippet.propTypes = { hit: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired }; /***/ }, /* 333 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHits = __webpack_require__(334); var _connectHits2 = _interopRequireDefault(_connectHits); var _Hits = __webpack_require__(335); var _Hits2 = _interopRequireDefault(_Hits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays a list of hits. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name Hits * @kind widget * @propType {Component} [hitComponent] - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey ais-Hits__root - the root of the component * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Hits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectHits2.default)(_Hits2.default); /***/ }, /* 334 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * parameter to the [searchParameters](guide/Search_parameters.html) prop on `<InstantSearch/>`. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var hits = searchResults.results ? searchResults.results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); /***/ }, /* 335 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Hits'); var Hits = function (_Component) { _inherits(Hits, _Component); function Hits() { _classCallCheck(this, Hits); return _possibleConstructorReturn(this, (Hits.__proto__ || Object.getPrototypeOf(Hits)).apply(this, arguments)); } _createClass(Hits, [{ key: 'render', value: function render() { var _props = this.props, ItemComponent = _props.hitComponent, hits = _props.hits; return _react2.default.createElement( 'div', cx('root'), hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }) ); } }]); return Hits; }(_react.Component); Hits.propTypes = { hits: _react.PropTypes.array, hitComponent: _react.PropTypes.func.isRequired }; Hits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; exports.default = Hits; /***/ }, /* 336 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHitsPerPage = __webpack_require__(337); var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage); var _HitsPerPage = __webpack_require__(338); var _HitsPerPage2 = _interopRequireDefault(_HitsPerPage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The HitsPerPage widget displays a dropdown menu to let the user change the number * of displayed hits. * * @name HitsPerPage * @kind widget * @propType {{value: number, label: string}[]} items - List of available options. * @propType {number} defaultRefinement - The number of items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-HitsPerPage__root - the root of the component. * @example * import React from 'react'; * import { * InstantSearch, * HitsPerPage, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <HitsPerPage defaultRefinement={20}/> * </InstantSearch> * ); * } */ exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default); /***/ }, /* 337 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId() { return 'hitsPerPage'; } function getCurrentRefinement(props, searchState) { var id = getId(); if (typeof searchState[id] !== 'undefined') { if (typeof searchState[id] === 'string') { return parseInt(searchState[id], 10); } return searchState[id]; } return props.defaultRefinement; } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: _react.PropTypes.number.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.number.isRequired })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextHitsPerPage) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextHitsPerPage)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState)); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 338 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(339); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('HitsPerPage'); var HitsPerPage = function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: 'render', value: function render() { var _props = this.props, currentRefinement = _props.currentRefinement, refine = _props.refine, items = _props.items; return _react2.default.createElement(_Select2.default, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx }); } }]); return HitsPerPage; }(_react.Component); HitsPerPage.propTypes = { refine: _react.PropTypes.func.isRequired, currentRefinement: _react.PropTypes.number.isRequired, transformItems: _react.PropTypes.func, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ /** * Number of hits to display. */ value: _react.PropTypes.number.isRequired, /** * Label to display on the option. */ label: _react.PropTypes.string })) }; exports.default = HitsPerPage; /***/ }, /* 339 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); var _has3 = _interopRequireDefault(_has2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Select = function (_Component) { _inherits(Select, _Component); function Select() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Select); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.onSelect(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Select, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, items = _props.items, selectedItem = _props.selectedItem; return _react2.default.createElement( 'select', _extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }), items.map(function (item) { return _react2.default.createElement( 'option', { key: (0, _has3.default)(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, (0, _has3.default)(item, 'label') ? item.label : item.value ); }) ); } }]); return Select; }(_react.Component); Select.propTypes = { cx: _react.PropTypes.func.isRequired, onSelect: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired, key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), label: _react.PropTypes.string, disabled: _react.PropTypes.bool })).isRequired, selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired }; exports.default = Select; /***/ }, /* 340 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectInfiniteHits = __webpack_require__(341); var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits); var _InfiniteHits = __webpack_require__(342); var _InfiniteHits2 = _interopRequireDefault(_InfiniteHits); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Displays an infinite list of hits along with a **load more** button. * * To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html). * * @name InfiniteHits * @kind widget * @propType {Component} hitComponent - Component used for rendering each hit from * the results. If it is not provided the rendering defaults to displaying the * hit in its JSON form. The component will be called with a `hit` prop. * @themeKey root - the root of the component * @example * import React from 'react'; * import { * InstantSearch, * Hits, * } from 'react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <InfiniteHits /> * </InstantSearch> * ); * } */ exports.default = (0, _connectInfiniteHits2.default)(_InfiniteHits2.default); /***/ }, /* 341 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function getId() { return 'page'; } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { if (!searchResults.results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var _searchResults$result = searchResults.results, hits = _searchResults$result.hits, page = _searchResults$result.page, nbPages = _searchResults$result.nbPages, hitsPerPage = _searchResults$result.hitsPerPage; if (page === 0) { this._allResults = hits; } else { var previousPage = this._allResults.length / hitsPerPage - 1; if (page > previousPage) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits)); } else if (page < previousPage) { this._allResults = hits; } // If it is the same page we do not touch the page result list } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var id = getId(); var currentPage = searchState[id] ? searchState[id] : 0; return searchParameters.setQueryParameters({ page: currentPage }); }, refine: function refine(props, searchState) { var id = getId(); var nextPage = searchState[id] ? Number(searchState[id]) + 1 : 1; return _extends({}, searchState, _defineProperty({}, id, nextPage)); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); if (prevSearchState[id] === nextSearchState[id]) { return _extends({}, nextSearchState, _defineProperty({}, id, 0)); } return nextSearchState; } }); /***/ }, /* 342 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('InfiniteHits'); var InfiniteHits = function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: 'render', value: function render() { var _props = this.props, ItemComponent = _props.hitComponent, hits = _props.hits, hasMore = _props.hasMore, refine = _props.refine; var renderedHits = hits.map(function (hit) { return _react2.default.createElement(ItemComponent, { key: hit.objectID, hit: hit }); }); var loadMoreButton = hasMore ? _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { onClick: function onClick() { return refine(); } }), 'Load more' ) : _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { disabled: true }), 'Load more' ); return _react2.default.createElement( 'div', cx('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(_react.Component); InfiniteHits.propTypes = { hits: _react.PropTypes.array, hitComponent: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]).isRequired, hasMore: _react.PropTypes.bool.isRequired, refine: _react.PropTypes.func.isRequired }; InfiniteHits.defaultProps = { hitComponent: function hitComponent(hit) { return _react2.default.createElement( 'div', { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px' } }, JSON.stringify(hit).slice(0, 100), '...' ); } }; exports.default = InfiniteHits; /***/ }, /* 343 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMenu = __webpack_require__(344); var _connectMenu2 = _interopRequireDefault(_connectMenu); var _Menu = __webpack_require__(345); var _Menu2 = _interopRequireDefault(_Menu); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Menu component displays a menu that lets the user choose a single value for a specific attribute. * @name Menu * @kind widget * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @themeKey ais-Menu__root - the root of the component * @themeKey ais-Menu__items - the container of all items in the menu * @themeKey ais-Menu__item - a single item * @themeKey ais-Menu__itemLinkSelected - the selected menu item * @themeKey ais-Menu__itemLink - the item link * @themeKey ais-Menu__itemLabelSelected - the selected item label * @themeKey ais-Menu__itemLabel - the item label * @themeKey ais-Menu__itemCount - the item count * @themeKey ais-Menu__itemCountSelected - the selected item count * @themeKey ais-Menu__noRefinement - present when there is no refinement * @themeKey ais-Menu__showMore - the button that let the user toggle more results * @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @example * import React from 'react'; * * import {Menu, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Menu * attributeName="category" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMenu2.default)(_Menu2.default); /***/ }, /* 344 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _orderBy2 = __webpack_require__(253); var _orderBy3 = _interopRequireDefault(_orderBy2); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId(props) { return props.attributeName; } var namespace = 'menu'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { if (searchState[namespace][id] === '') { return null; } return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return null; } function getValue(name, props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); return name === currentRefinement ? '' : name; } var sortBy = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user tha ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of diplayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [withSearchBox=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMenu', propTypes: { attributeName: _react.PropTypes.string.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, defaultRefinement: _react.PropTypes.string, transformItems: _react.PropTypes.func, withSearchBox: _react.PropTypes.bool, searchForFacetValues: _react.PropTypes.bool }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var results = searchResults.results; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState), count: v.count, isRefined: v.isRefined }; }); var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement ? nextRefinement : '')))); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters.addDisjunctiveFacet(attributeName); var currentRefinement = getCurrentRefinement(props, searchState); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); return { id: id, items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, currentRefinement: currentRefinement }] }; } }); /***/ }, /* 345 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); var _pick3 = _interopRequireDefault(_pick2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(324); var _Link2 = _interopRequireDefault(_Link); var _Highlight = __webpack_require__(325); var _Highlight2 = _interopRequireDefault(_Highlight); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Menu'); var Menu = function (_Component) { _inherits(Menu, _Component); function Menu() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Menu); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, refine = _this$props.refine, createURL = _this$props.createURL; var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.isRefined && 'itemLinkSelected'), { onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }), _react2.default.createElement( 'span', cx('itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }, _this.selectItem = function (item) { _this.props.refine(item.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Menu, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))); } }]); return Menu; }(_react.Component); Menu.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, searchForItems: _react.PropTypes.func.isRequired, withSearchBox: _react.PropTypes.bool, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.string.isRequired, count: _react.PropTypes.number.isRequired, isRefined: _react.PropTypes.bool.isRequired })), isFromSearch: _react.PropTypes.bool.isRequired, canRefine: _react.PropTypes.bool.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; Menu.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(Menu); /***/ }, /* 346 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMultiRange = __webpack_require__(347); var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange); var _MultiRange = __webpack_require__(348); var _MultiRange2 = _interopRequireDefault(_MultiRange); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * MultiRange is a widget used for selecting the range value of a numeric attribute. * @name MultiRange * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max". * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-MultiRange__root - The root component of the widget * @themeKey ais-MultiRange__items - The container of the items * @themeKey ais-MultiRange__item - A single item * @themeKey ais-MultiRange__itemSelected - The selected item * @themeKey ais-MultiRange__itemLabel - The label of an item * @themeKey ais-MultiRange__itemLabelSelected - The selected label item * @themeKey ais-MultiRange__itemRadio - The radio of an item * @themeKey ais-MultiRange__itemRadioSelected - The selected radio item * @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges * @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range * @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * * import {InstantSearch, MultiRange} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <MultiRange attributeName="price" * items={[ * {end: 10, label: '<$10'}, * {start: 10, end: 100, label: '$10-$100'}, * {start: 100, end: 500, label: '$100-$500'}, * {start: 500, label: '>$500'}, * ]} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectMultiRange2.default)(_MultiRange2.default); /***/ }, /* 347 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _find3 = __webpack_require__(222); var _find4 = _interopRequireDefault(_find3); 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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = _slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace = 'multiRange'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return ''; } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attributeName, results, value) { var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } /** * connectMultiRange connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectMultiRange * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @kind connector * @propType {string} attributeName - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaMultiRange', propTypes: { id: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.node, start: _react.PropTypes.number, end: _react.PropTypes.number })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: searchResults && searchResults.results ? itemHasRefinement(getId(props), searchResults.results, value) : false }; }); var stats = searchResults.results && searchResults.results.getFacetByName(attributeName) ? searchResults.results.getFacetStats(attributeName) : null; var refinedItem = (0, _find4.default)(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: (0, _isEmpty3.default)(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextRefinement)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement(props, searchState)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attributeName); if (start) { searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var value = getCurrentRefinement(props, searchState); var items = []; if (value !== '') { var _find2 = (0, _find4.default)(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attributeName + ': ' + label, attributeName: props.attributeName, currentRefinement: label, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); } }); } return { id: id, items: items }; } }); /***/ }, /* 348 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('MultiRange'); var MultiRange = function (_Component) { _inherits(MultiRange, _Component); function MultiRange() { var _ref; var _temp, _this, _ret; _classCallCheck(this, MultiRange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) { var _this$props = _this.props, refine = _this$props.refine, translate = _this$props.translate; var label = item.value === '' ? translate('all') : item.label; return _react2.default.createElement( 'label', cx(item.value === '' && 'itemAll'), _react2.default.createElement('input', _extends({}, cx('itemRadio', item.isRefined && 'itemRadioSelected'), { type: 'radio', checked: item.isRefined, disabled: item.noRefinement, onChange: refine.bind(null, item.value) })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ) ); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(MultiRange, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { var _props = this.props, items = _props.items, canRefine = _props.canRefine; return _react2.default.createElement(_List2.default, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx, items: items.map(function (item) { return _extends({}, item, { key: item.value }); }) }); } }]); return MultiRange; }(_react.Component); MultiRange.propTypes = { items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.node.isRequired, value: _react.PropTypes.string.isRequired, isRefined: _react.PropTypes.bool.isRequired, noRefinement: _react.PropTypes.bool.isRequired })).isRequired, refine: _react.PropTypes.func.isRequired, transformItems: _react.PropTypes.func, canRefine: _react.PropTypes.bool.isRequired, translate: _react.PropTypes.func.isRequired }; MultiRange.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ all: 'All' })(MultiRange); /***/ }, /* 349 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPagination = __webpack_require__(350); var _connectPagination2 = _interopRequireDefault(_connectPagination); var _Pagination = __webpack_require__(351); var _Pagination2 = _interopRequireDefault(_Pagination); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Pagination widget displays a simple pagination system allowing the user to * change the current page. * @name Pagination * @kind widget * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination__root - The root component of the widget * @themeKey ais-Pagination__itemFirst - The first page link item * @themeKey ais-Pagination__itemPrevious - The previous page link item * @themeKey ais-Pagination__itemPage - The page link item * @themeKey ais-Pagination__itemNext - The next page link item * @themeKey ais-Pagination__itemLast - The last page link item * @themeKey ais-Pagination__itemDisabled - a disabled item * @themeKey ais-Pagination__itemSelected - a selected item * @themeKey ais-Pagination__itemLink - The link of an item * @themeKey ais-Pagination__noRefinement - present when there is no refinement * @translationKey previous - Label value for the previous page link * @translationKey next - Label value for the next page link * @translationKey first - Label value for the first page link * @translationKey last - Label value for the last page link * @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string * @translationKey ariaPrevious - Accessibility label value for the previous page link * @translationKey ariaNext - Accessibility label value for the next page link * @translationKey ariaFirst - Accessibility label value for the first page link * @translationKey ariaLast - Accessibility label value for the last page link * @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string * @example * import React from 'react'; * * import {Pagination, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Pagination/> * </InstantSearch> * ); * } */ exports.default = (0, _connectPagination2.default)(_Pagination2.default); /***/ }, /* 350 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId() { return 'page'; } function getCurrentRefinement(props, searchState) { var id = getId(); var page = searchState[id]; if (typeof page === 'undefined') { page = 1; } else if (typeof page === 'string') { page = parseInt(page, 10); } if (props.defaultRefinement) { return props.defaultRefinement; } return page; } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [pagesPadding=3] - How many page links to display around the current page. * @propType {number} [maxPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { if (!searchResults.results) { return null; } var nbPages = searchResults.results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement(props, searchState), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextPage)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement(props, searchState) - 1); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); if (nextSearchState[id] && nextSearchState[id].isSamePage) { return _extends({}, nextSearchState, _defineProperty({}, id, prevSearchState[id])); } else if (prevSearchState[id] === nextSearchState[id]) { return (0, _omit3.default)(nextSearchState, id); } return nextSearchState; }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 351 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = __webpack_require__(352); var _range3 = _interopRequireDefault(_range2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _LinkList = __webpack_require__(355); var _LinkList2 = _interopRequireDefault(_LinkList); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Pagination'); function getPagesDisplayedCount(padding, total) { return Math.min(2 * padding + 1, total); } function calculatePaddingLeft(current, padding, total, totalDisplayedPages) { if (current <= padding) { return current; } if (current >= total - padding) { return totalDisplayedPages - (total - current); } return padding; } function getPages(page, total, padding) { var totalDisplayedPages = getPagesDisplayedCount(padding, total); if (totalDisplayedPages === total) return (0, _range3.default)(1, total + 1); var paddingLeft = calculatePaddingLeft(page, padding, total, totalDisplayedPages); var paddingRight = totalDisplayedPages - paddingLeft; var first = page - paddingLeft; var last = page + paddingRight; return (0, _range3.default)(first + 1, last + 1); } var Pagination = function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments)); } _createClass(Pagination, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'getItem', value: function getItem(modifier, translationKey, value) { var _props = this.props, nbPages = _props.nbPages, maxPages = _props.maxPages, translate = _props.translate; return { key: modifier + '.' + value, modifier: modifier, disabled: value < 1 || value >= Math.min(maxPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate('aria' + (0, _utils.capitalize)(translationKey), value) }; } }, { key: 'render', value: function render() { var _props2 = this.props, nbPages = _props2.nbPages, maxPages = _props2.maxPages, currentRefinement = _props2.currentRefinement, pagesPadding = _props2.pagesPadding, showFirst = _props2.showFirst, showPrevious = _props2.showPrevious, showNext = _props2.showNext, showLast = _props2.showLast, refine = _props2.refine, createURL = _props2.createURL, translate = _props2.translate, ListComponent = _props2.listComponent, otherProps = _objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']); var totalPages = Math.min(nbPages, maxPages); var lastPage = totalPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'itemFirst', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'itemPrevious', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } var samePage = { valueOf: function valueOf() { return currentRefinement; }, isSamePage: true }; items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value === currentRefinement ? samePage : value, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'itemNext', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'itemLast', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return _react2.default.createElement(ListComponent, _extends({}, otherProps, { cx: cx, items: items, selectedItem: currentRefinement, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(_react.Component); Pagination.propTypes = { nbPages: _react.PropTypes.number.isRequired, currentRefinement: _react.PropTypes.number.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, translate: _react.PropTypes.func.isRequired, listComponent: _react.PropTypes.func, showFirst: _react.PropTypes.bool, showPrevious: _react.PropTypes.bool, showNext: _react.PropTypes.bool, showLast: _react.PropTypes.bool, pagesPadding: _react.PropTypes.number, maxPages: _react.PropTypes.number }; Pagination.defaultProps = { listComponent: _LinkList2.default, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ previous: '‹', next: '›', first: '«', last: '»', page: function page(currentRefinement) { return currentRefinement.toString(); }, ariaPrevious: 'Previous page', ariaNext: 'Next page', ariaFirst: 'First page', ariaLast: 'Last page', ariaPage: function ariaPage(currentRefinement) { return 'Page ' + currentRefinement.toString(); } })(Pagination); /***/ }, /* 352 */ /***/ function(module, exports, __webpack_require__) { var createRange = __webpack_require__(353); /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); module.exports = range; /***/ }, /* 353 */ /***/ function(module, exports, __webpack_require__) { var baseRange = __webpack_require__(354), isIterateeCall = __webpack_require__(236), toFinite = __webpack_require__(216); /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } module.exports = createRange; /***/ }, /* 354 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax = Math.max; /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } module.exports = baseRange; /***/ }, /* 355 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); var _has3 = _interopRequireDefault(_has2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(324); var _Link2 = _interopRequireDefault(_Link); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var LinkList = function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments)); } _createClass(LinkList, [{ key: 'render', value: function render() { var _props = this.props, cx = _props.cx, createURL = _props.createURL, items = _props.items, selectedItem = _props.selectedItem, onSelect = _props.onSelect, canRefine = _props.canRefine; return _react2.default.createElement( 'ul', cx('root', !canRefine && 'noRefinement'), items.map(function (item) { return _react2.default.createElement( 'li', _extends({ key: (0, _has3.default)(item, 'key') ? item.key : item.value }, cx('item', // on purpose == following, see // https://github.com/algolia/instantsearch.js/commit/bfed1f3512e40fb1e9989453582b4a2c2d90e3f2 // eslint-disable-next-line item.value == selectedItem && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), { disabled: item.disabled }), item.disabled ? _react2.default.createElement( 'span', cx('itemLink', 'itemLinkDisabled'), (0, _has3.default)(item, 'label') ? item.label : item.value ) : _react2.default.createElement( _Link2.default, _extends({}, cx('itemLink', item.value === selectedItem && 'itemLinkSelected'), { 'aria-label': item.ariaLabel, href: createURL(item.value), onClick: onSelect.bind(null, item.value) }), (0, _has3.default)(item, 'label') ? item.label : item.value ) ); }) ); } }]); return LinkList; }(_react.Component); LinkList.propTypes = { cx: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]).isRequired, key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), label: _react.PropTypes.node, modifier: _react.PropTypes.string, ariaLabel: _react.PropTypes.string, disabled: _react.PropTypes.bool })), selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]), onSelect: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired }; exports.default = LinkList; /***/ }, /* 356 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPoweredBy = __webpack_require__(357); var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy); var _PoweredBy = __webpack_require__(358); var _PoweredBy2 = _interopRequireDefault(_PoweredBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * PoweredBy displays an Algolia logo. * * Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing). * @name PoweredBy * @kind widget * @themeKey ais-PoweredBy__root - The root component of the widget * @themeKey ais-PoweredBy__searchBy - The powered by label * @themeKey ais-PoweredBy__algoliaLink - The algolia logo link * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * * import {PoweredBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <PoweredBy /> * </InstantSearch> * ); * } */ exports.default = (0, _connectPoweredBy2.default)(_PoweredBy2.default); /***/ }, /* 357 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps() { var url = 'https://www.algolia.com/?' + 'utm_source=instantsearch.js&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /***/ }, /* 358 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return _react2.default.createElement( 'svg', { xmlns: 'http://www.w3.org/2000/svg', baseProfile: 'basic', viewBox: '0 0 1366 362' }, _react2.default.createElement( 'linearGradient', { id: 'g', x1: '428.258', x2: '434.145', y1: '404.15', y2: '409.85', gradientUnits: 'userSpaceOnUse', gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)' }, _react2.default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }), _react2.default.createElement('stop', { offset: '1', stopColor: '#3369E7' }) ), _react2.default.createElement('path', { d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z', fill: 'url(#g)' }), _react2.default.createElement('path', { d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z', fill: '#FFFFFF' }), _react2.default.createElement('path', { d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z', fill: '#182359' }) ); }; /* eslint-enable max-len */ var PoweredBy = function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments)); } _createClass(PoweredBy, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, url = _props.url; return _react2.default.createElement( 'div', cx('root'), _react2.default.createElement( 'span', cx('searchBy'), translate('searchBy'), ' ' ), _react2.default.createElement( 'a', _extends({ href: url, target: '_blank' }, cx('algoliaLink')), _react2.default.createElement(AlgoliaLogo, null) ) ); } }]); return PoweredBy; }(_react.Component); PoweredBy.propTypes = { url: _react.PropTypes.string.isRequired, translate: _react.PropTypes.func.isRequired }; exports.default = (0, _translatable2.default)({ searchBy: 'Search by' })(PoweredBy); /***/ }, /* 359 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _RangeInput = __webpack_require__(361); var _RangeInput2 = _interopRequireDefault(_RangeInput); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * RangeInput allows a user to select a numeric range using a minimum and maximum input. * @name RangeInput * @kind widget * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - the name of the attribute in the record * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @themeKey ais-RangeInput__root - The root component of the widget * @themeKey ais-RangeInput__labelMin - The label for the min input * @themeKey ais-RangeInput__inputMin - The min input * @themeKey ais-RangeInput__separator - The separator between input * @themeKey ais-RangeInput__labelMax - The label for the max input * @themeKey ais-RangeInput__inputMax - The max input * @themeKey ais-RangeInput__submit - The submit button * @themeKey ais-RangeInput__noRefinement - present when there is no refinement * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * * import {RangeInput, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RangeInput attributeName="price"/> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_RangeInput2.default); /***/ }, /* 360 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @propType {string} attributeName - Name of the attribute for faceting * @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied */ function getId(props) { return props.attributeName; } var namespace = 'range'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var _searchState$namespac = searchState[namespace][id], min = _searchState$namespac.min, max = _searchState$namespac.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; } if (typeof props.defaultRefinement !== 'undefined') { return props.defaultRefinement; } return {}; } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRange', propTypes: { id: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, defaultRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number.isRequired, max: _react.PropTypes.number.isRequired }), min: _react.PropTypes.number, max: _react.PropTypes.number }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var min = props.min, max = props.max; var hasMin = typeof min !== 'undefined'; var hasMax = typeof max !== 'undefined'; if (!hasMin || !hasMax) { if (!searchResults.results) { return { canRefine: false }; } var stats = searchResults.results.getFacetByName(attributeName) ? searchResults.results.getFacetStats(attributeName) : null; if (!stats) { return { canRefine: false }; } if (!hasMin) { min = stats.min; } if (!hasMax) { max = stats.max; } } var count = searchResults.results ? searchResults.results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRefinement = getCurrentRefinement(props, searchState), _getCurrentRefinement2 = _getCurrentRefinement.min, valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2, _getCurrentRefinement3 = _getCurrentRefinement.max, valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3; return { min: min, max: max, currentRefinement: { min: valueMin, max: valueMax }, count: count, canRefine: count.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) { throw new Error('You can\'t provide non finite values to the range connector'); } return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props), nextRefinement)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState); params = params.addDisjunctiveFacet(attributeName); var min = currentRefinement.min, max = currentRefinement.max; if (typeof min !== 'undefined') { params = params.addNumericRefinement(attributeName, '>=', min); } if (typeof max !== 'undefined') { params = params.addNumericRefinement(attributeName, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); var item = void 0; var hasMin = typeof currentRefinement.min !== 'undefined'; var hasMax = typeof currentRefinement.max !== 'undefined'; if (hasMin || hasMax) { var itemLabel = ''; if (hasMin) { itemLabel += currentRefinement.min + ' <= '; } itemLabel += props.attributeName; if (hasMax) { itemLabel += ' <= ' + currentRefinement.max; } item = { label: itemLabel, currentRefinement: currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, {})))); } }; } return { id: id, items: item ? [item] : [] }; } }); /***/ }, /* 361 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isNaN2 = __webpack_require__(218); var _isNaN3 = _interopRequireDefault(_isNaN2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('RangeInput'); var RangeInput = function (_Component) { _inherits(RangeInput, _Component); function RangeInput(props) { _classCallCheck(this, RangeInput); var _this = _possibleConstructorReturn(this, (RangeInput.__proto__ || Object.getPrototypeOf(RangeInput)).call(this, props)); _this.onSubmit = function (e) { e.preventDefault(); e.stopPropagation(); if (!(0, _isNaN3.default)(parseFloat(_this.state.from, 10)) && !(0, _isNaN3.default)(parseFloat(_this.state.to, 10))) { _this.props.refine({ min: _this.state.from, max: _this.state.to }); } }; _this.state = _this.props.canRefine ? { from: props.currentRefinement.min, to: props.currentRefinement.max } : { from: '', to: '' }; return _this; } _createClass(RangeInput, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.canRefine) { this.setState({ from: nextProps.currentRefinement.min, to: nextProps.currentRefinement.max }); } if (this.context.canRefine) this.context.canRefine(nextProps.canRefine); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, translate = _props.translate, canRefine = _props.canRefine; return _react2.default.createElement( 'form', _extends({}, cx('root', !canRefine && 'noRefinement'), { onSubmit: this.onSubmit }), _react2.default.createElement( 'fieldset', _extends({ disabled: !canRefine }, cx('fieldset')), _react2.default.createElement( 'label', cx('labelMin'), _react2.default.createElement('input', _extends({}, cx('inputMin'), { type: 'number', value: this.state.from, onChange: function onChange(e) { return _this2.setState({ from: e.target.value }); } })) ), _react2.default.createElement( 'span', cx('separator'), translate('separator') ), _react2.default.createElement( 'label', cx('labelMax'), _react2.default.createElement('input', _extends({}, cx('inputMax'), { type: 'number', value: this.state.to, onChange: function onChange(e) { return _this2.setState({ to: e.target.value }); } })) ), _react2.default.createElement( 'button', _extends({}, cx('submit'), { type: 'submit' }), translate('submit') ) ) ); } }]); return RangeInput; }(_react.Component); RangeInput.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, min: _react.PropTypes.number, max: _react.PropTypes.number, currentRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number, max: _react.PropTypes.number }), canRefine: _react.PropTypes.bool.isRequired }; RangeInput.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ submit: 'ok', separator: 'to' })(RangeInput); /***/ }, /* 362 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Since a lot of sliders already exist, we did not include one by default. * However you can easily connect React InstantSearch to an existing one * using the [connectRange connector](/connectors/connectRange.html). * * @name RangeSlider * @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values. * @kind widget * @example * * // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the * // range connector * * import React, {PropTypes} from 'react'; * import {connectRange} from 'react-instantsearch/connectors'; * import Rheostat from 'rheostat'; * * const Range = React.createClass({ propTypes: { min: React.PropTypes.number.isRequired, max: React.PropTypes.number.isRequired, currentRefinement: React.PropTypes.object.isRequired, refine: React.PropTypes.func.isRequired, }, getInitialState() { return {currentValues: {min: this.props.min, max: this.props.max}}; }, componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}}); } }, onValuesUpdated(sliderState) { this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}}); }, onChange(sliderState) { if (this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1]) { this.props.refine({min: sliderState.values[0], max: sliderState.values[1]}); } }, render() { const {min, max, currentRefinement} = this.props; const {currentValues} = this.state; return ( <div> <Rheostat min={min} max={max} values={[currentRefinement.min, currentRefinement.max]} onChange={this.onChange} onValuesUpdated={this.onValuesUpdated} /> <div style={{display: 'flex', justifyContent: 'space-between'}}> <div>{currentValues.min}</div> <div>{currentValues.max}</div> </div> </div> ); }, }); const ConnectedRange = connectRange(Range); */ exports.default = (0, _connectRange2.default)(function () { return _react2.default.createElement( 'div', null, 'We do not provide any Slider, see the documentation to learn how to connect one easily:', _react2.default.createElement( 'a', { target: '_blank', href: 'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html' }, 'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html' ) ); }); /***/ }, /* 363 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _StarRating = __webpack_require__(364); var _StarRating2 = _interopRequireDefault(_StarRating); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * StarRating lets the user refine search results by clicking on stars. * * The stars are based on the selected `attributeName`. * @requirements The attribute passed to the `attributeName` prop must be holding numerical values. * @name StarRating * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating. * @themeKey ais-StarRating__root - The root component of the widget * @themeKey ais-StarRating__ratingLink - The item link * @themeKey ais-StarRating__ratingLinkSelected - The selected link item * @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item * @themeKey ais-StarRating__ratingIcon - The rating icon * @themeKey ais-StarRating__ratingIconSelected - The selected rating icon * @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon * @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon * @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon * @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon * @themeKey ais-StarRating__ratingLabel - The link label * @themeKey ais-StarRating__ratingLabelSelected - The selected link label * @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label * @themeKey ais-StarRating__ratingCount - The link count * @themeKey ais-StarRating__ratingCountSelected - The selected link count * @themeKey ais-StarRating__ratingCountDisabled - The disabled link count * @themeKey ais-StarRating__noRefinement - present when there is no refinement * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * * import {StarRating, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <StarRating attributeName="rating" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRange2.default)(_StarRating2.default); /***/ }, /* 364 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('StarRating'); var StarRating = function (_Component) { _inherits(StarRating, _Component); function StarRating() { _classCallCheck(this, StarRating); return _possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments)); } _createClass(StarRating, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'onClick', value: function onClick(min, max, e) { e.preventDefault(); e.stopPropagation(); if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) { this.props.refine({ min: this.props.min, max: this.props.max }); } else { this.props.refine({ min: min, max: max }); } } }, { key: 'buildItem', value: function buildItem(_ref) { var max = _ref.max, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, isLastSelectableItem = _ref.isLastSelectableItem; var disabled = !count; var isCurrentMinLower = this.props.currentRefinement.min < lowerBound; var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max; var icons = []; for (var icon = 0; icon < max; icon++) { var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon'; icons.push(_react2.default.createElement('span', _extends({ key: icon }, cx(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled')))); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var StarsWrapper = isLastAndSelect ? 'div' : 'a'; var onClickHandler = isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return _react2.default.createElement( StarsWrapper, _extends({}, cx('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), { disabled: disabled, key: lowerBound }, onClickHandler), icons, _react2.default.createElement( 'span', cx('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'), translate('ratingLabel') ), _react2.default.createElement( 'span', null, ' ' ), _react2.default.createElement( 'span', cx('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'), count ) ); } }, { key: 'render', value: function render() { var _this2 = this; var _props = this.props, translate = _props.translate, refine = _props.refine, min = _props.min, max = _props.max, count = _props.count, createURL = _props.createURL, canRefine = _props.canRefine; var items = []; var _loop = function _loop(i) { var hasCount = !(0, _isEmpty3.default)(count.filter(function (item) { return Number(item.value) === i; })); var lastSelectableItem = count.reduce(function (acc, item) { return item.value < acc.value || !acc.value && hasCount ? item : acc; }, {}); var itemCount = count.reduce(function (acc, item) { return item.value >= i && hasCount ? acc + item.count : acc; }, 0); items.push(_this2.buildItem({ lowerBound: i, max: max, refine: refine, count: itemCount, translate: translate, createURL: createURL, isLastSelectableItem: i === Number(lastSelectableItem.value) })); }; for (var i = max; i >= min; i--) { _loop(i); } return _react2.default.createElement( 'div', cx('root', !canRefine && 'noRefinement'), items ); } }]); return StarRating; }(_react.Component); StarRating.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, min: _react.PropTypes.number, max: _react.PropTypes.number, currentRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number, max: _react.PropTypes.number }), count: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.string, count: _react.PropTypes.number })), canRefine: _react.PropTypes.bool.isRequired }; StarRating.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ ratingLabel: ' & Up' })(StarRating); /***/ }, /* 365 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRefinementList = __webpack_require__(366); var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList); var _RefinementList = __webpack_require__(367); var _RefinementList2 = _interopRequireDefault(_RefinementList); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true` * @propType {string[]} [defaultRefinement] - the values of the items selected by default * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-RefinementList__root - the root of the component * @themeKey ais-RefinementList__items - the container of all items in the list * @themeKey ais-RefinementList__itemSelected - the selected list item * @themeKey ais-RefinementList__itemCheckbox - the item checkbox * @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox * @themeKey ais-RefinementList__itemLabel - the item label * @themeKey ais-RefinementList__itemLabelSelected - the selected item label * @themeKey RefinementList__itemCount - the item count * @themeKey RefinementList__itemCountSelected - the selected item count * @themeKey ais-RefinementList__showMore - the button that let the user toggle more results * @themeKey ais-RefinementList__noRefinement - present when there is no refinement * @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded * @translationkey noResults - The label of the no results text when no search for facet values results are found. * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @example * import React from 'react'; * * import {RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <RefinementList attributeName="colors" /> * </InstantSearch> * ); * } */ exports.default = (0, _connectRefinementList2.default)(_RefinementList2.default); /***/ }, /* 366 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var namespace = 'refinementList'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var subState = searchState[namespace]; if (typeof subState[id] === 'string') { // All items were unselected if (subState[id] === '') { return []; } // Only one item was in the searchState but we know it should be an array return [subState[id]]; } return subState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return []; } function getValue(name, props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); var isAnewValue = currentRefinement.indexOf(name) === -1; var nextRefinement = isAnewValue ? currentRefinement.concat([name]) : // cannot use .push(), it mutates currentRefinement.filter(function (selectedValue) { return selectedValue !== name; }); // cannot use .splice(), it mutates return nextRefinement; } /** * connectRefinementList connector provides the logic to build a widget that will * give the user tha ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attributeName - the name of the attribute in the record * @propType {boolean} [withSearchBox=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limitMin=10] - the minimum number of displayed items * @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy = ['isRefined', 'count:desc', 'name:asc']; exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRefinementList', propTypes: { id: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, operator: _react.PropTypes.oneOf(['and', 'or']), showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, defaultRefinement: _react.PropTypes.arrayOf(_react.PropTypes.string), withSearchBox: _react.PropTypes.bool, searchForFacetValues: _react.PropTypes.bool, // @deprecated transformItems: _react.PropTypes.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var results = searchResults.results; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== ''); var withSearchBox = props.withSearchBox || props.searchForFacetValues; if (false) { // eslint-disable-next-line no-console console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) { return { label: v.name, value: getValue(v.name, props, searchState), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '')))); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, operator = props.operator, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit) }); searchParameters = searchParameters[addKey](attributeName); return getCurrentRefinement(props, searchState).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); return { id: id, items: getCurrentRefinement(props, searchState).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement(props, searchState), value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, items: getCurrentRefinement(props, searchState).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement(props, nextState).filter(function (other) { return other !== item; }); return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, nextSelectedItems.length > 0 ? nextSelectedItems : '')))); } }; }) }] : [] }; } }); /***/ }, /* 367 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); var _pick3 = _interopRequireDefault(_pick2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); var _Highlight = __webpack_require__(325); var _Highlight2 = _interopRequireDefault(_Highlight); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('RefinementList'); var RefinementList = function (_Component) { _inherits(RefinementList, _Component); function RefinementList(props) { _classCallCheck(this, RefinementList); var _this = _possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props)); _this.selectItem = function (item) { _this.props.refine(item.value); }; _this.renderItem = function (item) { var label = _this.props.isFromSearch ? _react2.default.createElement(_Highlight2.default, { attributeName: 'label', hit: item }) : item.label; return _react2.default.createElement( 'label', null, _react2.default.createElement('input', _extends({}, cx('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), { type: 'checkbox', checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item); } })), _react2.default.createElement('span', cx('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')), _react2.default.createElement( 'span', cx('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'), label ), ' ', _react2.default.createElement( 'span', cx('itemCount', item.isRefined && 'itemCountSelected'), item.count ) ); }; _this.state = { query: '' }; return _this; } _createClass(RefinementList, [{ key: 'componentWillMount', value: function componentWillMount() { if (this.context.canRefine) this.context.canRefine(this.props.canRefine); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { if (this.context.canRefine) this.context.canRefine(props.canRefine); } }, { key: 'render', value: function render() { return _react2.default.createElement( 'div', null, _react2.default.createElement(_List2.default, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx }, (0, _pick3.default)(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']))) ); } }]); return RefinementList; }(_react.Component); RefinementList.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, searchForItems: _react.PropTypes.func.isRequired, withSearchBox: _react.PropTypes.bool, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired, count: _react.PropTypes.number.isRequired, isRefined: _react.PropTypes.bool.isRequired })), isFromSearch: _react.PropTypes.bool.isRequired, canRefine: _react.PropTypes.bool.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; RefinementList.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; }, noResults: 'No results', submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(RefinementList); /***/ }, /* 368 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(173); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _ClearAll = __webpack_require__(369); var _ClearAll2 = _interopRequireDefault(_ClearAll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ClearAll widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearAll * @kind widget * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query * @themeKey ais-ClearAll__root - the widget button * @translationKey reset - the clear all button value * @example * import React from 'react'; * * import {ClearAll, RefinementList} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ClearAll /> * <RefinementList attributeName="colors" defaultRefinement={['Black']} /> * </InstantSearch> * ); * } */ exports.default = (0, _connectCurrentRefinements2.default)(_ClearAll2.default); /***/ }, /* 369 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('ClearAll'); var ClearAll = function (_Component) { _inherits(ClearAll, _Component); function ClearAll() { _classCallCheck(this, ClearAll); return _possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments)); } _createClass(ClearAll, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, items = _props.items, refine = _props.refine, query = _props.query; var isDisabled = items.length === 0 && (!query || query === ''); if (isDisabled) { return _react2.default.createElement( 'button', _extends({}, cx('root'), { disabled: true }), translate('reset') ); } return _react2.default.createElement( 'button', _extends({}, cx('root'), { onClick: refine.bind(null, items) }), translate('reset') ); } }]); return ClearAll; }(_react.Component); ClearAll.propTypes = { translate: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired, refine: _react.PropTypes.func.isRequired, query: _react.PropTypes.string }; exports.default = (0, _translatable2.default)({ reset: 'Clear all filters' })(ClearAll); /***/ }, /* 370 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectScrollTo = __webpack_require__(371); var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo); var _ScrollTo = __webpack_require__(372); var _ScrollTo2 = _interopRequireDefault(_ScrollTo); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The ScrollTo component will made the page scroll to the component wrapped by it when one of the * [search state](guide/Search_state.html) prop is updated. By default when the page number changes, * the scroll goes to the wrapped component. * * @name ScrollTo * @kind widget * @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes. * @example * import React from 'react'; * * import {ScrollTo, Hits, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); * } */ exports.default = (0, _connectScrollTo2.default)(_ScrollTo2.default); /***/ }, /* 371 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectScrollTo connector provides the logic to build a widget that will * let the page scroll to a certain point. * @name connectScrollTo * @kind connector * @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget. * @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: _react.PropTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var value = searchState[props.scrollOn]; return { value: value }; } }); /***/ }, /* 372 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _reactDom = __webpack_require__(373); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ScrollTo = function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments)); } _createClass(ScrollTo, [{ key: 'componentDidUpdate', value: function componentDidUpdate(prevProps) { var value = this.props.value; if (value !== prevProps.value) { var el = (0, _reactDom.findDOMNode)(this); el.scrollIntoView(); } } }, { key: 'render', value: function render() { return _react.Children.only(this.props.children); } }]); return ScrollTo; }(_react.Component); ScrollTo.propTypes = { value: _react.PropTypes.any, children: _react.PropTypes.node }; exports.default = ScrollTo; /***/ }, /* 373 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_373__; /***/ }, /* 374 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSearchBox = __webpack_require__(375); var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox); var _SearchBox = __webpack_require__(323); var _SearchBox2 = _interopRequireDefault(_SearchBox); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SearchBox component displays a search box that lets the user search for a specific query. * @name SearchBox * @kind widget * @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes. * @propType {boolean} [autoFocus=false] - Should the search box be focused on render? * @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused. * @themeKey ais-SearchBox__root - the root of the component * @themeKey ais-SearchBox__wrapper - the search box wrapper * @themeKey ais-SearchBox__input - the search box input * @themeKey ais-SearchBox__submit - the submit button * @themeKey ais-SearchBox__reset - the reset button * @translationkey submit - The submit button label * @translationkey reset - The reset button label * @translationkey submitTitle - The submit button title * @translationkey resetTitle - The reset button title * @translationkey placeholder - The label of the input placeholder * @example * import React from 'react'; * * import {SearchBox, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSearchBox2.default)(_SearchBox2.default); /***/ }, /* 375 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _react = __webpack_require__(105); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId() { return 'query'; } function getCurrentRefinement(props, searchState) { var id = getId(); if (typeof searchState[id] !== 'undefined') { return searchState[id]; } if (typeof props.defaultRefinement !== 'undefined') { return props.defaultRefinement; } return ''; } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query. * @name connectSearchBox * @kind connector * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the query to search for. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: _react.PropTypes.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement(props, searchState) }; }, refine: function refine(props, searchState, nextQuery) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextQuery)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState)); } }); /***/ }, /* 376 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSortBy = __webpack_require__(377); var _connectSortBy2 = _interopRequireDefault(_connectSortBy); var _SortBy = __webpack_require__(378); var _SortBy2 = _interopRequireDefault(_SortBy); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The SortBy component displays a list of indexes allowing a user to change the hits are sorting. * @name SortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind widget * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {string} defaultRefinement - The default selected index. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @themeKey ais-SortBy__root - the root of the component * @example * import React from 'react'; * * import {SortBy, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SortBy * items={[ * {value: 'ikea', label: 'Featured'}, * {value: 'ikea_price_asc', label: 'Price asc.'}, * {value: 'ikea_price_desc', label: 'Price desc.'}, * ]} * defaultRefinement="ikea" * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectSortBy2.default)(_SortBy2.default); /***/ }, /* 377 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId() { return 'sortBy'; } function getCurrentRefinement(props, searchState) { var id = getId(); if (searchState[id]) { return searchState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return null; } /** * connectSortBy connector provides the logic to build a widget that will * displays a list of indexes allowing a user to change the hits are sorting. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: _react.PropTypes.string, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.string.isRequired })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextRefinement)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement(props, searchState); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 378 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(339); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('SortBy'); var SortBy = function (_Component) { _inherits(SortBy, _Component); function SortBy() { var _ref; var _temp, _this, _ret; _classCallCheck(this, SortBy); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = SortBy.__proto__ || Object.getPrototypeOf(SortBy)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.value); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(SortBy, [{ key: 'render', value: function render() { var _props = this.props, refine = _props.refine, items = _props.items, currentRefinement = _props.currentRefinement; return _react2.default.createElement(_Select2.default, { cx: cx, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(_react.Component); SortBy.propTypes = { refine: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.string.isRequired })).isRequired, currentRefinement: _react.PropTypes.string.isRequired, transformItems: _react.PropTypes.func }; exports.default = SortBy; /***/ }, /* 379 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectStats = __webpack_require__(380); var _connectStats2 = _interopRequireDefault(_connectStats); var _Stats = __webpack_require__(381); var _Stats2 = _interopRequireDefault(_Stats); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). * @name Stats * @kind widget * @themeKey ais-Stats__root - the root of the component * @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time. * @example * import React from 'react'; * * import {Stats, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Stats /> * </InstantSearch> * ); * } */ exports.default = (0, _connectStats2.default)(_Stats2.default); /***/ }, /* 380 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { if (!searchResults.results) { return null; } return { nbHits: searchResults.results.nbHits, processingTimeMS: searchResults.results.processingTimeMS }; } }); /***/ }, /* 381 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Stats'); var Stats = function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments)); } _createClass(Stats, [{ key: 'render', value: function render() { var _props = this.props, translate = _props.translate, nbHits = _props.nbHits, processingTimeMS = _props.processingTimeMS; return _react2.default.createElement( 'span', cx('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(_react.Component); Stats.propTypes = { translate: _react.PropTypes.func.isRequired, nbHits: _react.PropTypes.number.isRequired, processingTimeMS: _react.PropTypes.number.isRequired }; exports.default = (0, _translatable2.default)({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /***/ }, /* 382 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectToggle = __webpack_require__(383); var _connectToggle2 = _interopRequireDefault(_connectToggle); var _Toggle = __webpack_require__(384); var _Toggle2 = _interopRequireDefault(_Toggle); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name Toggle * @kind widget * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName` when checked. * @propType {boolean} [defaultChecked=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-Toggle__root - the root of the component * @themeKey ais-Toggle__checkbox - the toggle checkbox * @themeKey ais-Toggle__label - the toggle label * @example * import React from 'react'; * * import {Toggle, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Toggle attributeName="materials" * label="Made with solid pine" * value={'Solid pine'} * /> * </InstantSearch> * ); * } */ exports.default = (0, _connectToggle2.default)(_Toggle2.default); /***/ }, /* 383 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function getId(props) { return props.attributeName; } var namespace = 'toggle'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && searchState[namespace][id]) { return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return false; } /** * connectToggle connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization. * @name connectToggle * @kind connector * @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attributeName`. * @propType {boolean} [defaultChecked=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaToggle', propTypes: { label: _react.PropTypes.string, filter: _react.PropTypes.func, attributeName: _react.PropTypes.string, value: _react.PropTypes.any, defaultRefinement: _react.PropTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextChecked) { return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextChecked)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, value = props.value, filter = props.filter; var checked = getCurrentRefinement(props, searchState); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var checked = getCurrentRefinement(props, searchState); var items = []; if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, false)))); } }); } return { id: id, items: items }; } }); /***/ }, /* 384 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Toggle'); var Toggle = function (_Component) { _inherits(Toggle, _Component); function Toggle() { var _ref; var _temp, _this, _ret; _classCallCheck(this, Toggle); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) { _this.props.refine(e.target.checked); }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(Toggle, [{ key: 'render', value: function render() { var _props = this.props, currentRefinement = _props.currentRefinement, label = _props.label; return _react2.default.createElement( 'label', cx('root'), _react2.default.createElement('input', _extends({}, cx('checkbox'), { type: 'checkbox', checked: currentRefinement, onChange: this.onChange })), _react2.default.createElement( 'span', cx('label'), label ) ); } }]); return Toggle; }(_react.Component); Toggle.propTypes = { currentRefinement: _react.PropTypes.bool.isRequired, refine: _react.PropTypes.func.isRequired, label: _react.PropTypes.string.isRequired }; exports.default = Toggle; /***/ }, /* 385 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Panel = __webpack_require__(386); var _Panel2 = _interopRequireDefault(_Panel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The Panel widget wraps other widgets in a consistent panel design. * * It also reacts, indicates and set CSS classes when widgets are no more * relevant for refining. E.g. when a RefinementList becomes empty because of * the current search results. * @name Panel * @kind widget * @propType {string} title - The panel title * @themeKey ais-Panel__root - Container of the widget * @themeKey ais-Panel__title - The panel title * @themeKey ais-Panel__noRefinement - Present if the panel content is empty * @example * import React from 'react'; * * import {Panel, RefinementList, InstantSearch} from '../packages/react-instantsearch/dom'; * * export default function App() { * return ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Panel title="category"> * <RefinementList attributeName="category" /> * </Panel> * </InstantSearch> * ); * } */ exports.default = _Panel2.default; /***/ }, /* 386 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var cx = (0, _classNames2.default)('Panel'); var Panel = function (_Component) { _inherits(Panel, _Component); _createClass(Panel, [{ key: 'getChildContext', value: function getChildContext() { return { canRefine: this.canRefine }; } }]); function Panel(props) { _classCallCheck(this, Panel); var _this = _possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props)); _this.state = { canRefine: true }; _this.canRefine = function (canRefine) { _this.setState({ canRefine: canRefine }); }; return _this; } _createClass(Panel, [{ key: 'render', value: function render() { return _react2.default.createElement( 'div', cx('root', !this.state.canRefine && 'noRefinement'), _react2.default.createElement( 'h5', cx('title'), this.props.title ), this.props.children ); } }]); return Panel; }(_react.Component); Panel.propTypes = { title: _react.PropTypes.string.isRequired, children: _react.PropTypes.node }; Panel.childContextTypes = { canRefine: _react.PropTypes.func }; exports.default = Panel; /***/ }, /* 387 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.default = createInstantSearch; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _InstantSearch = __webpack_require__(388); var _InstantSearch2 = _interopRequireDefault(_InstantSearch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _name$author$descript = { name: 'react-instantsearch', author: { name: 'Algolia, Inc.', url: 'https://www.algolia.com' }, description: '\u26A1 Lightning-fast search for React and React Native apps', version: '3.2.0', scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, homepage: 'https://community.algolia.com/instantsearch.js/react/', repository: { type: 'git', url: 'https://github.com/algolia/instantsearch.js/' }, dependencies: { algoliasearch: '^3.20.3', 'algoliasearch-helper': '^2.18.0', classnames: '^2.2.5', lodash: '^4.17.4' }, license: 'MIT', devDependencies: { enzyme: '^2.7.1', react: '^15.4.2', 'react-dom': '^15.4.2', 'react-native': '^0.41.2', 'react-test-renderer': '^15.4.2' } }; var version = _name$author$descript.version; /** * Creates a specialized root InstantSearch component. It accepts * an algolia client and a specification of the root Element. * @param {function} defaultAlgoliaClient - a function that builds an Algolia client * @param {object} root - the defininition of the root of an InstantSearch sub tree. * @returns {object} an InstantSearch root */ function createInstantSearch(defaultAlgoliaClient, root) { var _class, _temp; return _temp = _class = function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch(props) { _classCallCheck(this, CreateInstantSearch); var _this = _possibleConstructorReturn(this, (CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call(this)); _this.client = props.algoliaClient || defaultAlgoliaClient(props.appId, props.apiKey); _this.client.addAlgoliaAgent('react-instantsearch ' + version); return _this; } _createClass(CreateInstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } this.client.addAlgoliaAgent('react-instantsearch ' + version); } }, { key: 'render', value: function render() { return _react2.default.createElement(_InstantSearch2.default, { createURL: this.props.createURL, indexName: this.props.indexName, searchParameters: this.props.searchParameters, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, root: root, algoliaClient: this.client, children: this.props.children }); } }]); return CreateInstantSearch; }(_react.Component), _class.propTypes = { algoliaClient: _react.PropTypes.object, appId: _react.PropTypes.string, apiKey: _react.PropTypes.string, children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.arrayOf(_react2.default.PropTypes.node), _react2.default.PropTypes.node]), indexName: _react.PropTypes.string.isRequired, searchParameters: _react.PropTypes.object, createURL: _react.PropTypes.func, searchState: _react.PropTypes.object, onSearchStateChange: _react.PropTypes.func }, _temp; } /***/ }, /* 388 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _createInstantSearchManager = __webpack_require__(389); var _createInstantSearchManager2 = _interopRequireDefault(_createInstantSearchManager); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error('You can\'t switch <InstantSearch> from being uncontrolled to controlled'); } else if (props.searchState && !nextProps.searchState) { throw new Error('You can\'t switch <InstantSearch> from being controlled to uncontrolled'); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @example * import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom'; * * export default function Search() { * return ( * <InstantSearch * appId="appId" * apiKey="apiKey" * indexName="indexName" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); * } */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.aisManager = (0, _createInstantSearchManager2.default)({ indexName: props.indexName, searchParameters: props.searchParameters, algoliaClient: props.algoliaClient, initialState: initialState }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this) } }; } return { ais: _extends({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = _react.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return _react2.default.createElement( Root, props, this.props.children ); } }]); return InstantSearch; }(_react.Component); InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: _react.PropTypes.string.isRequired, algoliaClient: _react.PropTypes.object.isRequired, searchParameters: _react.PropTypes.object, createURL: _react.PropTypes.func, searchState: _react.PropTypes.object, onSearchStateChange: _react.PropTypes.func, children: _react.PropTypes.node, root: _react.PropTypes.shape({ Root: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]), props: _react.PropTypes.object }).isRequired }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: _react.PropTypes.object.isRequired }; exports.default = InstantSearch; /***/ }, /* 389 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = createInstantSearchManager; var _algoliasearchHelper = __webpack_require__(181); var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper); var _createWidgetsManager = __webpack_require__(390); var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager); var _createStore = __webpack_require__(391); var _createStore2 = _interopRequireDefault(_createStore); var _highlightTags = __webpack_require__(328); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, algoliaClient = _ref.algoliaClient, _ref$searchParameters = _ref.searchParameters, searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters; var baseSP = new _algoliasearchHelper.SearchParameters(_extends({}, searchParameters, { index: indexName }, _highlightTags2.default)); var helper = (0, _algoliasearchHelper2.default)(algoliaClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); var initialSearchParameters = helper.state; var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate); var store = (0, _createStore2.default)({ widgets: initialState, metadata: [], results: null, error: null, searching: false }); function updateClient(client) { helper.setClient(client); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); } function search() { var widgetSearchParameters = getSearchParameters(helper.state); helper.setState(widgetSearchParameters).search(); } function handleSearchSuccess(content) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { results: content, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(nextSearchState) { store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty(_extends2, nextSearchState.facetName, content.facetHits), _defineProperty(_extends2, 'query', nextSearchState.query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex }; } /***/ }, /* 390 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createWidgetsManager; var _utils = __webpack_require__(106); function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; (0, _utils.defer)(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } /***/ }, /* 391 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createStore; function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } /***/ }, /* 392 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var AlgoliaSearch = __webpack_require__(393); var createAlgoliasearch = __webpack_require__(416); module.exports = createAlgoliasearch(AlgoliaSearch); /***/ }, /* 393 */ /***/ function(module, exports, __webpack_require__) { module.exports = AlgoliaSearch; var Index = __webpack_require__(394); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); var AlgoliaSearchCore = __webpack_require__(411); var inherits = __webpack_require__(395); var errors = __webpack_require__(398); function AlgoliaSearch() { AlgoliaSearchCore.apply(this, arguments); } inherits(AlgoliaSearch, AlgoliaSearchCore); /* * Delete an index * * @param indexName the name of index to delete * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) { return this._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexName), hostType: 'write', callback: callback }); }; /** * Move an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of * srcIndexName (destination will be overriten if it already exist). * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) { var postObj = { operation: 'move', destination: dstIndexName }; return this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, hostType: 'write', callback: callback }); }; /** * Copy an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy * of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, callback) { var postObj = { operation: 'copy', destination: dstIndexName }; return this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, hostType: 'write', callback: callback }); }; /** * Return last log entries. * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry). * @param length Specify the maximum number of entries to retrieve starting * at offset. Maximum allowed value: 1000. * @param type Specify the maximum number of entries to retrieve starting * at offset. Maximum allowed value: 1000. * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.getLogs = function(offset, length, callback) { var clone = __webpack_require__(403); var params = {}; if (typeof offset === 'object') { // getLogs(params) params = clone(offset); callback = length; } else if (arguments.length === 0 || typeof offset === 'function') { // getLogs([cb]) callback = offset; } else if (arguments.length === 1 || typeof length === 'function') { // getLogs(1, [cb)] callback = length; params.offset = offset; } else { // getLogs(1, 2, [cb]) params.offset = offset; params.length = length; } if (params.offset === undefined) params.offset = 0; if (params.length === undefined) params.length = 10; return this._jsonRequest({ method: 'GET', url: '/1/logs?' + this._getSearchParams(params, ''), hostType: 'read', callback: callback }); }; /* * List all existing indexes (paginated) * * @param page The page to retrieve, starting at 0. * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with index list */ AlgoliaSearch.prototype.listIndexes = function(page, callback) { var params = ''; if (page === undefined || typeof page === 'function') { callback = page; } else { params = '?page=' + page; } return this._jsonRequest({ method: 'GET', url: '/1/indexes' + params, hostType: 'read', callback: callback }); }; /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearch.prototype.initIndex = function(indexName) { return new Index(this, indexName); }; /* * List all existing user keys with their associated ACLs * * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.listUserKeys = function(callback) { return this._jsonRequest({ method: 'GET', url: '/1/keys', hostType: 'read', callback: callback }); }; /* * Get ACL of a user key * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.getUserKeyACL = function(key, callback) { return this._jsonRequest({ method: 'GET', url: '/1/keys/' + key, hostType: 'read', callback: callback }); }; /* * Delete an existing user key * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.deleteUserKey = function(key, callback) { return this._jsonRequest({ method: 'DELETE', url: '/1/keys/' + key, hostType: 'write', callback: callback }); }; /* * Add a new global API key * * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string[]} params.indexes - Allowed targeted indexes for this key * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * client.addUserKey(['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * indexes: ['fruits'], * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation} */ AlgoliaSearch.prototype.addUserKey = function(acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.addUserKey(arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 1 || typeof params === 'function') { callback = params; params = null; } var postObj = { acl: acls }; if (params) { postObj.validity = params.validity; postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; postObj.maxHitsPerQuery = params.maxHitsPerQuery; postObj.indexes = params.indexes; postObj.description = params.description; if (params.queryParameters) { postObj.queryParameters = this._getSearchParams(params.queryParameters, ''); } postObj.referers = params.referers; } return this._jsonRequest({ method: 'POST', url: '/1/keys', body: postObj, hostType: 'write', callback: callback }); }; /** * Add a new global API key * @deprecated Please use client.addUserKey() */ AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) { return this.addUserKey(acls, params, callback); }, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addUserKey()')); /** * Update an existing API key * @param {string} key - The key to update * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string[]} params.indexes - Allowed targeted indexes for this key * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * client.updateUserKey('APIKEY', ['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * indexes: ['fruits'], * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation} */ AlgoliaSearch.prototype.updateUserKey = function(key, acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 2 || typeof params === 'function') { callback = params; params = null; } var putObj = { acl: acls }; if (params) { putObj.validity = params.validity; putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; putObj.maxHitsPerQuery = params.maxHitsPerQuery; putObj.indexes = params.indexes; putObj.description = params.description; if (params.queryParameters) { putObj.queryParameters = this._getSearchParams(params.queryParameters, ''); } putObj.referers = params.referers; } return this._jsonRequest({ method: 'PUT', url: '/1/keys/' + key, body: putObj, hostType: 'write', callback: callback }); }; /** * Initialize a new batch of search queries * @deprecated use client.search() */ AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() { this._batch = []; }, deprecatedMessage('client.startQueriesBatch()', 'client.search()')); /** * Add a search query in the batch * @deprecated use client.search() */ AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) { this._batch.push({ indexName: indexName, query: query, params: args }); }, deprecatedMessage('client.addQueryInBatch()', 'client.search()')); /** * Launch the batch of queries using XMLHttpRequest. * @deprecated use client.search() */ AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) { return this.search(this._batch, callback); }, deprecatedMessage('client.sendQueriesBatch()', 'client.search()')); /** * Perform write operations accross multiple indexes. * * To reduce the amount of time spent on network round trips, * you can create, update, or delete several objects in one call, * using the batch endpoint (all operations are done in the given order). * * Available actions: * - addObject * - updateObject * - partialUpdateObject * - partialUpdateObjectNoCreate * - deleteObject * * https://www.algolia.com/doc/rest_api#Indexes * @param {Object[]} operations An array of operations to perform * @return {Promise|undefined} Returns a promise if no callback given * @example * client.batch([{ * action: 'addObject', * indexName: 'clients', * body: { * name: 'Bill' * } * }, { * action: 'udpateObject', * indexName: 'fruits', * body: { * objectID: '29138', * name: 'banana' * } * }], cb) */ AlgoliaSearch.prototype.batch = function(operations, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.batch(operations[, callback])'; if (!isArray(operations)) { throw new Error(usage); } return this._jsonRequest({ method: 'POST', url: '/1/indexes/*/batch', body: { requests: operations }, hostType: 'write', callback: callback }); }; // environment specific methods AlgoliaSearch.prototype.destroy = notImplemented; AlgoliaSearch.prototype.enableRateLimitForward = notImplemented; AlgoliaSearch.prototype.disableRateLimitForward = notImplemented; AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented; AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented; AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented; function notImplemented() { var message = 'Not implemented in this environment.\n' + 'If you feel this is a mistake, write to [email protected]'; throw new errors.AlgoliaSearchError(message); } /***/ }, /* 394 */ /***/ function(module, exports, __webpack_require__) { var inherits = __webpack_require__(395); var IndexCore = __webpack_require__(396); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); var exitPromise = __webpack_require__(409); var errors = __webpack_require__(398); var deprecateForwardToSlaves = deprecate( function() {}, deprecatedMessage('forwardToSlaves', 'forwardToReplicas') ); module.exports = Index; function Index() { IndexCore.apply(this, arguments); } inherits(Index, IndexCore); /* * Add an object in this index * * @param content contains the javascript object to add inside the index * @param objectID (optional) an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.addObject = function(content, objectID, callback) { var indexObj = this; if (arguments.length === 1 || typeof objectID === 'function') { callback = objectID; objectID = undefined; } return this.as._jsonRequest({ method: objectID !== undefined ? 'PUT' : // update or create 'POST', // create (API generates an objectID) url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create (objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create body: content, hostType: 'write', callback: callback }); }; /* * Add several objects * * @param objects contains an array of objects to add * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.addObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'addObject', body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Update partially an object (only update attributes passed in argument) * * @param partialObject contains the javascript attributes to override, the * object must contains an objectID attribute * @param createIfNotExists (optional) if false, avoid an automatic creation of the object * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) { if (arguments.length === 1 || typeof createIfNotExists === 'function') { callback = createIfNotExists; createIfNotExists = undefined; } var indexObj = this; var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial'; if (createIfNotExists === false) { url += '?createIfNotExists=false'; } return this.as._jsonRequest({ method: 'POST', url: url, body: partialObject, hostType: 'write', callback: callback }); }; /* * Partially Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.partialUpdateObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'partialUpdateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Override the content of object * * @param object contains the javascript object to save, the object must contains an objectID attribute * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.saveObject = function(object, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID), body: object, hostType: 'write', callback: callback }); }; /* * Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.saveObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'updateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Delete an object from the index * * @param objectID the unique identifier of object to delete * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.deleteObject = function(objectID, callback) { if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') { var err = new errors.AlgoliaSearchError('Cannot delete an object without an objectID'); callback = objectID; if (typeof callback === 'function') { return callback(err); } return this.as._promise.reject(err); } var indexObj = this; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), hostType: 'write', callback: callback }); }; /* * Delete several objects from an index * * @param objectIDs contains an array of objectID to delete * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.deleteObjects = function(objectIDs, callback) { var isArray = __webpack_require__(407); var map = __webpack_require__(408); var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: map(objectIDs, function prepareRequest(objectID) { return { action: 'deleteObject', objectID: objectID, body: { objectID: objectID } }; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Delete all objects matching a query * * @param query the query string * @param params the optional query parameters * @param callback (optional) the result callback called with one argument * error: null or Error('message') */ Index.prototype.deleteByQuery = function(query, params, callback) { var clone = __webpack_require__(403); var map = __webpack_require__(408); var indexObj = this; var client = indexObj.as; if (arguments.length === 1 || typeof params === 'function') { callback = params; params = {}; } else { params = clone(params); } params.attributesToRetrieve = 'objectID'; params.hitsPerPage = 1000; params.distinct = false; // when deleting, we should never use cache to get the // search results this.clearCache(); // there's a problem in how we use the promise chain, // see how waitTask is done var promise = this .search(query, params) .then(stopOrDelete); function stopOrDelete(searchContent) { // stop here if (searchContent.nbHits === 0) { // return indexObj.as._request.resolve(); return searchContent; } // continue and do a recursive call var objectIDs = map(searchContent.hits, function getObjectID(object) { return object.objectID; }); return indexObj .deleteObjects(objectIDs) .then(waitTask) .then(doDeleteByQuery); } function waitTask(deleteObjectsContent) { return indexObj.waitTask(deleteObjectsContent.taskID); } function doDeleteByQuery() { return indexObj.deleteByQuery(query, params); } if (!callback) { return promise; } promise.then(success, failure); function success() { exitPromise(function exit() { callback(null); }, client._setTimeout || setTimeout); } function failure(err) { exitPromise(function exit() { callback(err); }, client._setTimeout || setTimeout); } }; /* * Browse all content from an index using events. Basically this will do * .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @return {EventEmitter} * @example * var browser = index.browseAll('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }); * * browser.on('result', function resultCallback(content) { * console.log(content.hits); * }); * * // if any error occurs, you get it * browser.on('error', function(err) { * throw err; * }); * * // when you have browsed the whole index, you get this event * browser.on('end', function() { * console.log('finished'); * }); * * // at any point if you want to stop the browsing process, you can stop it manually * // otherwise it will go on and on * browser.stop(); * * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ Index.prototype.browseAll = function(query, queryParameters) { if (typeof query === 'object') { queryParameters = query; query = undefined; } var merge = __webpack_require__(402); var IndexBrowser = __webpack_require__(410); var browser = new IndexBrowser(); var client = this.as; var index = this; var params = client._getSearchParams( merge({}, queryParameters || {}, { query: query }), '' ); // start browsing browseLoop(); function browseLoop(cursor) { if (browser._stopped) { return; } var queryString; if (cursor !== undefined) { queryString = 'cursor=' + encodeURIComponent(cursor); } else { queryString = params; } client._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse?' + queryString, hostType: 'read', callback: browseCallback }); } function browseCallback(err, content) { if (browser._stopped) { return; } if (err) { browser._error(err); return; } browser._result(content); // no cursor means we are finished browsing if (content.cursor === undefined) { browser._end(); return; } browseLoop(content.cursor); } return browser; }; /* * Get a Typeahead.js adapter * @param searchParams contains an object with query parameters (see search for details) */ Index.prototype.ttAdapter = function(params) { var self = this; return function ttAdapter(query, syncCb, asyncCb) { var cb; if (typeof asyncCb === 'function') { // typeahead 0.11 cb = asyncCb; } else { // pre typeahead 0.11 cb = syncCb; } self.search(query, params, function searchDone(err, content) { if (err) { cb(err); return; } cb(content.hits); }); }; }; /* * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param callback the result callback with with two arguments: * error: null or Error('message') * content: the server answer that contains the list of results */ Index.prototype.waitTask = function(taskID, callback) { // wait minimum 100ms before retrying var baseDelay = 100; // wait maximum 5s before retrying var maxDelay = 5000; var loop = 0; // waitTask() must be handled differently from other methods, // it's a recursive method using a timeout var indexObj = this; var client = indexObj.as; var promise = retryLoop(); function retryLoop() { return client._jsonRequest({ method: 'GET', hostType: 'read', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID }).then(function success(content) { loop++; var delay = baseDelay * loop * loop; if (delay > maxDelay) { delay = maxDelay; } if (content.status !== 'published') { return client._promise.delay(delay).then(retryLoop); } return content; }); } if (!callback) { return promise; } promise.then(successCb, failureCb); function successCb(content) { exitPromise(function exit() { callback(null, content); }, client._setTimeout || setTimeout); } function failureCb(err) { exitPromise(function exit() { callback(err); }, client._setTimeout || setTimeout); } }; /* * This function deletes the index content. Settings and index specific API keys are kept untouched. * * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the settings object or the error message if a failure occured */ Index.prototype.clearIndex = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear', hostType: 'write', callback: callback }); }; /* * Get settings of this index * * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the settings object or the error message if a failure occured */ Index.prototype.getSettings = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?getVersion=2', hostType: 'read', callback: callback }); }; Index.prototype.searchSynonyms = function(params, callback) { if (typeof params === 'function') { callback = params; params = {}; } else if (params === undefined) { params = {}; } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search', body: params, hostType: 'read', callback: callback }); }; Index.prototype.saveSynonym = function(synonym, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) + '?forwardToReplicas=' + forwardToReplicas, body: synonym, hostType: 'write', callback: callback }); }; Index.prototype.getSynonym = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; Index.prototype.deleteSynonym = function(objectID, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) + '?forwardToReplicas=' + forwardToReplicas, hostType: 'write', callback: callback }); }; Index.prototype.clearSynonyms = function(opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' + '?forwardToReplicas=' + forwardToReplicas, hostType: 'write', callback: callback }); }; Index.prototype.batchSynonyms = function(synonyms, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' + '?forwardToReplicas=' + forwardToReplicas + '&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'), hostType: 'write', body: synonyms, callback: callback }); }; /* * Set settings for this index * * @param settigns the settings object that can contains : * - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3). * - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7). * - hitsPerPage: (integer) the number of hits per page (default = 10). * - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects. * If set to null, all attributes are retrieved. * - attributesToHighlight: (array of strings) default list of attributes to highlight. * If set to null, all indexed attributes are highlighted. * - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number * of words to return (syntax is attributeName:nbWords). * By default no snippet is computed. If set to null, no snippet is computed. * - attributesToIndex: (array of strings) the list of fields you want to index. * If set to null, all textual and numerical attributes of your objects are indexed, * but you should update it to get optimal results. * This parameter has two important uses: * - Limit the attributes to index: For example if you store a binary image in base64, * you want to store it and be able to * retrieve it but you don't want to search in the base64 string. * - Control part of the ranking*: (see the ranking parameter for full explanation) * Matches in attributes at the beginning of * the list will be considered more important than matches in attributes further down the list. * In one attribute, matching text at the beginning of the attribute will be * considered more important than text after, you can disable * this behavior if you add your attribute inside `unordered(AttributeName)`, * for example attributesToIndex: ["title", "unordered(text)"]. * - attributesForFaceting: (array of strings) The list of fields you want to use for faceting. * All strings in the attribute selected for faceting are extracted and added as a facet. * If set to null, no attribute is used for faceting. * - attributeForDistinct: (string) The attribute name used for the Distinct feature. * This feature is similar to the SQL "distinct" keyword: when enabled * in query with the distinct=1 parameter, all hits containing a duplicate * value for this attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best one is kept and others are removed. * - ranking: (array of strings) controls the way results are sorted. * We have six available criteria: * - typo: sort according to number of typos, * - geo: sort according to decreassing distance when performing a geo-location based search, * - proximity: sort according to the proximity of query words in hits, * - attribute: sort according to the order of attributes defined by attributesToIndex, * - exact: * - if the user query contains one word: sort objects having an attribute * that is exactly the query word before others. * For example if you search for the "V" TV show, you want to find it * with the "V" query and avoid to have all popular TV * show starting by the v letter before it. * - if the user query contains multiple words: sort according to the * number of words that matched exactly (and not as a prefix). * - custom: sort according to a user defined formula set in **customRanking** attribute. * The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"] * - customRanking: (array of strings) lets you specify part of the ranking. * The syntax of this condition is an array of strings containing attributes * prefixed by asc (ascending order) or desc (descending order) operator. * For example `"customRanking" => ["desc(population)", "asc(name)"]` * - queryType: Select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - highlightPreTag: (string) Specify the string that is inserted before * the highlighted parts in the query result (default to "<em>"). * - highlightPostTag: (string) Specify the string that is inserted after * the highlighted parts in the query result (default to "</em>"). * - optionalWords: (array of strings) Specify a list of words that should * be considered as optional when found in the query. * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the server answer or the error message if a failure occured */ Index.prototype.setSettings = function(settings, opts, callback) { if (arguments.length === 1 || typeof opts === 'function') { callback = opts; opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; var indexObj = this; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToReplicas=' + forwardToReplicas, hostType: 'write', body: settings, callback: callback }); }; /* * List all existing user keys associated to this index * * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.listUserKeys = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', hostType: 'read', callback: callback }); }; /* * Get ACL of a user key associated to this index * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.getUserKeyACL = function(key, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, hostType: 'read', callback: callback }); }; /* * Delete an existing user key associated to this index * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.deleteUserKey = function(key, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, hostType: 'write', callback: callback }); }; /* * Add a new API key to this index * * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will * be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * index.addUserKey(['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation} */ Index.prototype.addUserKey = function(acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.addUserKey(arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 1 || typeof params === 'function') { callback = params; params = null; } var postObj = { acl: acls }; if (params) { postObj.validity = params.validity; postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; postObj.maxHitsPerQuery = params.maxHitsPerQuery; postObj.description = params.description; if (params.queryParameters) { postObj.queryParameters = this.as._getSearchParams(params.queryParameters, ''); } postObj.referers = params.referers; } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys', body: postObj, hostType: 'write', callback: callback }); }; /** * Add an existing user key associated to this index * @deprecated use index.addUserKey() */ Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) { return this.addUserKey(acls, params, callback); }, deprecatedMessage('index.addUserKeyWithValidity()', 'index.addUserKey()')); /** * Update an existing API key of this index * @param {string} key - The key to update * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will * be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * index.updateUserKey('APIKEY', ['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation} */ Index.prototype.updateUserKey = function(key, acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 2 || typeof params === 'function') { callback = params; params = null; } var putObj = { acl: acls }; if (params) { putObj.validity = params.validity; putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; putObj.maxHitsPerQuery = params.maxHitsPerQuery; putObj.description = params.description; if (params.queryParameters) { putObj.queryParameters = this.as._getSearchParams(params.queryParameters, ''); } putObj.referers = params.referers; } return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key, body: putObj, hostType: 'write', callback: callback }); }; /***/ }, /* 395 */ /***/ function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }, /* 396 */ /***/ function(module, exports, __webpack_require__) { var buildSearchMethod = __webpack_require__(397); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); module.exports = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param query the full text query * @param args (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param callback the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param query the similar query * @param args (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = buildSearchMethod('similarQuery'); /* * Browse index content. The response content will have a `cursor` property that you can use * to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browse('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }, callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browse = function(query, queryParameters, callback) { var merge = __webpack_require__(402); var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + params, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(cursor), hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone = __webpack_require__(403); var omit = __webpack_require__(404); var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])'; if (params.facetName === undefined || params.facetQuery === undefined) { throw new Error(usage); } var facetName = params.facetName; var filteredParams = omit(clone(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occured */ IndexCore.prototype.getObject = function(objectID, attrs, callback) { var indexObj = this; if (arguments.length === 1 || typeof attrs === 'function') { callback = attrs; attrs = undefined; } var params = ''; if (attrs !== undefined) { params = '?attributes='; for (var i = 0; i < attrs.length; ++i) { if (i !== 0) { params += ','; } params += attrs[i]; } } return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, hostType: 'read', callback: callback }); }; /* * Get several objects from this index * * @param objectIDs the array of unique identifier of objects to retrieve */ IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) { var isArray = __webpack_require__(407); var map = __webpack_require__(408); var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; if (arguments.length === 1 || typeof attributesToRetrieve === 'function') { callback = attributesToRetrieve; attributesToRetrieve = undefined; } var body = { requests: map(objectIDs, function prepareRequest(objectID) { var request = { indexName: indexObj.indexName, objectID: objectID }; if (attributesToRetrieve) { request.attributesToRetrieve = attributesToRetrieve.join(','); } return request; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/*/objects', hostType: 'read', body: body, callback: callback }); }; IndexCore.prototype.as = null; IndexCore.prototype.indexName = null; IndexCore.prototype.typeAheadArgs = null; IndexCore.prototype.typeAheadValueOption = null; /***/ }, /* 397 */ /***/ function(module, exports, __webpack_require__) { module.exports = buildSearchMethod; var errors = __webpack_require__(398); function buildSearchMethod(queryParam, url) { return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } if (arguments.length === 0 || typeof query === 'function') { // .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // .search(query/args), .search(query, cb) callback = args; args = undefined; } // .search(args), careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } if (args !== undefined) { // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback); }; } /***/ }, /* 398 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // This file hosts our error definitions // We use custom error "types" so that we can act on them when we need it // e.g.: if error instanceof errors.UnparsableJSON then.. var inherits = __webpack_require__(395); function AlgoliaSearchError(message, extraProperties) { var forEach = __webpack_require__(399); var error = this; // try to get a stacktrace if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old'; } this.name = 'AlgoliaSearchError'; this.message = message || 'Unknown error'; if (extraProperties) { forEach(extraProperties, function addToErrorObject(value, key) { error[key] = value; }); } } inherits(AlgoliaSearchError, Error); function createCustomError(name, message) { function AlgoliaSearchCustomError() { var args = Array.prototype.slice.call(arguments, 0); // custom message not set, use default if (typeof args[0] !== 'string') { args.unshift(message); } AlgoliaSearchError.apply(this, args); this.name = 'AlgoliaSearch' + name + 'Error'; } inherits(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place module.exports = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timedout before getting a response' ), Network: createCustomError( 'Network', 'Network issue, see err.more for details' ), JSONPScriptFail: createCustomError( 'JSONPScriptFail', '<script> was loaded but did not call our provided callback' ), JSONPScriptError: createCustomError( 'JSONPScriptError', '<script> unable to load due to an `error` event on it' ), Unknown: createCustomError( 'Unknown', 'Unknown error occured' ) }; /***/ }, /* 399 */ /***/ function(module, exports) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }, /* 400 */ /***/ function(module, exports) { module.exports = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.log(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; /***/ }, /* 401 */ /***/ function(module, exports) { module.exports = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace('.', '') .replace('()', ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#' + githubAnchorLink; }; /***/ }, /* 402 */ /***/ function(module, exports, __webpack_require__) { var foreach = __webpack_require__(399); module.exports = function merge(destination/* , sources */) { var sources = Array.prototype.slice.call(arguments); foreach(sources, function(source) { for (var keyName in source) { if (source.hasOwnProperty(keyName)) { if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') { destination[keyName] = merge({}, destination[keyName], source[keyName]); } else if (source[keyName] !== undefined) { destination[keyName] = source[keyName]; } } } }); return destination; }; /***/ }, /* 403 */ /***/ function(module, exports) { module.exports = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; /***/ }, /* 404 */ /***/ function(module, exports, __webpack_require__) { module.exports = function omit(obj, test) { var keys = __webpack_require__(405); var foreach = __webpack_require__(399); var filtered = {}; foreach(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; /***/ }, /* 405 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(406); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }, /* 406 */ /***/ function(module, exports) { 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }, /* 407 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }, /* 408 */ /***/ function(module, exports, __webpack_require__) { var foreach = __webpack_require__(399); module.exports = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; /***/ }, /* 409 */ /***/ function(module, exports) { // Parse cloud does not supports setTimeout // We do not store a setTimeout reference in the client everytime // We only fallback to a fake setTimeout when not available // setTimeout cannot be override globally sadly module.exports = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; /***/ }, /* 410 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // This is the object returned by the `index.browseAll()` method module.exports = IndexBrowser; var inherits = __webpack_require__(395); var EventEmitter = __webpack_require__(303).EventEmitter; function IndexBrowser() { } inherits(IndexBrowser, EventEmitter); IndexBrowser.prototype.stop = function() { this._stopped = true; this._clean(); }; IndexBrowser.prototype._end = function() { this.emit('end'); this._clean(); }; IndexBrowser.prototype._error = function(err) { this.emit('error', err); this._clean(); }; IndexBrowser.prototype._result = function(content) { this.emit('result', content); }; IndexBrowser.prototype._clean = function() { this.removeAllListeners('stop'); this.removeAllListeners('end'); this.removeAllListeners('error'); this.removeAllListeners('result'); }; /***/ }, /* 411 */ /***/ function(module, exports, __webpack_require__) { module.exports = AlgoliaSearchCore; var errors = __webpack_require__(398); var exitPromise = __webpack_require__(409); var IndexCore = __webpack_require__(396); var store = __webpack_require__(412); // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = ({"NODE_ENV":"production"}).RESET_APP_DATA_TIMER && parseInt(({"NODE_ENV":"production"}).RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API. * Set to 'https:' to force using https. * Default to document.location.protocol in browsers * @param {Object|Array} [opts.hosts={ * read: [this.applicationID + '-dsn.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]), * write: [this.applicationID + '.algolia.net'].concat([ * this.applicationID + '-1.algolianet.com', * this.applicationID + '-2.algolianet.com', * this.applicationID + '-3.algolianet.com'] * ]) - The hosts to use for Algolia Search API. * If you provide them, you will less benefit from our HA implementation */ function AlgoliaSearchCore(applicationID, apiKey, opts) { var debug = __webpack_require__(413)('algoliasearch'); var clone = __webpack_require__(403); var isArray = __webpack_require__(407); var map = __webpack_require__(408); var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)'; if (opts._allowEmptyCredentials !== true && !applicationID) { throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage); } if (opts._allowEmptyCredentials !== true && !apiKey) { throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage); } this.applicationID = applicationID; this.apiKey = apiKey; this.hosts = { read: [], write: [] }; opts = opts || {}; var protocol = opts.protocol || 'https:'; this._timeouts = opts.timeouts || { connect: 1 * 1000, // 500ms connect is GPRS latency read: 2 * 1000, write: 30 * 1000 }; // backward compat, if opts.timeout is passed, we use it to configure all timeouts like before if (opts.timeout) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout; } // while we advocate for colon-at-the-end values: 'http:' for `opts.protocol` // we also accept `http` and `https`. It's a common error. if (!/:$/.test(protocol)) { protocol = protocol + ':'; } if (opts.protocol !== 'http:' && opts.protocol !== 'https:') { throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)'); } this._checkAppIdData(); if (!opts.hosts) { var defaultHosts = map(this._shuffleResult, function(hostNumber) { return applicationID + '-' + hostNumber + '.algolianet.com'; }); // no hosts given, compute defaults this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts); this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts); } else if (isArray(opts.hosts)) { // when passing custom hosts, we need to have a different host index if the number // of write/read hosts are different. this.hosts.read = clone(opts.hosts); this.hosts.write = clone(opts.hosts); } else { this.hosts.read = clone(opts.hosts.read); this.hosts.write = clone(opts.hosts.write); } // add protocol and lowercase hosts this.hosts.read = map(this.hosts.read, prepareHost(protocol)); this.hosts.write = map(this.hosts.write, prepareHost(protocol)); this.extraHeaders = []; // In some situations you might want to warm the cache this.cache = opts._cache || {}; this._ua = opts._ua; this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache; this._useFallback = opts.useFallback === undefined ? true : opts.useFallback; this._setTimeout = opts._setTimeout; debug('init done, %j', this); } /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearchCore.prototype.initIndex = function(indexName) { return new IndexCore(this, indexName); }; /** * Add an extra field to the HTTP request * * @param name the header field name * @param value the header field value */ AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) { this.extraHeaders.push({ name: name.toLowerCase(), value: value }); }; /** * Augment sent x-algolia-agent with more data, each agent part * is automatically separated from the others by a semicolon; * * @param algoliaAgent the agent to add */ AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) { if (this._ua.indexOf(';' + algoliaAgent) === -1) { this._ua += ';' + algoliaAgent; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = __webpack_require__(413)('algoliasearch:' + initialOpts.url); var body; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders(false); } else { headers = this._computeRequestHeaders(); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); var cacheID; if (client._useCache) { cacheID = initialOpts.url; } // as we sometime use POST requests to pass parameters (like query='aa'), // the cacheID must also include the body to be different between calls if (client._useCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (client._useCache && cache && cache[cacheID] !== undefined) { requestDebug('serving response from cache'); return client._promise.resolve(JSON.parse(cache[cacheID])); } // if we reached max tries if (tries >= client.hosts[initialOpts.hostType].length) { if (!hasFallback || usingFallback) { requestDebug('could not get any response'); // then stop return client._promise.reject(new errors.AlgoliaSearchError( 'Cannot connect to the AlgoliaSearch API.' + ' Send an email to [email protected] to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); client._setHostIndexByType(0, initialOpts.hostType); usingFallback = true; // the current request is now using fallback return doRequest(client._request.fallback, reqOpts); } var currentHost = client._getHostByType(initialOpts.hostType); var url = currentHost + reqOpts.url; var options = { body: reqOpts.body, jsonBody: reqOpts.jsonBody, method: reqOpts.method, headers: headers, timeouts: reqOpts.timeouts, debug: requestDebug }; requestDebug('method: %s, url: %s, headers: %j, timeouts: %d', options.method, url, options.headers, options.timeouts); if (requester === client._request.fallback) { requestDebug('using fallback'); } // `requester` is any of this._request or this._request.fallback // thus it needs to be called using the client as context return requester.call(client, url, options).then(success, tryFallback); function success(httpResponse) { // compute the status of the response, // // When in browser mode, using XDR or JSONP, we have no statusCode available // So we rely on our API response `status` property. // But `waitTask` can set a `status` property which is not the statusCode (it's the task status) // So we check if there's a `message` along `status` and it means it's an error // // That's the only case where we have a response.status that's not the http statusCode var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status || // this is important to check the request statusCode AFTER the body eventual // statusCode because some implementations (jQuery XDomainRequest transport) may // send statusCode 200 while we had an error httpResponse.statusCode || // When in browser mode, using XDR or JSONP // we default to success when no error (no response.status && response.message) // If there was a JSON.parse() error then body is null and it fails httpResponse && httpResponse.body && 200; requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j', httpResponse.statusCode, status, httpResponse.headers); var httpResponseOk = Math.floor(status / 100) === 2; var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime, statusCode: status }); if (httpResponseOk) { if (client._useCache && cache) { cache[cacheID] = httpResponse.responseText; } return httpResponse.body; } var shouldRetry = Math.floor(status / 100) !== 4; if (shouldRetry) { tries += 1; return retryRequest(); } requestDebug('unrecoverable error'); // no success and no retry => fail var unrecoverableError = new errors.AlgoliaSearchError( httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status} ); return client._promise.reject(unrecoverableError); } function tryFallback(err) { // error cases: // While not in fallback mode: // - CORS not supported // - network error // While in fallback mode: // - timeout // - network error // - badly formatted JSONP (script loaded, did not call our callback) // In both cases: // - uncaught exception occurs (TypeError) requestDebug('error: %s, stack: %s', err.message, err.stack); var endTime = new Date(); debugData.push({ currentHost: currentHost, headers: removeCredentials(headers), content: body || null, contentLength: body !== undefined ? body.length : null, method: reqOpts.method, timeouts: reqOpts.timeouts, url: reqOpts.url, startTime: startTime, endTime: endTime, duration: endTime - startTime }); if (!(err instanceof errors.AlgoliaSearchError)) { err = new errors.Unknown(err && err.message, err); } tries += 1; // stop the request implementation when: if ( // we did not generate this error, // it comes from a throw in some other piece of code err instanceof errors.Unknown || // server sent unparsable JSON err instanceof errors.UnparsableJSON || // max tries and already using fallback or no fallback tries >= client.hosts[initialOpts.hostType].length && (usingFallback || !hasFallback)) { // stop request implementation for this command err.debugData = debugData; return client._promise.reject(err); } // When a timeout occured, retry by raising timeout if (err instanceof errors.RequestTimeout) { return retryRequestWithHigherTimeout(); } return retryRequest(); } function retryRequest() { requestDebug('retrying request'); client._incrementHostIndex(initialOpts.hostType); return doRequest(requester, reqOpts); } function retryRequestWithHigherTimeout() { requestDebug('retrying request with higher timeout'); client._incrementHostIndex(initialOpts.hostType); client._incrementTimeoutMultipler(); reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType); return doRequest(requester, reqOpts); } } var promise = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType) } ); // either we have a callback // either we are using promises if (initialOpts.callback) { promise.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, content); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { return promise; } }; /* * Transform search param object in query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; AlgoliaSearchCore.prototype._computeRequestHeaders = function(withAPIKey) { var forEach = __webpack_require__(399); var requestHeaders = { 'x-algolia-agent': this._ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (withAPIKey !== false) { requestHeaders['x-algolia-api-key'] = this.apiKey; } if (this.userToken) { requestHeaders['x-algolia-usertoken'] = this.userToken; } if (this.securityTags) { requestHeaders['x-algolia-tagfilters'] = this.securityTags; } if (this.extraHeaders) { forEach(this.extraHeaders, function addToRequestHeaders(header) { requestHeaders[header.name] = header.value; }); } return requestHeaders; }; /** * Search through multiple indices at the same time * @param {Object[]} queries An array of queries you want to run. * @param {string} queries[].indexName The index name you want to target * @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params` * @param {Object} queries[].params Any search param like hitsPerPage, .. * @param {Function} callback Callback to be called * @return {Promise|undefined} Returns a promise if no callback given */ AlgoliaSearchCore.prototype.search = function(queries, opts, callback) { var isArray = __webpack_require__(407); var map = __webpack_require__(408); var usage = 'Usage: client.search(arrayOfQueries[, callback])'; if (!isArray(queries)) { throw new Error(usage); } if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } var client = this; var postObj = { requests: map(queries, function prepareRequest(query) { var params = ''; // allow query.query // so we are mimicing the index.search(query, params) method // {indexName:, query:, params:} if (query.query !== undefined) { params += 'query=' + encodeURIComponent(query.query); } return { indexName: query.indexName, params: client._getSearchParams(query.params, params) }; }) }; var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) { return requestId + '=' + encodeURIComponent( '/1/indexes/' + encodeURIComponent(request.indexName) + '?' + request.params ); }).join('&'); var url = '/1/indexes/*/queries'; if (opts.strategy !== undefined) { url += '?strategy=' + opts.strategy; } return this._jsonRequest({ cache: this.cache, method: 'POST', url: url, body: postObj, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/*', body: { params: JSONPParams } }, callback: callback }); }; /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ AlgoliaSearchCore.prototype.setSecurityTags = function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.securityTags = tags; }; /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ AlgoliaSearchCore.prototype.setUserToken = function(userToken) { this.userToken = userToken; }; /** * Clear all queries in client's cache * @return undefined */ AlgoliaSearchCore.prototype.clearCache = function() { this.cache = {}; }; /** * Set the number of milliseconds a request can take before automatically being terminated. * @deprecated * @param {Number} milliseconds */ AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) { if (milliseconds) { this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds; } }; /** * Set the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) { this._timeouts = timeouts; }; /** * Get the three different (connect, read, write) timeouts to be used when requesting * @param {Object} timeouts */ AlgoliaSearchCore.prototype.getTimeouts = function() { return this._timeouts; }; AlgoliaSearchCore.prototype._getAppIdData = function() { var data = store.get(this.applicationID); if (data !== null) this._cacheAppIdData(data); return data; }; AlgoliaSearchCore.prototype._setAppIdData = function(data) { data.lastChange = (new Date()).getTime(); this._cacheAppIdData(data); return store.set(this.applicationID, data); }; AlgoliaSearchCore.prototype._checkAppIdData = function() { var data = this._getAppIdData(); var now = (new Date()).getTime(); if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) { return this._resetInitialAppIdData(data); } return data; }; AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) { var newData = data || {}; newData.hostIndexes = {read: 0, write: 0}; newData.timeoutMultiplier = 1; newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]); return this._setAppIdData(newData); }; AlgoliaSearchCore.prototype._cacheAppIdData = function(data) { this._hostIndexes = data.hostIndexes; this._timeoutMultiplier = data.timeoutMultiplier; this._shuffleResult = data.shuffleResult; }; AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) { var foreach = __webpack_require__(399); var currentData = this._getAppIdData(); foreach(newData, function(value, key) { currentData[key] = value; }); return this._setAppIdData(currentData); }; AlgoliaSearchCore.prototype._getHostByType = function(hostType) { return this.hosts[hostType][this._getHostIndexByType(hostType)]; }; AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() { return this._timeoutMultiplier; }; AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) { return this._hostIndexes[hostType]; }; AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) { var clone = __webpack_require__(403); var newHostIndexes = clone(this._hostIndexes); newHostIndexes[hostType] = hostIndex; this._partialAppIdDataUpdate({hostIndexes: newHostIndexes}); return hostIndex; }; AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) { return this._setHostIndexByType( (this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType ); }; AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() { var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4); return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier}); }; AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) { return { connect: this._timeouts.connect * this._timeoutMultiplier, complete: this._timeouts[hostType] * this._timeoutMultiplier }; }; function prepareHost(protocol) { return function prepare(host) { return protocol + '//' + host.toLowerCase(); }; } // Prototype.js < 1.7, a widely used library, defines a weird // Array.prototype.toJSON function that will fail to stringify our content // appropriately // refs: // - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q // - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c // - http://stackoverflow.com/a/3148441/147079 function safeJSONStringify(obj) { /* eslint no-extend-native:0 */ if (Array.prototype.toJSON === undefined) { return JSON.stringify(obj); } var toJSON = Array.prototype.toJSON; delete Array.prototype.toJSON; var out = JSON.stringify(obj); Array.prototype.toJSON = toJSON; return out; } function shuffle(array) { var currentIndex = array.length; var temporaryValue; var randomIndex; // While there remain elements to shuffle... while (currentIndex !== 0) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function removeCredentials(headers) { var newHeaders = {}; for (var headerName in headers) { if (Object.prototype.hasOwnProperty.call(headers, headerName)) { var value; if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') { value = '**hidden for security purposes**'; } else { value = headers[headerName]; } newHeaders[headerName] = value; } } return newHeaders; } /***/ }, /* 412 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(413)('algoliasearch:src/hostIndexState.js'); var localStorageNamespace = 'algoliasearch-client-js'; var store; var moduleStore = { state: {}, set: function(key, data) { this.state[key] = data; return this.state[key]; }, get: function(key) { return this.state[key] || null; } }; var localStorageStore = { set: function(key, data) { moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure try { var namespace = JSON.parse(global.localStorage[localStorageNamespace]); namespace[key] = data; global.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(global.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; module.exports = { get: getOrSet, set: getOrSet, supportsLocalStorage: supportsLocalStorage }; function getOrSet(key, data) { if (arguments.length === 1) { return store.get(key); } return store.set(key, data); } function supportsLocalStorage() { try { if ('localStorage' in global && global.localStorage !== null) { if (!global.localStorage[localStorageNamespace]) { // actual creation of the namespace global.localStorage.setItem(localStorageNamespace, JSON.stringify({})); } return true; } return false; } catch (_) { return false; } } // In case of any error on localStorage, we clean our own namespace, this should handle // quota errors when a lot of keys + data are used function cleanup() { try { global.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 413 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(414); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return ({"NODE_ENV":"production"}).DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300))) /***/ }, /* 414 */ /***/ function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug.default = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(415); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }, /* 415 */ /***/ function(module, exports) { /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } /***/ }, /* 416 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(417); var Promise = global.Promise || __webpack_require__(418).Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback module.exports = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = __webpack_require__(395); var errors = __webpack_require__(398); var inlineHeaders = __webpack_require__(420); var jsonpRequest = __webpack_require__(422); var places = __webpack_require__(423); uaSuffix = uaSuffix || ''; if (false) { require('debug').enable('algoliasearch*'); } function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = __webpack_require__(403); var getDocumentProtocol = __webpack_require__(424); opts = cloneDeep(opts || {}); if (opts.protocol === undefined) { opts.protocol = getDocumentProtocol(); } opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = __webpack_require__(425); algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia global.__algolia = { debug: __webpack_require__(413), algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in global, hasXDomainRequest: 'XDomainRequest' in global }; if (support.hasXMLHttpRequest) { support.cors = 'withCredentials' in new XMLHttpRequest(); } function AlgoliaSearchBrowser() { // call AlgoliaSearch constructor AlgoliaSearch.apply(this, arguments); } inherits(AlgoliaSearchBrowser, AlgoliaSearch); AlgoliaSearchBrowser.prototype._request = function request(url, opts) { return new Promise(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors.Network('CORS not supported')); return; } url = inlineHeaders(url, opts.headers); var body = opts.body; var req = support.cors ? new XMLHttpRequest() : new XDomainRequest(); var reqTimeout; var timedOut; var connected = false; reqTimeout = setTimeout(onTimeout, opts.timeouts.connect); // we set an empty onprogress listener // so that XDomainRequest on IE9 is not aborted // refs: // - https://github.com/algolia/algoliasearch-client-js/issues/76 // - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment req.onprogress = onProgress; if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange; req.onload = onLoad; req.onerror = onError; // do not rely on default XHR async flag, as some analytics code like hotjar // breaks it and set it to false by default if (req instanceof XMLHttpRequest) { req.open(opts.method, url, true); } else { req.open(opts.method, url); } // headers are meant to be sent after open if (support.cors) { if (body) { if (opts.method === 'POST') { // https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests req.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); } else { req.setRequestHeader('content-type', 'application/json'); } } req.setRequestHeader('accept', 'application/json'); } req.send(body); // event object not received in IE8, at least // but we do not use it, still important to note function onLoad(/* event */) { // When browser does not supports req.timeout, we can // have both a load and timeout event, since handled by a dumb setTimeout if (timedOut) { return; } clearTimeout(reqTimeout); var out; try { out = { body: JSON.parse(req.responseText), responseText: req.responseText, statusCode: req.status, // XDomainRequest does not have any response headers headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {} }; } catch (e) { out = new errors.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors.UnparsableJSON) { reject(out); } else { resolve(out); } } function onError(event) { if (timedOut) { return; } clearTimeout(reqTimeout); // error event is trigerred both with XDR/XHR on: // - DNS error // - unallowed cross domain request reject( new errors.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors.RequestTimeout()); } function onConnect() { connected = true; clearTimeout(reqTimeout); reqTimeout = setTimeout(onTimeout, opts.timeouts.complete); } function onProgress() { if (!connected) onConnect(); } function onReadyStateChange() { if (!connected && req.readyState > 1) onConnect(); } }); }; AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) { url = inlineHeaders(url, opts.headers); return new Promise(function wrapJsonpRequest(resolve, reject) { jsonpRequest(url, opts, function jsonpRequestDone(err, content) { if (err) { reject(err); return; } resolve(content); }); }); }; AlgoliaSearchBrowser.prototype._promise = { reject: function rejectPromise(val) { return Promise.reject(val); }, resolve: function resolvePromise(val) { return Promise.resolve(val); }, delay: function delayPromise(ms) { return new Promise(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); } }; return algoliasearch; }; /***/ }, /* 417 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 418 */ /***/ function(module, exports, __webpack_require__) { var require;/* WEBPACK VAR INJECTION */(function(process, global) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.0.5 */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ES6Promise = factory()); }(this, (function () { 'use strict'; function objectOrFunction(x) { return typeof x === 'function' || typeof x === 'object' && x !== null; } function isFunction(x) { return typeof x === 'function'; } var _isArray = undefined; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var isArray = _isArray; var len = 0; var vertxNext = undefined; var customSchedulerFn = undefined; var asap = function asap(callback, arg) { queue[len] = callback; queue[len + 1] = arg; len += 2; if (len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (customSchedulerFn) { customSchedulerFn(flush); } else { scheduleFlush(); } } }; function setScheduler(scheduleFn) { customSchedulerFn = scheduleFn; } function setAsap(asapFn) { asap = asapFn; } var browserWindow = typeof window !== 'undefined' ? window : undefined; var browserGlobal = browserWindow || {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; // test for web worker but not in IE10 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function () { return process.nextTick(flush); }; } // vertx function useVertxTimer() { if (typeof vertxNext !== 'undefined') { return function () { vertxNext(flush); }; } return useSetTimeout(); } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function () { node.data = iterations = ++iterations % 2; }; } // web worker function useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = flush; return function () { return channel.port2.postMessage(0); }; } function useSetTimeout() { // Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout = setTimeout; return function () { return globalSetTimeout(flush, 1); }; } var queue = new Array(1000); function flush() { for (var i = 0; i < len; i += 2) { var callback = queue[i]; var arg = queue[i + 1]; callback(arg); queue[i] = undefined; queue[i + 1] = undefined; } len = 0; } function attemptVertx() { try { var r = require; var vertx = __webpack_require__(419); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = undefined; // Decide what async method to use to triggering processing of queued callbacks: if (isNode) { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else if (isWorker) { scheduleFlush = useMessageChannel(); } else if (browserWindow === undefined && "function" === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var _arguments = arguments; var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { (function () { var callback = _arguments[_state - 1]; asap(function () { return invokeCallback(_state, child, callback, parent._result); }); })(); } else { subscribe(parent, child, onFulfillment, onRejection); } return child; } /** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */ function resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(noop); _resolve(promise, object); return promise; } var PROMISE_ID = Math.random().toString(36).substring(16); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var GET_THEN_ERROR = new ErrorObject(); function selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function getThen(promise) { try { return promise.then; } catch (error) { GET_THEN_ERROR.error = error; return GET_THEN_ERROR; } } function tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then) { asap(function (promise) { var sealed = false; var error = tryThen(then, thenable, function (value) { if (sealed) { return; } sealed = true; if (thenable !== value) { _resolve(promise, value); } else { fulfill(promise, value); } }, function (reason) { if (sealed) { return; } sealed = true; _reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; _reject(promise, error); } }, promise); } function handleOwnThenable(promise, thenable) { if (thenable._state === FULFILLED) { fulfill(promise, thenable._result); } else if (thenable._state === REJECTED) { _reject(promise, thenable._result); } else { subscribe(thenable, undefined, function (value) { return _resolve(promise, value); }, function (reason) { return _reject(promise, reason); }); } } function handleMaybeThenable(promise, maybeThenable, then$$) { if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { handleOwnThenable(promise, maybeThenable); } else { if (then$$ === GET_THEN_ERROR) { _reject(promise, GET_THEN_ERROR.error); } else if (then$$ === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$)) { handleForeignThenable(promise, maybeThenable, then$$); } else { fulfill(promise, maybeThenable); } } } function _resolve(promise, value) { if (promise === value) { _reject(promise, selfFulfillment()); } else if (objectOrFunction(value)) { handleMaybeThenable(promise, value, getThen(value)); } else { fulfill(promise, value); } } function publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } publish(promise); } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._result = value; promise._state = FULFILLED; if (promise._subscribers.length !== 0) { asap(publish, promise); } } function _reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = REJECTED; promise._result = reason; asap(publishRejection, promise); } function subscribe(parent, child, onFulfillment, onRejection) { var _subscribers = parent._subscribers; var length = _subscribers.length; parent._onerror = null; _subscribers[length] = child; _subscribers[length + FULFILLED] = onFulfillment; _subscribers[length + REJECTED] = onRejection; if (length === 0 && parent._state) { asap(publish, parent); } } function publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child = undefined, callback = undefined, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function ErrorObject() { this.error = null; } var TRY_CATCH_ERROR = new ErrorObject(); function tryCatch(callback, detail) { try { return callback(detail); } catch (e) { TRY_CATCH_ERROR.error = e; return TRY_CATCH_ERROR; } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value = undefined, error = undefined, succeeded = undefined, failed = undefined; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { _reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) { // noop } else if (hasCallback && succeeded) { _resolve(promise, value); } else if (failed) { _reject(promise, error); } else if (settled === FULFILLED) { fulfill(promise, value); } else if (settled === REJECTED) { _reject(promise, value); } } function initializePromise(promise, resolver) { try { resolver(function resolvePromise(value) { _resolve(promise, value); }, function rejectPromise(reason) { _reject(promise, reason); }); } catch (e) { _reject(promise, e); } } var id = 0; function nextId() { return id++; } function makePromise(promise) { promise[PROMISE_ID] = id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { _reject(this.promise, validationError()); } } function validationError() { return new Error('Array Methods must be provided an Array'); }; Enumerator.prototype._enumerate = function () { var length = this.length; var _input = this._input; for (var i = 0; this._state === PENDING && i < length; i++) { this._eachEntry(_input[i], i); } }; Enumerator.prototype._eachEntry = function (entry, i) { var c = this._instanceConstructor; var resolve$$ = c.resolve; if (resolve$$ === resolve) { var _then = getThen(entry); if (_then === then && entry._state !== PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof _then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === Promise) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$) { return resolve$$(entry); }), i); } } else { this._willSettleAt(resolve$$(entry), i); } }; Enumerator.prototype._settledAt = function (state, i, value) { var promise = this.promise; if (promise._state === PENDING) { this._remaining--; if (state === REJECTED) { _reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { fulfill(promise, this._result); } }; Enumerator.prototype._willSettleAt = function (promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; /** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */ function all(entries) { return new Enumerator(this, entries).promise; } /** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */ function race(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } /** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(noop); _reject(promise, reason); return promise; } function needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function Promise(resolver) { this[PROMISE_ID] = nextId(); this._result = this._state = undefined; this._subscribers = []; if (noop !== resolver) { typeof resolver !== 'function' && needsResolver(); this instanceof Promise ? initializePromise(this, resolver) : needsNew(); } } Promise.all = all; Promise.race = race; Promise.resolve = resolve; Promise.reject = reject; Promise._setScheduler = setScheduler; Promise._setAsap = setAsap; Promise._asap = asap; Promise.prototype = { constructor: Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: then, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function _catch(onRejection) { return this.then(null, onRejection); } }; function polyfill() { var local = undefined; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P) { var promiseToString = null; try { promiseToString = Object.prototype.toString.call(P.resolve()); } catch (e) { // silently ignored } if (promiseToString === '[object Promise]' && !P.cast) { return; } } local.Promise = Promise; } // Strange compat.. Promise.polyfill = polyfill; Promise.Promise = Promise; return Promise; }))); //# sourceMappingURL=es6-promise.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(300), (function() { return this; }()))) /***/ }, /* 419 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, /* 420 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = inlineHeaders; var encode = __webpack_require__(421); function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode(headers); } /***/ }, /* 421 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; /***/ }, /* 422 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = jsonpRequest; var errors = __webpack_require__(398); var JSONPCounter = 0; function jsonpRequest(url, opts, cb) { if (opts.method !== 'GET') { cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.')); return; } opts.debug('JSONP: start'); var cbCalled = false; var timedOut = false; JSONPCounter += 1; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); var cbName = 'algoliaJSONP_' + JSONPCounter; var done = false; window[cbName] = function(data) { removeGlobals(); if (timedOut) { opts.debug('JSONP: Late answer, ignoring'); return; } cbCalled = true; clean(); cb(null, { body: data/* , // We do not send the statusCode, there's no statusCode in JSONP, it will be // computed using data.status && data.message like with XDR statusCode*/ }); }; // add callback by hand url += '&callback=' + cbName; // add body params manually if (opts.jsonBody && opts.jsonBody.params) { url += '&' + opts.jsonBody.params; } var ontimeout = setTimeout(timeout, opts.timeouts.complete); // script onreadystatechange needed only for // <= IE8 // https://github.com/angular/angular.js/issues/4523 script.onreadystatechange = readystatechange; script.onload = success; script.onerror = error; script.async = true; script.defer = true; script.src = url; head.appendChild(script); function success() { opts.debug('JSONP: success'); if (done || timedOut) { return; } done = true; // script loaded but did not call the fn => script loading error if (!cbCalled) { opts.debug('JSONP: Fail. Script loaded but did not call the callback'); clean(); cb(new errors.JSONPScriptFail()); } } function readystatechange() { if (this.readyState === 'loaded' || this.readyState === 'complete') { success(); } } function clean() { clearTimeout(ontimeout); script.onload = null; script.onreadystatechange = null; script.onerror = null; head.removeChild(script); } function removeGlobals() { try { delete window[cbName]; delete window[cbName + '_loaded']; } catch (e) { window[cbName] = window[cbName + '_loaded'] = undefined; } } function timeout() { opts.debug('JSONP: Script timeout'); timedOut = true; clean(); cb(new errors.RequestTimeout()); } function error() { opts.debug('JSONP: Script error'); if (done || timedOut) { return; } clean(); cb(new errors.JSONPScriptError()); } } /***/ }, /* 423 */ /***/ function(module, exports, __webpack_require__) { module.exports = createPlacesClient; var buildSearchMethod = __webpack_require__(397); function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = __webpack_require__(403); opts = opts && cloneDeep(opts) || {}; opts.hosts = opts.hosts || [ 'places-dsn.algolia.net', 'places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com' ]; // allow initPlaces() no arguments => community rate limited if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) { appID = ''; apiKey = ''; opts._allowEmptyCredentials = true; } var client = algoliasearch(appID, apiKey, opts); var index = client.initIndex('places'); index.search = buildSearchMethod('query', '/1/places/query'); return index; }; } /***/ }, /* 424 */ /***/ function(module, exports) { 'use strict'; module.exports = getDocumentProtocol; function getDocumentProtocol() { var protocol = window.document.location.protocol; // when in `file:` mode (local html file), default to `http:` if (protocol !== 'http:' && protocol !== 'https:') { protocol = 'http:'; } return protocol; } /***/ }, /* 425 */ /***/ function(module, exports) { 'use strict'; module.exports = '3.20.4'; /***/ } /******/ ]) }); ; //# sourceMappingURL=Dom.js.map
src/components/Navbar.js
jamez14/jams-tweeter
import React, { Component } from 'react'; export class Navbar extends Component { render() { return ( <nav className="navbar navbar-fixed-top navbar-dark bg-primary"> <button className="navbar-toggler hidden-sm-up" type="button"> &#9776; </button> <div className="collapse navbar-toggleable-xs"> <a className="navbar-brand" href="#">Jams Tweeter</a> <ul className="nav navbar-nav"> <li className="nav-item active"> <a className="nav-link" href="#">Home <span className="sr-only">(current)</span></a> </li> <li className="nav-item"> <a className="nav-link" href="#">Notifications</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Moments</a> </li> <li className="nav-item"> <a className="nav-link" href="#">Message</a> </li> </ul> </div> </nav> ); } }
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
Rogerlin2013/actor-platform
import _ from 'lodash'; import React from 'react'; import ReactMixin from 'react-mixin'; import addons from 'react/addons'; const {addons: { PureRenderMixin }} = addons; @ReactMixin.decorate(PureRenderMixin) class UserProfileContactInfo extends React.Component { static propTypes = { phones: React.PropTypes.array }; constructor(props) { super(props); } render() { let phones = this.props.phones; let contactPhones = _.map(phones, (phone, i) => { return ( <li className="profile__list__item row" key={i}> <i className="material-icons">call</i> <div className="col-xs"> <span className="contact">+{phone.number}</span> <span className="title">{phone.title}</span> </div> </li> ); }); return ( <ul className="profile__list profile__list--contacts"> {contactPhones} </ul> ); } } export default UserProfileContactInfo;
ajax/libs/react-widgets/3.1.0/react-widgets-simple-number.js
sufuf3/cdnjs
/*! (c) 2015 Jason Quense | https://github.com/jquense/react-widgets/blob/master/License.txt */ /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(1); exports.__esModule = true; exports['default'] = simpleNumber; var _configure = __webpack_require__(3); var _configure2 = babelHelpers.interopRequireDefault(_configure); var _formatNumberWithString = __webpack_require__(4); var _formatNumberWithString2 = babelHelpers.interopRequireDefault(_formatNumberWithString); var _deconstructNumberFormat = __webpack_require__(5); var _deconstructNumberFormat2 = babelHelpers.interopRequireDefault(_deconstructNumberFormat); function simpleNumber() { var localizer = { formats: { 'default': '-#,##0.' }, parse: function parse(value, format) { if (format) { var data = _deconstructNumberFormat2['default'](format); if (data.negativeLeftPos !== -1) value = value.substr(data.negativeLeftPos + 1); if (data.negativeRightPos !== -1) value = value.substring(0, data.negativeRightPos); value = value.replace(data.prefix, '').replace(data.suffix, ''); var halves = value.split(data.decimalChar); if (data.integerSeperator) halves[0] = halves[0].replace(new RegExp('\\' + data.integerSeperator, 'g')); if (data.decimalsSeparator) halves[1] = halves[1].replace(new RegExp('\\' + data.decimalsSeparator, 'g')); value = halves.join(data.decimalChar); } var number = parseFloat(value); return number; }, format: function format(value, _format) { return _formatNumberWithString2['default'](value, _format); }, precision: function precision(format) { var data = _deconstructNumberFormat2['default'](format); return data.maxRight !== -1 ? data.maxRight : null; } }; _configure2['default'].setNumberLocalizer(localizer); return localizer; } module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === "object") { factory(exports); } else { factory(root.babelHelpers = {}); } })(this, function (global) { var babelHelpers = global; babelHelpers.createDecoratedObject = function (descriptors) { var target = {}; for (var i = 0; i < descriptors.length; i++) { var descriptor = descriptors[i]; var decorators = descriptor.decorators; var key = descriptor.key; delete descriptor.key; delete descriptor.decorators; descriptor.enumerable = true; descriptor.configurable = true; if ("value" in descriptor || descriptor.initializer) descriptor.writable = true; if (decorators) { for (var f = 0; f < decorators.length; f++) { var decorator = decorators[f]; if (typeof decorator === "function") { descriptor = decorator(target, key, descriptor) || descriptor; } else { throw new TypeError("The decorator for method " + descriptor.key + " is of the invalid type " + typeof decorator); } } } if (descriptor.initializer) { descriptor.value = descriptor.initializer.call(target); } Object.defineProperty(target, key, descriptor); } return target; }; babelHelpers.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; }; babelHelpers.interopRequireWildcard = function (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; } }; babelHelpers.interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; babelHelpers._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; }; }) /***/ }, /* 2 */, /* 3 */ /***/ function(module, exports) { module.exports = window.ReactWidgets; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var deconstructNumberFormat = __webpack_require__(5); var formatFactory = __webpack_require__(6); exports = module.exports = function formatNumberWithString(value, requiredFormat, overrideOptions) { var deconstructedFormat = [] if (requiredFormat) deconstructedFormat = deconstructNumberFormat(requiredFormat.trim()); value = (value === null ? '' : value); value = value + ''; //make a string value = value.length ? value.trim() : ''; var options = []; var format = formatFactory({ negativeType: deconstructedFormat.negativeType, negativeLeftSymbol: deconstructedFormat.negativeLeftSymbol, negativeRightSymbol: deconstructedFormat.negativeRightSymbol, negativeLeftOut: deconstructedFormat.negativeLeftPos === 0, negativeRightOut: deconstructedFormat.negativeRightPos === 0, prefix: deconstructedFormat.prefix, suffix: deconstructedFormat.suffix, integerSeparator: deconstructedFormat.integerSeparator, decimalsSeparator: deconstructedFormat.decimalsSeparator, decimal: deconstructedFormat.decimalChar, padLeft: deconstructedFormat.padLeft, padRight: deconstructedFormat.padRight, round: deconstructedFormat.maxRight, truncate: null }) return format(value, overrideOptions); }; /***/ }, /* 5 */ /***/ function(module, exports) { 'use strict'; exports = module.exports = function deconstructNumberFormat(requiredFormat) { var format= requiredFormat || '-9,999.90'; format=format.trim(); //ignore leading and trailing spaces // ********************************************************************************* // find position and type of negative and contents of prefix and suffix text // ********************************************************************************* var negativeType = '', negativeRightSymbol = '', negativeLeftSymbol = '', negativeRightPos = -1, negativeLeftPos = -1, absFormat, prefix = '', suffix = ''; // brackets as negative if (/^([^()]+)?[(]([^09#]+)?[09#., ]+([^)]+)?[)](.+)?$/.test(format)) { negativeType = 'brackets'; negativeLeftPos = format.indexOf("("); negativeLeftSymbol = '(' if (negativeLeftPos > 0) { //after prefix prefix = format.slice(0, negativeLeftPos); } else { prefix = format.search(/0|9|#/) > 0 ? format.slice(1, format.search(/0|9|#/)) : ""; } format = format.slice(prefix.length+1); negativeRightPos = format.indexOf(")"); negativeRightSymbol = ')' if (negativeRightPos < format.length-1) { //before prefix suffix = format.slice(negativeRightPos+1); format = format.slice(0, negativeRightPos); } else { suffix = format.search(/[^09#,.]([^09#](.+)?)?[)]$/) > -1 ? format.slice(format.search(/[^09#,.]([^09#](.+)?)?[)]$/), -1) : ""; format = format.slice(0, format.length - suffix.length - 1); negativeRightPos = 0; } } else if (format.indexOf("-") === -1){ //positive values only negativeType = 'none'; prefix = format.search(/[.,]?[09#]/) > 0 ? format.slice(0, format.search(/[.,]?[09#]/)) : ""; format = format.slice(prefix.length); suffix = format.search(/[^09#,.]([^09#]+|$)/) > -1 ? format.slice(format.search(/[^09#,.]([^09#]+|$)/)) : ""; format = format.slice(0, format.length-suffix.length); } else if (/^([^09#-]+)?-.+$/.test(format)) { //negative symbol to left of number (before or after prefix) negativeType = 'left'; negativeLeftPos = format.indexOf("-"); negativeLeftSymbol = '-' if (negativeLeftPos > 0) { //after prefix prefix = format.slice(0, negativeLeftPos); } else { prefix = format.search(/[09#]/) > 0 ? format.slice(1, format.search(/[09#]/)) : ""; } format = format.slice(prefix.length+1); suffix = format.search(/[^09#,.]([^09#]+|$)/) > -1 ? format.slice(format.search(/[^09#,.]([^09#]+|$)/)) : ""; format = format.slice(0, format.length-suffix.length); } else { //negative symbol to right of number (before or after suffix) prefix = format.search(/[09#]/) > 0 ? format.slice(0, format.search(/[09#]/)) : ""; format = format.slice(prefix.length); negativeType = 'right'; negativeRightSymbol = '-' negativeRightPos = format.lastIndexOf("-"); if (negativeRightPos < format.length-1) { //before suffix suffix = format.slice(negativeRightPos+1); format = format.slice(0, negativeRightPos); } else { suffix = format.search(/[^09#,.]([^09#](.+)?)?-$/) > -1 ? format.slice(format.search(/[^09#,.]([^09#](.+)?)?-$/), format.length-1) : ""; format = format.slice(0, format.length - suffix.length - 1); negativeRightPos = 0; } } // ********************************************************************************* //include spaces with negative symbols // ********************************************************************************* //When negative is before prefix move spaces from start of prefix to end of negative symbol while (negativeLeftPos === 0 && prefix && prefix[0] === ' ') { negativeLeftSymbol = negativeLeftSymbol + ' '; prefix = prefix.slice(1); } //When negative follows suffix move spaces end of suffix to start of negative symbol while (negativeRightPos === 0 && suffix && suffix[suffix.length-1] === ' ') { negativeRightSymbol = ' ' + negativeRightSymbol; suffix = suffix.slice(0, -1); } //When negative follows prefix move spaces from start of format to end of negative symbol while (negativeLeftPos > 0 && format.length && format[0] === ' ') { negativeLeftSymbol = negativeLeftSymbol + ' '; format = format.slice(1); } //When negative before suffix move spaces from end of format to start of negative symbol while (negativeRightPos > 0 && format.length && format[format.length-1] === ' ') { negativeRightSymbol = ' ' + negativeRightSymbol; format = format.slice(0, -1); } var absMask = format; // ********************************************************************************* //find the decimal character and parts of absolute format // ********************************************************************************* var decimalChar = '', decimalsPart = '', integerPart = '', decimalsSeparator = '', integerSeparator = ''; //if last char is a ',' and there are no other commas then use this as decimal point if (format[format.length-1] === ',' && format.indexOf(',') === format.length-1) { decimalChar = ','; //otherwise use consider '.' } else if (format.indexOf('.') > -1) { if (format.indexOf('.') === format.lastIndexOf('.')) { decimalChar = "."; } else { // two of '.' means this must be the separator, so assume ',' is the decimal decimalChar = ','; } //otherwise use ',' if it exists and there is only one } else if (format.indexOf(',') > -1) { if (format.indexOf(',') === format.lastIndexOf(',')) { decimalChar = ','; } else { decimalChar = '.'; } } if (decimalChar && format.indexOf(decimalChar)>-1) { decimalsPart = format.slice(format.indexOf(decimalChar)+1); integerPart = format.slice(0,format.indexOf(decimalChar)); } else { integerPart = format; decimalsPart = ''; } while (decimalsPart.length && decimalsPart.search(/[., ]$/) > -1) { decimalsPart = decimalsPart.slice(0, -1); } while (integerPart.length && integerPart[0].search(/[., ]/) > -1) { integerPart = integerPart.slice(1); } //find the thousands/thousanths separators if (integerPart && integerPart.search(/[., ]/) > 0) { integerSeparator = integerPart[integerPart.search(/[., ]/)]; integerPart = integerPart.replace(/[., ]/g, ""); } if (decimalsPart && decimalsPart.search(/[., ]/) > 0) { decimalsSeparator = decimalsPart[decimalsPart.search(/[., ]/)]; decimalsPart = decimalsPart.replace(/[., ]/g, ""); } if ((integerPart.length && !(/^[09#]+$/).test(integerPart)) || (decimalsPart.length && !(/^[09#]+$/).test(decimalsPart))) {return false}; // ********************************************************************************* //resolve length and padding // ********************************************************************************* var padLeft, maxLeft, padRight, maxRight; padLeft = integerPart.indexOf("0") >= 0 ? integerPart.length - integerPart.indexOf("0") : -1; maxLeft = integerPart.length === 0 ||integerPart[0] === "0" || integerPart[0] === "9" ? integerPart.length : -1; padRight = decimalsPart.indexOf("0") >= 0 ? decimalsPart.lastIndexOf("0")+1 : -1; maxRight = decimalsPart.length === 0 || decimalsPart[decimalsPart.length-1] === "0" || decimalsPart[decimalsPart.length-1] === "9" ? decimalsPart.length : -1; // ********************************************************************************* // output // ********************************************************************************* var deconstructedFormat = { negativeType: negativeType, negativeLeftPos: negativeLeftPos, negativeRightPos: negativeRightPos, negativeLeftSymbol: negativeLeftSymbol, negativeRightSymbol: negativeRightSymbol, suffix: suffix, prefix: prefix, absMask: absMask, decimalChar: decimalChar, integerSeparator: integerSeparator, decimalsSeparator: decimalsSeparator, padLeft: padLeft, maxLeft: maxLeft, padRight: padRight, maxRight: maxRight } return deconstructedFormat; }; /***/ }, /* 6 */ /***/ function(module, exports) { module.exports = formatter; function formatter(options) { options = options || {}; // ********************************************************************************************* // Set defaults for negatives // options.negative, options.negativeOut, options.separator retained for backward compatibility // ********************************************************************************************* // type of negative; default left options.negativeType = options.negativeType || (options.negative === 'R' ? 'right' : 'left') // negative symbols '-' or '()' if (typeof options.negativeLeftSymbol !== 'string') { switch (options.negativeType) { case 'left': options.negativeLeftSymbol = '-'; break; case 'brackets': options.negativeLeftSymbol = '('; break; default: options.negativeLeftSymbol = ''; } } if (typeof options.negativeRightSymbol !== 'string') { switch (options.negativeType) { case 'right': options.negativeRightSymbol = '-'; break; case 'brackets': options.negativeRightSymbol = ')'; break; default: options.negativeRightSymbol = ''; } } // whether negative symbol should be inside/outside prefix and suffix if (typeof options.negativeLeftOut !== "boolean") { options.negativeLeftOut = (options.negativeOut === false ? false : true); } if (typeof options.negativeRightOut !== "boolean") { options.negativeRightOut = (options.negativeOut === false ? false : true); } //prefix and suffix options.prefix = options.prefix || ''; options.suffix = options.suffix || ''; //separators if (typeof options.integerSeparator !== 'string') { options.integerSeparator = (typeof options.separator === 'string' ? options.separator : ','); } options.decimalsSeparator = typeof options.decimalsSeparator === 'string' ? options.decimalsSeparator : ''; options.decimal = options.decimal || '.'; //padders options.padLeft = options.padLeft || -1 //default no padding options.padRight = options.padRight || -1 //default no padding function format(number, overrideOptions) { overrideOptions = overrideOptions || {}; if (number || number === 0) { number = '' + number;//convert number to string if it isn't already } else { return ''; } //identify a negative number and make it absolute var output = []; var negative = number.charAt(0) === '-'; number = number.replace(/^\-/g, ''); //Prepare output with left hand negative and/or prefix if (!options.negativeLeftOut && !overrideOptions.noUnits) { output.push(options.prefix); } if (negative) { output.push(options.negativeLeftSymbol); } if (options.negativeLeftOut && !overrideOptions.noUnits) { output.push(options.prefix); } //Format core number number = number.split('.'); if (options.round != null) round(number, options.round); if (options.truncate != null) number[1] = truncate(number[1], options.truncate); if (options.padLeft > 0) number[0] = padLeft(number[0], options.padLeft); if (options.padRight > 0) number[1] = padRight(number[1], options.padRight); if (!overrideOptions.noSeparator && number[1]) number[1] = addDecimalSeparators(number[1], options.decimalsSeparator); if (!overrideOptions.noSeparator && number[0]) number[0] = addIntegerSeparators(number[0], options.integerSeparator); output.push(number[0]); if (number[1]) { output.push(options.decimal); output.push(number[1]); } //Prepare output with right hand negative and/or prefix if (options.negativeRightOut && !overrideOptions.noUnits) { output.push(options.suffix); } if (negative) { output.push(options.negativeRightSymbol); } if (!options.negativeRightOut && !overrideOptions.noUnits) { output.push(options.suffix); } //join output and return return output.join(''); } format.negative = options.negative; format.negativeOut = options.negativeOut; format.negativeType = options.negativeType; format.negativeLeftOut = options.negativeLeftOut; format.negativeLeftSymbol = options.negativeLeftSymbol; format.negativeRightOut = options.negativeRightOut; format.negativeRightSymbol = options.negativeRightSymbol; format.prefix = options.prefix; format.suffix = options.suffix; format.separate = options.separate; format.integerSeparator = options.integerSeparator; format.decimalsSeparator = options.decimalsSeparator; format.decimal = options.decimal; format.padLeft = options.padLeft; format.padRight = options.padRight; format.truncate = options.truncate; format.round = options.round; function unformat(number, allowedSeparators) { allowedSeparators = allowedSeparators || []; if (options.allowedSeparators) { options.allowedSeparators.forEach(function (s) { allowedSeparators.push (s); }); } allowedSeparators.push(options.integerSeparator); allowedSeparators.push(options.decimalsSeparator); number = number.replace(options.prefix, ''); number = number.replace(options.suffix, ''); var newNumber = number; do { number = newNumber; for (var i = 0; i < allowedSeparators.length; i++) { newNumber = newNumber.replace(allowedSeparators[i], ''); } } while (newNumber != number); return number; } format.unformat = unformat; function validate(number, allowedSeparators) { number = unformat(number, allowedSeparators); number = number.split(options.decimal); if (number.length > 2) { return false; } else if (options.truncate != null && number[1] && number[1].length > options.truncate) { return false; } else if (options.round != null && number[1] && number[1].length > options.round) { return false; } else { return /^-?\d+\.?\d*$/.test(number); } } return format; } //where x is already the integer part of the number function addIntegerSeparators(x, separator) { x += ''; if (!separator) return x; var rgx = /(\d+)(\d{3})/; while (rgx.test(x)) { x = x.replace(rgx, '$1' + separator + '$2'); } return x; } //where x is already the decimal part of the number function addDecimalSeparators(x, separator) { x += ''; if (!separator) return x; var rgx = /(\d{3})(\d+)/; while (rgx.test(x)) { x = x.replace(rgx, '$1' + separator + '$2'); } return x; } //where x is the integer part of the number function padLeft(x, padding) { x = x + ''; var buf = []; while (buf.length + x.length < padding) { buf.push('0'); } return buf.join('') + x; } //where x is the decimals part of the number function padRight(x, padding) { if (x) { x += ''; } else { x = ''; } var buf = []; while (buf.length + x.length < padding) { buf.push('0'); } return x + buf.join(''); } function truncate(x, length) { if (x) { x += ''; } if (x && x.length > length) { return x.substr(0, length); } else { return x; } } //where number is an array with 0th item as integer string and 1st item as decimal string (no negatives) function round(number, places) { if (number[1] && places >= 0 && number[1].length > places) { //truncate to correct number of decimal places var decim = number[1].slice(0, places); //if next digit was >= 5 we need to round up if (+(number[1].substr(places, 1)) >= 5) { decim = (+decim + 1) + '' if (decim.length > places) { //adding one has made it longer decim = decim.substring(1); //ignore the 1 at the beginning which is the carry to the integer part number[0] = (+number[0]+1) + '' //add 1 to the integer part } } number[1] = decim; } return number; } /***/ } /******/ ]);
client/modules/home/containers/charts/list.js
JSSolutions/Databazel
import React from 'react'; import { useDeps, composeWithTracker, composeAll } from 'mantra-core'; import ChartsList from '../../components/charts/list.jsx'; export const composer = ({ context }, onData) => { const { Meteor, Collections } = context(); if (Meteor.subscribe('charts').ready()) { const charts = Collections.Charts.find({}).fetch(); onData(null, { charts }); } }; export const depsMapper = (context, actions) => ({ routeTo: actions.core.routeTo, meteorMethodCall: actions.core.meteorMethodCall, exportDataToCsv: actions.charts.exportDataToCsv, context: () => context, }); export default composeAll( composeWithTracker(composer, () => <i />), useDeps(depsMapper) )(ChartsList);
RNTester/js/ActivityIndicatorExample.js
jasonnoahchoi/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @providesModule ActivityIndicatorExample */ 'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, View } from 'react-native'; /** * Optional Flowtype state and timer types definition */ type State = { animating: boolean; }; type Timer = number; class ToggleAnimatingActivityIndicator extends Component { /** * Optional Flowtype state and timer types */ state: State; _timer: Timer; constructor(props) { super(props); this.state = { animating: true, }; } componentDidMount() { this.setToggleTimeout(); } componentWillUnmount() { clearTimeout(this._timer); } setToggleTimeout() { this._timer = setTimeout(() => { this.setState({animating: !this.state.animating}); this.setToggleTimeout(); }, 2000); } render() { return ( <ActivityIndicator animating={this.state.animating} style={[styles.centering, {height: 80}]} size="large" /> ); } } exports.displayName = (undefined: ?string); exports.framework = 'React'; exports.title = '<ActivityIndicator>'; exports.description = 'Animated loading indicators.'; exports.examples = [ { title: 'Default (small, white)', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} color="white" /> ); } }, { title: 'Gray', render() { return ( <View> <ActivityIndicator style={[styles.centering]} /> <ActivityIndicator style={[styles.centering, {backgroundColor: '#eeeeee'}]} /> </View> ); } }, { title: 'Custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator color="#0000ff" /> <ActivityIndicator color="#aa00aa" /> <ActivityIndicator color="#aa3300" /> <ActivityIndicator color="#00aa00" /> </View> ); } }, { title: 'Large', render() { return ( <ActivityIndicator style={[styles.centering, styles.gray]} size="large" color="white" /> ); } }, { title: 'Large, custom colors', render() { return ( <View style={styles.horizontal}> <ActivityIndicator size="large" color="#0000ff" /> <ActivityIndicator size="large" color="#aa00aa" /> <ActivityIndicator size="large" color="#aa3300" /> <ActivityIndicator size="large" color="#00aa00" /> </View> ); } }, { title: 'Start/stop', render() { return <ToggleAnimatingActivityIndicator />; } }, { title: 'Custom size', render() { return ( <ActivityIndicator style={[styles.centering, {transform: [{scale: 1.5}]}]} size="large" /> ); } }, { platform: 'android', title: 'Custom size (size: 75)', render() { return ( <ActivityIndicator style={styles.centering} size={75} /> ); } }, ]; const styles = StyleSheet.create({ centering: { alignItems: 'center', justifyContent: 'center', padding: 8, }, gray: { backgroundColor: '#cccccc', }, horizontal: { flexDirection: 'row', justifyContent: 'space-around', padding: 8, }, });
src/routes/Character/routes/Profile/components/ProfileView.js
warcraftlfg/warcrafthub-client
import React from 'react' import { Row, Col } from 'react-bootstrap' import CharacterItems from './CharacterItems' import CharacterItemIlvl from './CharacterItemIlvl' import CharacterItemsAudit from './CharacterItemsAudit' import CharacterT19 from './CharacterT19' export const ProfileView = (props) => { return ( <div className='character-profile'> <Row> <Col md={12} /> <Col md={8}> <Row> <Col md={12}> <CharacterItems items={props.character.data.items} region={props.character.data.region} race={props.character.data.race} thumbnail={props.character.data.thumbnail} /> </Col> </Row> </Col> <Col md={4}> <CharacterItemIlvl averageItemLevel={props.character.data.averageItemLevel} averageItemLevelEquipped={props.character.data.averageItemLevelEquipped} /> <CharacterItemsAudit items={props.character.data.items} /> <CharacterT19 items={props.character.data.items} class={props.character.data.class} /> //TODO artefact power & Guild history </Col> </Row> </div> ) } ProfileView.propTypes = { character: React.PropTypes.shape({ isLoading: React.PropTypes.bool.isRequired, hasError: React.PropTypes.bool.isRequired, data: React.PropTypes.object }) } export default ProfileView
definitions/npm/redux-forms-react_v0.11.x/flow_v0.34.x-v0.52.x/test_redux-forms-react_v0.11.x.js
mkscrg/flow-typed
/* @flow */ import React from 'react'; import { Form, Field, FieldArray } from 'redux-forms-react'; let el; /* ======== */ /* = Form = */ /* ======== */ el = ( <Form name="test" /> ); let f: HTMLFormElement; el = ( <Form name="test" persistent onSubmit={(values) => new Promise((resolve, reject) => { resolve(values) })} withRef={(form) => { f = form; }} /> ); // $ExpectError - missing prop el = (<Form />); // $ExpectError - unknown prop el = (<Form namee="test" />); // $ExpectError - invalid prop el = (<Form name="test" persistent="1337" />); // $ExpectError - invalid prop el = (<Form name="test" onSubmit="1337" />); // $ExpectError - invalid prop el = (<Form name="test" withRef="1337" />); /* ========= */ /* = Field = */ /* ========= */ el = ( <Field name="test" /> ); el = ( <Field name="test" validate={value => Boolean(value) ? null : 'error'} normalize={value => value.substring(5)} defaultValue="kek" /> ); // $ExpectError - missing prop el = (<Field />); // $ExpectError - unknown prop el = (<Field namee="test" />); // $ExpectError - invalid prop el = (<Field name="test" validate="bur" />); // $ExpectError - invalid prop el = (<Field name="test" normalize="bur" />); /* ============== */ /* = FieldArray = */ /* ============== */ el = (<FieldArray name="test" />); // $ExpectError - missing prop el = (<FieldArray />); // $ExpectError - unknown prop el = (<FieldArray namee="test" />);
spec/javascripts/jsx/announcements/components/AnnouncementsIndexSpec.js
djbender/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {mount, shallow} from 'enzyme' import {Provider} from 'react-redux' import _ from 'lodash' import AnnouncementsIndex from 'jsx/announcements/components/AnnouncementsIndex' import sampleData from '../sampleData' const makeProps = (props = {}) => _.merge( { announcements: [], announcementsPage: 1, isCourseContext: true, isLoadingAnnouncements: false, hasLoadedAnnouncements: false, announcementsLastPage: 5, permissions: { create: true, manage_content: true, moderate: true }, getAnnouncements() {}, setAnnouncementSelection() {}, deleteAnnouncements() {}, toggleAnnouncementsLock() {} }, props ) // necessary to mock this because we have a child Container/"Smart" component // that need to pull their props from the store state const store = { getState: () => ({ contextType: 'course', contextId: '1', permissions: { create: true, manage_content: true, moderate: true }, selectedAnnouncements: [] }), // we only need to define these functions so that we match the react-redux contextTypes // shape for a store otherwise react-redux thinks our store is invalid dispatch() {}, subscribe() {} } QUnit.module('AnnouncementsIndex component') test('renders the component', () => { const tree = mount( <Provider store={store}> <AnnouncementsIndex {...makeProps()} /> </Provider> ) const node = tree.find('AnnouncementsIndex') ok(node.exists()) }) test('displays spinner when loading announcements', () => { const tree = shallow(<AnnouncementsIndex {...makeProps({isLoadingAnnouncements: true})} />) const node = tree.find('Spinner') ok(node.exists()) }) test('calls getAnnouncements if hasLoadedAnnouncements is false', () => { const getAnnouncements = sinon.spy() mount( <Provider store={store}> <AnnouncementsIndex {...makeProps({getAnnouncements})} /> </Provider> ) equal(getAnnouncements.callCount, 1) }) test('should render IndexHeader if we have manage_content permissions', () => { const tree = mount( <Provider store={store}> <AnnouncementsIndex {...makeProps({permissions: {manage_content: true}})} /> </Provider> ) const node = tree.find('IndexHeader') ok(node.exists()) }) test('should render IndexHeader even if we do not have manage_content permissions', () => { const tree = mount( <Provider store={store}> <AnnouncementsIndex {...makeProps({permissions: {manage_content: false}})} /> </Provider> ) const node = tree.find('IndexHeader') ok(node.exists()) }) test('clicking announcement checkbox triggers setAnnouncementSelection with correct data', assert => { const done = assert.async() const selectSpy = sinon.spy() const props = { announcements: sampleData.announcements, announcementSelectionChangeStart: selectSpy, hasLoadedAnnouncements: true, permissions: { moderate: true } } const tree = mount( <Provider store={store}> <AnnouncementsIndex {...makeProps(props)} /> </Provider> ) tree.find('input[type="checkbox"]').simulate('change', {target: {checked: true}}) setTimeout(() => { equal(selectSpy.callCount, 1) deepEqual(selectSpy.firstCall.args, [{selected: true, id: sampleData.announcements[0].id}]) done() }) }) test('onManageAnnouncement shows delete modal when called with delete action', assert => { const done = assert.async() const props = { announcements: sampleData.announcements, hasLoadedAnnouncements: true, permissions: { moderate: true } } function indexRef(c) { if (c) { c.onManageAnnouncement(null, {action: 'delete'}) setTimeout(() => { ok(c.deleteModal) c.deleteModal.hide() done() }) } } mount( <Provider store={store}> <AnnouncementsIndex {...makeProps(props)} ref={indexRef} /> </Provider> ) }) test('onManageAnnouncement calls toggleAnnouncementsLock when called with lock action', assert => { const done = assert.async() const lockSpy = sinon.spy() const props = { announcements: sampleData.announcements, hasLoadedAnnouncements: true, permissions: { moderate: true }, toggleAnnouncementsLock: lockSpy } function indexRef(c) { if (c) { c.onManageAnnouncement(null, {action: 'lock'}) setTimeout(() => { equal(lockSpy.callCount, 1) done() }) } } mount( <Provider store={store}> <AnnouncementsIndex {...makeProps(props)} ref={indexRef} /> </Provider> ) })
app/main.js
AidanNichol/stedwards-booking-system
import 'babel-polyfill' // import 'longjohn'; import React from 'react'; import ReactDom from 'react-dom'; import {isUserAuthorized} from 'services/auth'; // import {loginUser} from '_users' // loginUser() import { Provider } from 'react-redux'; import {store, sagaMiddleware} from './store'; import { Router, Route, IndexRoute, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import initialSaga from 'sagas/initialSaga'; import MainLayout from 'layouts/main-layout'; const Home = ()=>(<div> ?? </div>) import MembersListContainer from 'containers/members-list-container'; import BookingsContainer from 'containers/bookings-container'; import BulkAddContainer from 'containers/bulkAdd-container'; import BusListsContainer from 'containers/buslists-container'; import PaymentsContainer from 'containers/Payments-container'; // Provider is a top-level component that wrapps our entire application, including // the Router. We pass it a reference to the store so we can use react-redux's // connect() method for Component Containers. const history = syncHistoryWithStore(browserHistory, store) ReactDom.render( <Provider store={store}> <Router history={history}> <Route path="/" component={MainLayout} onEnter={()=>{sagaMiddleware.run(initialSaga); }}> <IndexRoute component={Home} /> <Route path="membersList/:id" component={MembersListContainer} /> <Route path="membersList" component={MembersListContainer} /> {/* <Route path="bulkadd/:id" component={BulkAddContainer}></Route> */} {isUserAuthorized([ 'bookings']) ? <Route path="bulkadd" component={BulkAddContainer}> <IndexRoute component={BulkAddContainer}/> <Route path=":id" component={BulkAddContainer} /> </Route> : null} {/* <Route path="bulkadd" component={BulkAddContainer} /> */} <Route path="buslists/:id" component={BusListsContainer} /> <Route path="payments" component={PaymentsContainer} /> <Route path="bookings/:id" component={BookingsContainer} /> </Route> </Router> </Provider>, document.getElementById('root') );
src/docs/components/ArticleDoc.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Article from 'grommet/components/Article'; import Section from 'grommet/components/Section'; import Header from 'grommet/components/Header'; import Footer from 'grommet/components/Footer'; import Anchor from 'grommet/components/Anchor'; import DocsArticle from '../../components/DocsArticle'; import Code from '../../components/Code'; Article.displayName = 'Article'; export const DESC = (<span> A standard <Anchor href='http://www.w3.org/TR/html5/sections.html#the-article-element'> HTML5 article</Anchor>. It might contain a <Anchor path='/docs/header'>Header</Anchor>, one or more <Anchor path='/docs/section'>Sections</Anchor>, and a <Anchor path='/docs/footer'>Footer</Anchor>. </span>); export default class ArticleDoc extends Component { render () { return ( <DocsArticle title='Article'> <section> <p>{DESC}</p> <Article colorIndex='light-2'> <Header colorIndex="grey-5" justify="center" align="center"> Header </Header> <Section basis='medium' pad='large' justify='center' align='center'> Sections </Section> <Footer colorIndex="grey-5" justify="center" align="center"> Footer </Footer> </Article> </section> <section> <h2>Properties</h2> <dl> <dt><code>onSelect {'{function (selected)}'}</code></dt> <dd>Function that will be called when the article changes the currently selected chapter.</dd> <dt><code>selected {'{number}'}</code></dt> <dd>The currently selected chapter using a zero based index. Defaults to 0.</dd> <dt><code>scrollStep true|false</code></dt> <dd>Whether to allow keyboard control of stepped scrolling through children. When true, directional keys will step through the children, depending on the direction they are laid out. If the spacebar is pressed, the children will automatically be stepped through at an interval of ten seconds per child.</dd> </dl> <p>Properties for <Anchor path='/docs/box'>Box</Anchor> are also available.</p> </section> <section> <h2>Usage</h2> <Code preamble={`import Article from 'grommet/components/Article';`}> <Article> {'{contents}'} </Article> </Code> </section> </DocsArticle> ); } };
app/containers/app.js
mthmulders/lin2go
import React from 'react' import { Text, View } from 'react-native'; import { connect } from 'react-redux'; import Toast from 'react-native-simple-toast'; import Game from '../containers/game'; import Home from '../components/home'; import Logo from '../components/logo'; import Stats from '../components/stats'; import styles from '../styles'; import { clearMessage } from '../actions'; export const App = (props) => { const { clearMessage, gameRunning, message, showStats, stats } = props; if (message) { Toast.show(message, Toast.LONG); setTimeout(clearMessage, 4000); } return ( <View style={ styles.container }> <Logo /> { !gameRunning && !showStats && <Home /> } { gameRunning && !showStats && <Game /> } { !gameRunning && showStats && <Stats stats={ stats } /> } </View> ); }; /** * Props: * message: string */ const mapStateToProps = (state) => { return { gameRunning: state.game.targetWord !== undefined, message: state.messages.message, showStats: state.nav.showStats }; }; const mapDispatchToProps = (dispatch) => { return { clearMessage: () => dispatch(clearMessage()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(App);
app/imports/ui/client/layouts/Header/index.js
valcol/ScrumNinja
import React, { Component } from 'react'; import { Meteor } from 'meteor/meteor'; import { createContainer } from 'meteor/react-meteor-data'; class Header extends Component { constructor(props) { super(props); this.handleSubmitLogout = this.handleSubmitLogout.bind(this); } handleSubmitLogout(event) { event.preventDefault(); Meteor.logout(); window.location.href = '/r/login'; } render() { return ( <header className="main-header"> {/* Logo */} <a href="/" className="logo"> {/* mini logo for sidebar mini 50x50 pixels */} <span className="logo-mini"><img src="/img/logo.png"alt="logo"></img></span> {/* logo for regular state and mobile devices */} <span className="logo-lg"><img src="/img/logo-wide.png"alt="logo"></img></span> </a> {/* Header Navbar */} <nav className="navbar navbar-static-top" role="navigation"> {/* Sidebar toggle button*/} <a href="#" className="sidebar-toggle" data-toggle="offcanvas" role="button"> <span className="sr-only">Toggle navigation</span> </a> {/* Navbar Right Menu */} <div className="navbar-custom-menu"> <ul className="nav navbar-nav"> {/* Tasks Menu */} <li className="dropdown tasks-menu"> {/* Menu Toggle Button */} <a href="#" className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-flag-o" /> <span className="label label-danger">9</span> </a> <ul className="dropdown-menu"> <li className="header">You have 9 tasks</li> <li> {/* Inner menu: contains the tasks */} <ul className="menu"> <li>{/* Task item */} <a href="#"> {/* Task title and progress text */} <h3> Design some buttons <small className="pull-right">20%</small> </h3> {/* The progress bar */} <div className="progress xs"> {/* Change the css width attribute to simulate progress */} <div className="progress-bar progress-bar-aqua" style={{width: '20%'}} role="progressbar" aria-valuenow={20} aria-valuemin={0} aria-valuemax={100}> <span className="sr-only">20% Complete</span> </div> </div> </a> </li> {/* end task item */} </ul> </li> <li className="footer"> <a href="#">View all tasks</a> </li> </ul> </li> {/* User Account Menu */} <li className="dropdown user user-menu"> {/* Menu Toggle Button */} <a href="#" className="dropdown-toggle" data-toggle="dropdown"> {/* The user image in the navbar*/} {/* hidden-xs hides the username on small devices so only the image appears. */} <span>{this.props.user.username}</span> </a> <ul className="dropdown-menu"> {/* Menu Body */} {/* Menu Footer*/} <li className="user-footer"> <div className="pull-left"> <a href="profile" className="btn btn-default btn-flat">Profile</a> </div> <div className="pull-right"> <button onClick={this.handleSubmitLogout} className="btn btn-default btn-flat">Sign out</button> </div> </li> </ul> </li> {/* Control Sidebar Toggle Button */} <li> <a href="#" data-toggle="control-sidebar"><i className="fa fa-gears" /></a> </li> </ul> </div> </nav> </header> ); } } export default createContainer(() => { return { user: Meteor.user() || {} }; }, Header);
src/components/search_bar.js
adimircolen/learn_react
import React, { Component } from 'react' class SearchBar extends Component { constructor (props) { super(props) this.state = { term: '' } } render () { return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.setState({term: event.target.value})} /> </div> ) } } export default SearchBar
ajax/libs/yui/3.14.1/scrollview-base/scrollview-base-debug.js
ematsusaka/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});
examples/polymer/bower_components/polymer/polymer.js
weijye91/todomvc
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.5.1 window.PolymerGestures = {}; (function(scope) { var HAS_FULL_PATH = false; // test for full event path support var pathTest = document.createElement('meta'); if (pathTest.createShadowRoot) { var sr = pathTest.createShadowRoot(); var s = document.createElement('span'); sr.appendChild(s); pathTest.addEventListener('testpath', function(ev) { if (ev.path) { // if the span is in the event path, then path[0] is the real source for all events HAS_FULL_PATH = ev.path[0] === s; } ev.stopPropagation(); }); var ev = new CustomEvent('testpath', {bubbles: true}); // must add node to DOM to trigger event listener document.head.appendChild(pathTest); s.dispatchEvent(ev); pathTest.parentNode.removeChild(pathTest); sr = s = null; } pathTest = null; var target = { shadow: function(inEl) { if (inEl) { return inEl.shadowRoot || inEl.webkitShadowRoot; } }, canTarget: function(shadow) { return shadow && Boolean(shadow.elementFromPoint); }, targetingShadow: function(inEl) { var s = this.shadow(inEl); if (this.canTarget(s)) { return s; } }, olderShadow: function(shadow) { var os = shadow.olderShadowRoot; if (!os) { var se = shadow.querySelector('shadow'); if (se) { os = se.olderShadowRoot; } } return os; }, allShadows: function(element) { var shadows = [], s = this.shadow(element); while(s) { shadows.push(s); s = this.olderShadow(s); } return shadows; }, searchRoot: function(inRoot, x, y) { var t, st, sr, os; if (inRoot) { t = inRoot.elementFromPoint(x, y); if (t) { // found element, check if it has a ShadowRoot sr = this.targetingShadow(t); } else if (inRoot !== document) { // check for sibling roots sr = this.olderShadow(inRoot); } // search other roots, fall back to light dom element return this.searchRoot(sr, x, y) || t; } }, owner: function(element) { if (!element) { return document; } var s = element; // walk up until you hit the shadow root or document while (s.parentNode) { s = s.parentNode; } // the owner element is expected to be a Document or ShadowRoot if (s.nodeType != Node.DOCUMENT_NODE && s.nodeType != Node.DOCUMENT_FRAGMENT_NODE) { s = document; } return s; }, findTarget: function(inEvent) { if (HAS_FULL_PATH && inEvent.path && inEvent.path.length) { return inEvent.path[0]; } var x = inEvent.clientX, y = inEvent.clientY; // if the listener is in the shadow root, it is much faster to start there var s = this.owner(inEvent.target); // if x, y is not in this root, fall back to document search if (!s.elementFromPoint(x, y)) { s = document; } return this.searchRoot(s, x, y); }, findTouchAction: function(inEvent) { var n; if (HAS_FULL_PATH && inEvent.path && inEvent.path.length) { var path = inEvent.path; for (var i = 0; i < path.length; i++) { n = path[i]; if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } } } else { n = inEvent.target; while(n) { if (n.nodeType === Node.ELEMENT_NODE && n.hasAttribute('touch-action')) { return n.getAttribute('touch-action'); } n = n.parentNode || n.host; } } // auto is default return "auto"; }, LCA: function(a, b) { if (a === b) { return a; } if (a && !b) { return a; } if (b && !a) { return b; } if (!b && !a) { return document; } // fast case, a is a direct descendant of b or vice versa if (a.contains && a.contains(b)) { return a; } if (b.contains && b.contains(a)) { return b; } var adepth = this.depth(a); var bdepth = this.depth(b); var d = adepth - bdepth; if (d >= 0) { a = this.walk(a, d); } else { b = this.walk(b, -d); } while (a && b && a !== b) { a = a.parentNode || a.host; b = b.parentNode || b.host; } return a; }, walk: function(n, u) { for (var i = 0; n && (i < u); i++) { n = n.parentNode || n.host; } return n; }, depth: function(n) { var d = 0; while(n) { d++; n = n.parentNode || n.host; } return d; }, deepContains: function(a, b) { var common = this.LCA(a, b); // if a is the common ancestor, it must "deeply" contain b return common === a; }, insideNode: function(node, x, y) { var rect = node.getBoundingClientRect(); return (rect.left <= x) && (x <= rect.right) && (rect.top <= y) && (y <= rect.bottom); }, path: function(event) { var p; if (HAS_FULL_PATH && event.path && event.path.length) { p = event.path; } else { p = []; var n = this.findTarget(event); while (n) { p.push(n); n = n.parentNode || n.host; } } return p; } }; scope.targetFinding = target; /** * Given an event, finds the "deepest" node that could have been the original target before ShadowDOM retargetting * * @param {Event} Event An event object with clientX and clientY properties * @return {Element} The probable event origninator */ scope.findTarget = target.findTarget.bind(target); /** * Determines if the "container" node deeply contains the "containee" node, including situations where the "containee" is contained by one or more ShadowDOM * roots. * * @param {Node} container * @param {Node} containee * @return {Boolean} */ scope.deepContains = target.deepContains.bind(target); /** * Determines if the x/y position is inside the given node. * * Example: * * function upHandler(event) { * var innode = PolymerGestures.insideNode(event.target, event.clientX, event.clientY); * if (innode) { * // wait for tap? * } else { * // tap will never happen * } * } * * @param {Node} node * @param {Number} x Screen X position * @param {Number} y screen Y position * @return {Boolean} */ scope.insideNode = target.insideNode; })(window.PolymerGestures); (function() { function shadowSelector(v) { return 'html /deep/ ' + selector(v); } function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + ';}'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] }, 'manipulation' ]; var styles = ''; // only install stylesheet if the browser has touch action support var hasTouchAction = typeof document.head.style.touchAction === 'string'; // only add shadow selectors if shadowdom is supported var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot; if (hasTouchAction) { attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r) + '\n'; if (hasShadowRoot) { styles += shadowSelector(r) + rule(r) + '\n'; } } else { styles += r.selectors.map(selector) + rule(r.rule) + '\n'; if (hasShadowRoot) { styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n'; } } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); } })(); /** * This is the constructor for new PointerEvents. * * New Pointer Events must be given a type, and an optional dictionary of * initialization properties. * * Due to certain platform requirements, events returned from the constructor * identify as MouseEvents. * * @constructor * @param {String} inType The type of the event to create. * @param {Object} [inDict] An optional dictionary of initial event properties. * @return {Event} A new PointerEvent of type `inType` and initialized with properties from `inDict`. */ (function(scope) { var MOUSE_PROPS = [ 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', 'pageX', 'pageY' ]; var MOUSE_DEFAULTS = [ false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, 0, 0 ]; var NOP_FACTORY = function(){ return function(){}; }; var eventFactory = { // TODO(dfreedm): this is overridden by tap recognizer, needs review preventTap: NOP_FACTORY, makeBaseEvent: function(inType, inDict) { var e = document.createEvent('Event'); e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false); e.preventTap = eventFactory.preventTap(e); return e; }, makeGestureEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); for (var i = 0, keys = Object.keys(inDict), k; i < keys.length; i++) { k = keys[i]; e[k] = inDict[k]; } return e; }, makePointerEvent: function(inType, inDict) { inDict = inDict || Object.create(null); var e = this.makeBaseEvent(inType, inDict); // define inherited MouseEvent properties for(var i = 0, p; i < MOUSE_PROPS.length; i++) { p = MOUSE_PROPS[i]; e[p] = inDict[p] || MOUSE_DEFAULTS[i]; } e.buttons = inDict.buttons || 0; // Spec requires that pointers without pressure specified use 0.5 for down // state and 0 for up state. var pressure = 0; if (inDict.pressure) { pressure = inDict.pressure; } else { pressure = e.buttons ? 0.5 : 0; } // add x/y properties aliased to clientX/Y e.x = e.clientX; e.y = e.clientY; // define the properties of the PointerEvent interface e.pointerId = inDict.pointerId || 0; e.width = inDict.width || 0; e.height = inDict.height || 0; e.pressure = pressure; e.tiltX = inDict.tiltX || 0; e.tiltY = inDict.tiltY || 0; e.pointerType = inDict.pointerType || ''; e.hwTimestamp = inDict.hwTimestamp || 0; e.isPrimary = inDict.isPrimary || false; e._source = inDict._source || ''; return e; } }; scope.eventFactory = eventFactory; })(window.PolymerGestures); /** * This module implements an map of pointer states */ (function(scope) { var USE_MAP = window.Map && window.Map.prototype.forEach; var POINTERS_FN = function(){ return this.size; }; function PointerMap() { if (USE_MAP) { var m = new Map(); m.pointers = POINTERS_FN; return m; } else { this.keys = []; this.values = []; } } PointerMap.prototype = { set: function(inId, inEvent) { var i = this.keys.indexOf(inId); if (i > -1) { this.values[i] = inEvent; } else { this.keys.push(inId); this.values.push(inEvent); } }, has: function(inId) { return this.keys.indexOf(inId) > -1; }, 'delete': function(inId) { var i = this.keys.indexOf(inId); if (i > -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } }, get: function(inId) { var i = this.keys.indexOf(inId); return this.values[i]; }, clear: function() { this.keys.length = 0; this.values.length = 0; }, // return value, key, map forEach: function(callback, thisArg) { this.values.forEach(function(v, i) { callback.call(thisArg, v, this.keys[i], this); }, this); }, pointers: function() { return this.keys.length; } }; scope.PointerMap = PointerMap; })(window.PolymerGestures); (function(scope) { var CLONE_PROPS = [ // MouseEvent 'bubbles', 'cancelable', 'view', 'detail', 'screenX', 'screenY', 'clientX', 'clientY', 'ctrlKey', 'altKey', 'shiftKey', 'metaKey', 'button', 'relatedTarget', // DOM Level 3 'buttons', // PointerEvent 'pointerId', 'width', 'height', 'pressure', 'tiltX', 'tiltY', 'pointerType', 'hwTimestamp', 'isPrimary', // event instance 'type', 'target', 'currentTarget', 'which', 'pageX', 'pageY', 'timeStamp', // gesture addons 'preventTap', 'tapPrevented', '_source' ]; var CLONE_DEFAULTS = [ // MouseEvent false, false, null, null, 0, 0, 0, 0, false, false, false, false, 0, null, // DOM Level 3 0, // PointerEvent 0, 0, 0, 0, 0, 0, '', 0, false, // event instance '', null, null, 0, 0, 0, 0, function(){}, false ]; var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined'); var eventFactory = scope.eventFactory; // set of recognizers to run for the currently handled event var currentGestures; /** * This module is for normalizing events. Mouse and Touch events will be * collected here, and fire PointerEvents that have the same semantics, no * matter the source. * Events fired: * - pointerdown: a pointing is added * - pointerup: a pointer is removed * - pointermove: a pointer is moved * - pointerover: a pointer crosses into an element * - pointerout: a pointer leaves an element * - pointercancel: a pointer will no longer generate events */ var dispatcher = { IS_IOS: false, pointermap: new scope.PointerMap(), requiredGestures: new scope.PointerMap(), eventMap: Object.create(null), // Scope objects for native events. // This exists for ease of testing. eventSources: Object.create(null), eventSourceList: [], gestures: [], // map gesture event -> {listeners: int, index: gestures[int]} dependencyMap: { // make sure down and up are in the map to trigger "register" down: {listeners: 0, index: -1}, up: {listeners: 0, index: -1} }, gestureQueue: [], /** * Add a new event source that will generate pointer events. * * `inSource` must contain an array of event names named `events`, and * functions with the names specified in the `events` array. * @param {string} name A name for the event source * @param {Object} source A new source of platform events. */ registerSource: function(name, source) { var s = source; var newEvents = s.events; if (newEvents) { newEvents.forEach(function(e) { if (s[e]) { this.eventMap[e] = s[e].bind(s); } }, this); this.eventSources[name] = s; this.eventSourceList.push(s); } }, registerGesture: function(name, source) { var obj = Object.create(null); obj.listeners = 0; obj.index = this.gestures.length; for (var i = 0, g; i < source.exposes.length; i++) { g = source.exposes[i].toLowerCase(); this.dependencyMap[g] = obj; } this.gestures.push(source); }, register: function(element, initial) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.register.call(es, element, initial); } }, unregister: function(element) { var l = this.eventSourceList.length; for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) { // call eventsource register es.unregister.call(es, element); } }, // EVENTS down: function(inEvent) { this.requiredGestures.set(inEvent.pointerId, currentGestures); this.fireEvent('down', inEvent); }, move: function(inEvent) { // pipe move events into gesture queue directly inEvent.type = 'move'; this.fillGestureQueue(inEvent); }, up: function(inEvent) { this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, cancel: function(inEvent) { inEvent.tapPrevented = true; this.fireEvent('up', inEvent); this.requiredGestures.delete(inEvent.pointerId); }, addGestureDependency: function(node, currentGestures) { var gesturesWanted = node._pgEvents; if (gesturesWanted && currentGestures) { var gk = Object.keys(gesturesWanted); for (var i = 0, r, ri, g; i < gk.length; i++) { // gesture g = gk[i]; if (gesturesWanted[g] > 0) { // lookup gesture recognizer r = this.dependencyMap[g]; // recognizer index ri = r ? r.index : -1; currentGestures[ri] = true; } } } }, // LISTENER LOGIC eventHandler: function(inEvent) { // This is used to prevent multiple dispatch of events from // platform events. This can happen when two elements in different scopes // are set up to create pointer events, which is relevant to Shadow DOM. var type = inEvent.type; // only generate the list of desired events on "down" if (type === 'touchstart' || type === 'mousedown' || type === 'pointerdown' || type === 'MSPointerDown') { if (!inEvent._handledByPG) { currentGestures = {}; } // in IOS mode, there is only a listener on the document, so this is not re-entrant if (this.IS_IOS) { var ev = inEvent; if (type === 'touchstart') { var ct = inEvent.changedTouches[0]; // set up a fake event to give to the path builder ev = {target: inEvent.target, clientX: ct.clientX, clientY: ct.clientY, path: inEvent.path}; } // use event path if available, otherwise build a path from target finding var nodes = inEvent.path || scope.targetFinding.path(ev); for (var i = 0, n; i < nodes.length; i++) { n = nodes[i]; this.addGestureDependency(n, currentGestures); } } else { this.addGestureDependency(inEvent.currentTarget, currentGestures); } } if (inEvent._handledByPG) { return; } var fn = this.eventMap && this.eventMap[type]; if (fn) { fn(inEvent); } inEvent._handledByPG = true; }, // set up event listeners listen: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.addEvent(target, e); } }, // remove event listeners unlisten: function(target, events) { for (var i = 0, l = events.length, e; (i < l) && (e = events[i]); i++) { this.removeEvent(target, e); } }, addEvent: function(target, eventName) { target.addEventListener(eventName, this.boundHandler); }, removeEvent: function(target, eventName) { target.removeEventListener(eventName, this.boundHandler); }, // EVENT CREATION AND TRACKING /** * Creates a new Event of type `inType`, based on the information in * `inEvent`. * * @param {string} inType A string representing the type of event to create * @param {Event} inEvent A platform event with a target * @return {Event} A PointerEvent of type `inType` */ makeEvent: function(inType, inEvent) { var e = eventFactory.makePointerEvent(inType, inEvent); e.preventDefault = inEvent.preventDefault; e.tapPrevented = inEvent.tapPrevented; e._target = e._target || inEvent.target; return e; }, // make and dispatch an event in one call fireEvent: function(inType, inEvent) { var e = this.makeEvent(inType, inEvent); return this.dispatchEvent(e); }, /** * Returns a snapshot of inEvent, with writable properties. * * @param {Event} inEvent An event that contains properties to copy. * @return {Object} An object containing shallow copies of `inEvent`'s * properties. */ cloneEvent: function(inEvent) { var eventCopy = Object.create(null), p; for (var i = 0; i < CLONE_PROPS.length; i++) { p = CLONE_PROPS[i]; eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i]; // Work around SVGInstanceElement shadow tree // Return the <use> element that is represented by the instance for Safari, Chrome, IE. // This is the behavior implemented by Firefox. if (p === 'target' || p === 'relatedTarget') { if (HAS_SVG_INSTANCE && eventCopy[p] instanceof SVGElementInstance) { eventCopy[p] = eventCopy[p].correspondingUseElement; } } } // keep the semantics of preventDefault eventCopy.preventDefault = function() { inEvent.preventDefault(); }; return eventCopy; }, /** * Dispatches the event to its target. * * @param {Event} inEvent The event to be dispatched. * @return {Boolean} True if an event handler returns true, false otherwise. */ dispatchEvent: function(inEvent) { var t = inEvent._target; if (t) { t.dispatchEvent(inEvent); // clone the event for the gesture system to process // clone after dispatch to pick up gesture prevention code var clone = this.cloneEvent(inEvent); clone.target = t; this.fillGestureQueue(clone); } }, gestureTrigger: function() { // process the gesture queue for (var i = 0, e, rg; i < this.gestureQueue.length; i++) { e = this.gestureQueue[i]; rg = e._requiredGestures; if (rg) { for (var j = 0, g, fn; j < this.gestures.length; j++) { // only run recognizer if an element in the source event's path is listening for those gestures if (rg[j]) { g = this.gestures[j]; fn = g[e.type]; if (fn) { fn.call(g, e); } } } } } this.gestureQueue.length = 0; }, fillGestureQueue: function(ev) { // only trigger the gesture queue once if (!this.gestureQueue.length) { requestAnimationFrame(this.boundGestureTrigger); } ev._requiredGestures = this.requiredGestures.get(ev.pointerId); this.gestureQueue.push(ev); } }; dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher); dispatcher.boundGestureTrigger = dispatcher.gestureTrigger.bind(dispatcher); scope.dispatcher = dispatcher; /** * Listen for `gesture` on `node` with the `handler` function * * If `handler` is the first listener for `gesture`, the underlying gesture recognizer is then enabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.activateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { var recognizer = dispatcher.gestures[dep.index]; if (!node._pgListeners) { dispatcher.register(node); node._pgListeners = 0; } // TODO(dfreedm): re-evaluate bookkeeping to avoid using attributes if (recognizer) { var touchAction = recognizer.defaultActions && recognizer.defaultActions[g]; var actionNode; switch(node.nodeType) { case Node.ELEMENT_NODE: actionNode = node; break; case Node.DOCUMENT_FRAGMENT_NODE: actionNode = node.host; break; default: actionNode = null; break; } if (touchAction && actionNode && !actionNode.hasAttribute('touch-action')) { actionNode.setAttribute('touch-action', touchAction); } } if (!node._pgEvents) { node._pgEvents = {}; } node._pgEvents[g] = (node._pgEvents[g] || 0) + 1; node._pgListeners++; } return Boolean(dep); }; /** * * Listen for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.addEventListener = function(node, gesture, handler, capture) { if (handler) { scope.activateGesture(node, gesture); node.addEventListener(gesture, handler, capture); } }; /** * Tears down the gesture configuration for `node` * * If `handler` is the last listener for `gesture`, the underlying gesture recognizer is disabled. * * @param {Element} node * @param {string} gesture * @return Boolean `gesture` is a valid gesture */ scope.deactivateGesture = function(node, gesture) { var g = gesture.toLowerCase(); var dep = dispatcher.dependencyMap[g]; if (dep) { if (node._pgListeners > 0) { node._pgListeners--; } if (node._pgListeners === 0) { dispatcher.unregister(node); } if (node._pgEvents) { if (node._pgEvents[g] > 0) { node._pgEvents[g]--; } else { node._pgEvents[g] = 0; } } } return Boolean(dep); }; /** * Stop listening for `gesture` from `node` with `handler` function. * * @param {Element} node * @param {string} gesture * @param {Function} handler * @param {Boolean} capture */ scope.removeEventListener = function(node, gesture, handler, capture) { if (handler) { scope.deactivateGesture(node, gesture); node.removeEventListener(gesture, handler, capture); } }; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; // radius around touchend that swallows mouse events var DEDUP_DIST = 25; var WHICH_TO_BUTTONS = [0, 1, 4, 2]; var CURRENT_BUTTONS = 0; var FIREFOX_LINUX = /Linux.*Firefox\//i; var HAS_BUTTONS = (function() { // firefox on linux returns spec-incorrect values for mouseup.buttons // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.buttons#See_also // https://codereview.chromium.org/727593003/#msg16 if (FIREFOX_LINUX.test(navigator.userAgent)) { return false; } try { return new MouseEvent('test', {buttons: 1}).buttons === 1; } catch (e) { return false; } })(); // handler block for native mouse events var mouseEvents = { POINTER_ID: 1, POINTER_TYPE: 'mouse', events: [ 'mousedown', 'mousemove', 'mouseup' ], exposes: [ 'down', 'up', 'move' ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, lastTouches: [], // collide with the global mouse listener isEventSimulatedFromTouch: function(inEvent) { var lts = this.lastTouches; var x = inEvent.clientX, y = inEvent.clientY; for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) { // simulated mouse events will be swallowed near a primary touchend var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) { return true; } } }, prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e.pointerId = this.POINTER_ID; e.isPrimary = true; e.pointerType = this.POINTER_TYPE; e._source = 'mouse'; if (!HAS_BUTTONS) { var type = inEvent.type; var bit = WHICH_TO_BUTTONS[inEvent.which] || 0; if (type === 'mousedown') { CURRENT_BUTTONS |= bit; } else if (type === 'mouseup') { CURRENT_BUTTONS &= ~bit; } e.buttons = CURRENT_BUTTONS; } return e; }, mousedown: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var p = pointermap.has(this.POINTER_ID); var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(this.POINTER_ID, e.target); dispatcher.down(e); } }, mousemove: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var target = pointermap.get(this.POINTER_ID); if (target) { var e = this.prepareEvent(inEvent); e.target = target; // handle case where we missed a mouseup if ((HAS_BUTTONS ? e.buttons : e.which) === 0) { if (!HAS_BUTTONS) { CURRENT_BUTTONS = e.buttons = 0; } dispatcher.cancel(e); this.cleanupMouse(e.buttons); } else { dispatcher.move(e); } } } }, mouseup: function(inEvent) { if (!this.isEventSimulatedFromTouch(inEvent)) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(this.POINTER_ID); dispatcher.up(e); this.cleanupMouse(e.buttons); } }, cleanupMouse: function(buttons) { if (buttons === 0) { pointermap.delete(this.POINTER_ID); } } }; scope.mouseEvents = mouseEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var allShadows = scope.targetFinding.allShadows.bind(scope.targetFinding); var pointermap = dispatcher.pointermap; var touchMap = Array.prototype.map.call.bind(Array.prototype.map); // This should be long enough to ignore compat mouse events made by touch var DEDUP_TIMEOUT = 2500; var DEDUP_DIST = 25; var CLICK_COUNT_TIMEOUT = 200; var HYSTERESIS = 20; var ATTRIB = 'touch-action'; // TODO(dfreedm): disable until http://crbug.com/399765 is resolved // var HAS_TOUCH_ACTION = ATTRIB in document.head.style; var HAS_TOUCH_ACTION = false; // handler block for native touch events var touchEvents = { IS_IOS: false, events: [ 'touchstart', 'touchmove', 'touchend', 'touchcancel' ], exposes: [ 'down', 'up', 'move' ], register: function(target, initial) { if (this.IS_IOS ? initial : !initial) { dispatcher.listen(target, this.events); } }, unregister: function(target) { if (!this.IS_IOS) { dispatcher.unlisten(target, this.events); } }, scrollTypes: { EMITTER: 'none', XSCROLLER: 'pan-x', YSCROLLER: 'pan-y', }, touchActionToScrollType: function(touchAction) { var t = touchAction; var st = this.scrollTypes; if (t === st.EMITTER) { return 'none'; } else if (t === st.XSCROLLER) { return 'X'; } else if (t === st.YSCROLLER) { return 'Y'; } else { return 'XY'; } }, POINTER_TYPE: 'touch', firstTouch: null, isPrimaryTouch: function(inTouch) { return this.firstTouch === inTouch.identifier; }, setPrimaryTouch: function(inTouch) { // set primary touch if there no pointers, or the only pointer is the mouse if (pointermap.pointers() === 0 || (pointermap.pointers() === 1 && pointermap.has(1))) { this.firstTouch = inTouch.identifier; this.firstXY = {X: inTouch.clientX, Y: inTouch.clientY}; this.firstTarget = inTouch.target; this.scrolling = null; this.cancelResetClickCount(); } }, removePrimaryPointer: function(inPointer) { if (inPointer.isPrimary) { this.firstTouch = null; this.firstXY = null; this.resetClickCount(); } }, clickCount: 0, resetId: null, resetClickCount: function() { var fn = function() { this.clickCount = 0; this.resetId = null; }.bind(this); this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT); }, cancelResetClickCount: function() { if (this.resetId) { clearTimeout(this.resetId); } }, typeToButtons: function(type) { var ret = 0; if (type === 'touchstart' || type === 'touchmove') { ret = 1; } return ret; }, findTarget: function(touch, id) { if (this.currentTouchEvent.type === 'touchstart') { if (this.isPrimaryTouch(touch)) { var fastPath = { clientX: touch.clientX, clientY: touch.clientY, path: this.currentTouchEvent.path, target: this.currentTouchEvent.target }; return scope.findTarget(fastPath); } else { return scope.findTarget(touch); } } // reuse target we found in touchstart return pointermap.get(id); }, touchToPointer: function(inTouch) { var cte = this.currentTouchEvent; var e = dispatcher.cloneEvent(inTouch); // Spec specifies that pointerId 1 is reserved for Mouse. // Touch identifiers can start at 0. // Add 2 to the touch identifier for compatibility. var id = e.pointerId = inTouch.identifier + 2; e.target = this.findTarget(inTouch, id); e.bubbles = true; e.cancelable = true; e.detail = this.clickCount; e.buttons = this.typeToButtons(cte.type); e.width = inTouch.webkitRadiusX || inTouch.radiusX || 0; e.height = inTouch.webkitRadiusY || inTouch.radiusY || 0; e.pressure = inTouch.webkitForce || inTouch.force || 0.5; e.isPrimary = this.isPrimaryTouch(inTouch); e.pointerType = this.POINTER_TYPE; e._source = 'touch'; // forward touch preventDefaults var self = this; e.preventDefault = function() { self.scrolling = false; self.firstXY = null; cte.preventDefault(); }; return e; }, processTouches: function(inEvent, inFunction) { var tl = inEvent.changedTouches; this.currentTouchEvent = inEvent; for (var i = 0, t, p; i < tl.length; i++) { t = tl[i]; p = this.touchToPointer(t); if (inEvent.type === 'touchstart') { pointermap.set(p.pointerId, p.target); } if (pointermap.has(p.pointerId)) { inFunction.call(this, p); } if (inEvent.type === 'touchend' || inEvent._cancel) { this.cleanUpPointer(p); } } }, // For single axis scrollers, determines whether the element should emit // pointer events or behave as a scroller shouldScroll: function(inEvent) { if (this.firstXY) { var ret; var touchAction = scope.targetFinding.findTouchAction(inEvent); var scrollAxis = this.touchActionToScrollType(touchAction); if (scrollAxis === 'none') { // this element is a touch-action: none, should never scroll ret = false; } else if (scrollAxis === 'XY') { // this element should always scroll ret = true; } else { var t = inEvent.changedTouches[0]; // check the intended scroll axis, and other axis var a = scrollAxis; var oa = scrollAxis === 'Y' ? 'X' : 'Y'; var da = Math.abs(t['client' + a] - this.firstXY[a]); var doa = Math.abs(t['client' + oa] - this.firstXY[oa]); // if delta in the scroll axis > delta other axis, scroll instead of // making events ret = da >= doa; } return ret; } }, findTouch: function(inTL, inId) { for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) { if (t.identifier === inId) { return true; } } }, // In some instances, a touchstart can happen without a touchend. This // leaves the pointermap in a broken state. // Therefore, on every touchstart, we remove the touches that did not fire a // touchend event. // To keep state globally consistent, we fire a // pointercancel for this "abandoned" touch vacuumTouches: function(inEvent) { var tl = inEvent.touches; // pointermap.pointers() should be < tl.length here, as the touchstart has not // been processed yet. if (pointermap.pointers() >= tl.length) { var d = []; pointermap.forEach(function(value, key) { // Never remove pointerId == 1, which is mouse. // Touch identifiers are 2 smaller than their pointerId, which is the // index in pointermap. if (key !== 1 && !this.findTouch(tl, key - 2)) { var p = value; d.push(p); } }, this); d.forEach(function(p) { this.cancel(p); pointermap.delete(p.pointerId); }, this); } }, touchstart: function(inEvent) { this.vacuumTouches(inEvent); this.setPrimaryTouch(inEvent.changedTouches[0]); this.dedupSynthMouse(inEvent); if (!this.scrolling) { this.clickCount++; this.processTouches(inEvent, this.down); } }, down: function(inPointer) { dispatcher.down(inPointer); }, touchmove: function(inEvent) { if (HAS_TOUCH_ACTION) { // touchevent.cancelable == false is sent when the page is scrolling under native Touch Action in Chrome 36 // https://groups.google.com/a/chromium.org/d/msg/input-dev/wHnyukcYBcA/b9kmtwM1jJQJ if (inEvent.cancelable) { this.processTouches(inEvent, this.move); } } else { if (!this.scrolling) { if (this.scrolling === null && this.shouldScroll(inEvent)) { this.scrolling = true; } else { this.scrolling = false; inEvent.preventDefault(); this.processTouches(inEvent, this.move); } } else if (this.firstXY) { var t = inEvent.changedTouches[0]; var dx = t.clientX - this.firstXY.X; var dy = t.clientY - this.firstXY.Y; var dd = Math.sqrt(dx * dx + dy * dy); if (dd >= HYSTERESIS) { this.touchcancel(inEvent); this.scrolling = true; this.firstXY = null; } } } }, move: function(inPointer) { dispatcher.move(inPointer); }, touchend: function(inEvent) { this.dedupSynthMouse(inEvent); this.processTouches(inEvent, this.up); }, up: function(inPointer) { inPointer.relatedTarget = scope.findTarget(inPointer); dispatcher.up(inPointer); }, cancel: function(inPointer) { dispatcher.cancel(inPointer); }, touchcancel: function(inEvent) { inEvent._cancel = true; this.processTouches(inEvent, this.cancel); }, cleanUpPointer: function(inPointer) { pointermap['delete'](inPointer.pointerId); this.removePrimaryPointer(inPointer); }, // prevent synth mouse events from creating pointer events dedupSynthMouse: function(inEvent) { var lts = scope.mouseEvents.lastTouches; var t = inEvent.changedTouches[0]; // only the primary finger will synth mouse events if (this.isPrimaryTouch(t)) { // remember x/y of last touch var lt = {x: t.clientX, y: t.clientY}; lts.push(lt); var fn = (function(lts, lt){ var i = lts.indexOf(lt); if (i > -1) { lts.splice(i, 1); } }).bind(null, lts, lt); setTimeout(fn, DEDUP_TIMEOUT); } } }; // prevent "ghost clicks" that come from elements that were removed in a touch handler var STOP_PROP_FN = Event.prototype.stopImmediatePropagation || Event.prototype.stopPropagation; document.addEventListener('click', function(ev) { var x = ev.clientX, y = ev.clientY; // check if a click is within DEDUP_DIST px radius of the touchstart var closeTo = function(touch) { var dx = Math.abs(x - touch.x), dy = Math.abs(y - touch.y); return (dx <= DEDUP_DIST && dy <= DEDUP_DIST); }; // if click coordinates are close to touch coordinates, assume the click came from a touch var wasTouched = scope.mouseEvents.lastTouches.some(closeTo); // if the click came from touch, and the touchstart target is not in the path of the click event, // then the touchstart target was probably removed, and the click should be "busted" var path = scope.targetFinding.path(ev); if (wasTouched) { for (var i = 0; i < path.length; i++) { if (path[i] === touchEvents.firstTarget) { return; } } ev.preventDefault(); STOP_PROP_FN.call(ev); } }, true); scope.touchEvents = touchEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var HAS_BITMAP_TYPE = window.MSPointerEvent && typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number'; var msEvents = { events: [ 'MSPointerDown', 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel', ], register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, POINTER_TYPES: [ '', 'unavailable', 'touch', 'pen', 'mouse' ], prepareEvent: function(inEvent) { var e = inEvent; e = dispatcher.cloneEvent(inEvent); if (HAS_BITMAP_TYPE) { e.pointerType = this.POINTER_TYPES[inEvent.pointerType]; } e._source = 'ms'; return e; }, cleanup: function(id) { pointermap['delete'](id); }, MSPointerDown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(inEvent.pointerId, e.target); dispatcher.down(e); }, MSPointerMove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, MSPointerUp: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, MSPointerCancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.msEvents = msEvents; })(window.PolymerGestures); (function(scope) { var dispatcher = scope.dispatcher; var pointermap = dispatcher.pointermap; var pointerEvents = { events: [ 'pointerdown', 'pointermove', 'pointerup', 'pointercancel' ], prepareEvent: function(inEvent) { var e = dispatcher.cloneEvent(inEvent); e._source = 'pointer'; return e; }, register: function(target) { dispatcher.listen(target, this.events); }, unregister: function(target) { if (target === document) { return; } dispatcher.unlisten(target, this.events); }, cleanup: function(id) { pointermap['delete'](id); }, pointerdown: function(inEvent) { var e = this.prepareEvent(inEvent); e.target = scope.findTarget(inEvent); pointermap.set(e.pointerId, e.target); dispatcher.down(e); }, pointermove: function(inEvent) { var target = pointermap.get(inEvent.pointerId); if (target) { var e = this.prepareEvent(inEvent); e.target = target; dispatcher.move(e); } }, pointerup: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.up(e); this.cleanup(inEvent.pointerId); }, pointercancel: function(inEvent) { var e = this.prepareEvent(inEvent); e.relatedTarget = scope.findTarget(inEvent); e.target = pointermap.get(e.pointerId); dispatcher.cancel(e); this.cleanup(inEvent.pointerId); } }; scope.pointerEvents = pointerEvents; })(window.PolymerGestures); /** * This module contains the handlers for native platform events. * From here, the dispatcher is called to create unified pointer events. * Included are touch events (v1), mouse events, and MSPointerEvents. */ (function(scope) { var dispatcher = scope.dispatcher; var nav = window.navigator; if (window.PointerEvent) { dispatcher.registerSource('pointer', scope.pointerEvents); } else if (nav.msPointerEnabled) { dispatcher.registerSource('ms', scope.msEvents); } else { dispatcher.registerSource('mouse', scope.mouseEvents); if (window.ontouchstart !== undefined) { dispatcher.registerSource('touch', scope.touchEvents); } } // Work around iOS bugs https://bugs.webkit.org/show_bug.cgi?id=135628 and https://bugs.webkit.org/show_bug.cgi?id=136506 var ua = navigator.userAgent; var IS_IOS = ua.match(/iPad|iPhone|iPod/) && 'ontouchstart' in window; dispatcher.IS_IOS = IS_IOS; scope.touchEvents.IS_IOS = IS_IOS; dispatcher.register(document, true); })(window.PolymerGestures); /** * This event denotes the beginning of a series of tracking events. * * @module PointerGestures * @submodule Events * @class trackstart */ /** * Pixels moved in the x direction since trackstart. * @type Number * @property dx */ /** * Pixes moved in the y direction since trackstart. * @type Number * @property dy */ /** * Pixels moved in the x direction since the last track. * @type Number * @property ddx */ /** * Pixles moved in the y direction since the last track. * @type Number * @property ddy */ /** * The clientX position of the track gesture. * @type Number * @property clientX */ /** * The clientY position of the track gesture. * @type Number * @property clientY */ /** * The pageX position of the track gesture. * @type Number * @property pageX */ /** * The pageY position of the track gesture. * @type Number * @property pageY */ /** * The screenX position of the track gesture. * @type Number * @property screenX */ /** * The screenY position of the track gesture. * @type Number * @property screenY */ /** * The last x axis direction of the pointer. * @type Number * @property xDirection */ /** * The last y axis direction of the pointer. * @type Number * @property yDirection */ /** * A shared object between all tracking events. * @type Object * @property trackInfo */ /** * The element currently under the pointer. * @type Element * @property relatedTarget */ /** * The type of pointer that make the track gesture. * @type String * @property pointerType */ /** * * This event fires for all pointer movement being tracked. * * @class track * @extends trackstart */ /** * This event fires when the pointer is no longer being tracked. * * @class trackend * @extends trackstart */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var track = { events: [ 'down', 'move', 'up', ], exposes: [ 'trackstart', 'track', 'trackx', 'tracky', 'trackend' ], defaultActions: { 'track': 'none', 'trackx': 'pan-y', 'tracky': 'pan-x' }, WIGGLE_THRESHOLD: 4, clampDir: function(inDelta) { return inDelta > 0 ? 1 : -1; }, calcPositionDelta: function(inA, inB) { var x = 0, y = 0; if (inA && inB) { x = inB.pageX - inA.pageX; y = inB.pageY - inA.pageY; } return {x: x, y: y}; }, fireTrack: function(inType, inEvent, inTrackingData) { var t = inTrackingData; var d = this.calcPositionDelta(t.downEvent, inEvent); var dd = this.calcPositionDelta(t.lastMoveEvent, inEvent); if (dd.x) { t.xDirection = this.clampDir(dd.x); } else if (inType === 'trackx') { return; } if (dd.y) { t.yDirection = this.clampDir(dd.y); } else if (inType === 'tracky') { return; } var gestureProto = { bubbles: true, cancelable: true, trackInfo: t.trackInfo, relatedTarget: inEvent.relatedTarget, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, _source: 'track' }; if (inType !== 'tracky') { gestureProto.x = inEvent.x; gestureProto.dx = d.x; gestureProto.ddx = dd.x; gestureProto.clientX = inEvent.clientX; gestureProto.pageX = inEvent.pageX; gestureProto.screenX = inEvent.screenX; gestureProto.xDirection = t.xDirection; } if (inType !== 'trackx') { gestureProto.dy = d.y; gestureProto.ddy = dd.y; gestureProto.y = inEvent.y; gestureProto.clientY = inEvent.clientY; gestureProto.pageY = inEvent.pageY; gestureProto.screenY = inEvent.screenY; gestureProto.yDirection = t.yDirection; } var e = eventFactory.makeGestureEvent(inType, gestureProto); t.downTarget.dispatchEvent(e); }, down: function(inEvent) { if (inEvent.isPrimary && (inEvent.pointerType === 'mouse' ? inEvent.buttons === 1 : true)) { var p = { downEvent: inEvent, downTarget: inEvent.target, trackInfo: {}, lastMoveEvent: null, xDirection: 0, yDirection: 0, tracking: false }; pointermap.set(inEvent.pointerId, p); } }, move: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (!p.tracking) { var d = this.calcPositionDelta(p.downEvent, inEvent); var move = d.x * d.x + d.y * d.y; // start tracking only if finger moves more than WIGGLE_THRESHOLD if (move > this.WIGGLE_THRESHOLD) { p.tracking = true; p.lastMoveEvent = p.downEvent; this.fireTrack('trackstart', inEvent, p); } } if (p.tracking) { this.fireTrack('track', inEvent, p); this.fireTrack('trackx', inEvent, p); this.fireTrack('tracky', inEvent, p); } p.lastMoveEvent = inEvent; } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); if (p) { if (p.tracking) { this.fireTrack('trackend', inEvent, p); } pointermap.delete(inEvent.pointerId); } } }; dispatcher.registerGesture('track', track); })(window.PolymerGestures); /** * This event is fired when a pointer is held down for 200ms. * * @module PointerGestures * @submodule Events * @class hold */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * Screen X axis position of the held pointer * @type Number * @property clientX */ /** * Screen Y axis position of the held pointer * @type Number * @property clientY */ /** * Type of pointer that made the holding event. * @type String * @property pointerType */ /** * This event is fired every 200ms while a pointer is held down. * * @class holdpulse * @extends hold */ /** * Milliseconds pointer has been held down. * @type Number * @property holdTime */ /** * This event is fired when a held pointer is released or moved. * * @class release */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var hold = { // wait at least HOLD_DELAY ms between hold and pulse events HOLD_DELAY: 200, // pointer can move WIGGLE_THRESHOLD pixels before not counting as a hold WIGGLE_THRESHOLD: 16, events: [ 'down', 'move', 'up', ], exposes: [ 'hold', 'holdpulse', 'release' ], heldPointer: null, holdJob: null, pulse: function() { var hold = Date.now() - this.heldPointer.timeStamp; var type = this.held ? 'holdpulse' : 'hold'; this.fireHold(type, hold); this.held = true; }, cancel: function() { clearInterval(this.holdJob); if (this.held) { this.fireHold('release'); } this.held = false; this.heldPointer = null; this.target = null; this.holdJob = null; }, down: function(inEvent) { if (inEvent.isPrimary && !this.heldPointer) { this.heldPointer = inEvent; this.target = inEvent.target; this.holdJob = setInterval(this.pulse.bind(this), this.HOLD_DELAY); } }, up: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { this.cancel(); } }, move: function(inEvent) { if (this.heldPointer && this.heldPointer.pointerId === inEvent.pointerId) { var x = inEvent.clientX - this.heldPointer.clientX; var y = inEvent.clientY - this.heldPointer.clientY; if ((x * x + y * y) > this.WIGGLE_THRESHOLD) { this.cancel(); } } }, fireHold: function(inType, inHoldTime) { var p = { bubbles: true, cancelable: true, pointerType: this.heldPointer.pointerType, pointerId: this.heldPointer.pointerId, x: this.heldPointer.clientX, y: this.heldPointer.clientY, _source: 'hold' }; if (inHoldTime) { p.holdTime = inHoldTime; } var e = eventFactory.makeGestureEvent(inType, p); this.target.dispatchEvent(e); } }; dispatcher.registerGesture('hold', hold); })(window.PolymerGestures); /** * This event is fired when a pointer quickly goes down and up, and is used to * denote activation. * * Any gesture event can prevent the tap event from being created by calling * `event.preventTap`. * * Any pointer event can prevent the tap by setting the `tapPrevented` property * on itself. * * @module PointerGestures * @submodule Events * @class tap */ /** * X axis position of the tap. * @property x * @type Number */ /** * Y axis position of the tap. * @property y * @type Number */ /** * Type of the pointer that made the tap. * @property pointerType * @type String */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var tap = { events: [ 'down', 'up' ], exposes: [ 'tap' ], down: function(inEvent) { if (inEvent.isPrimary && !inEvent.tapPrevented) { pointermap.set(inEvent.pointerId, { target: inEvent.target, buttons: inEvent.buttons, x: inEvent.clientX, y: inEvent.clientY }); } }, shouldTap: function(e, downState) { var tap = true; if (e.pointerType === 'mouse') { // only allow left click to tap for mouse tap = (e.buttons ^ 1) && (downState.buttons & 1); } return tap && !e.tapPrevented; }, up: function(inEvent) { var start = pointermap.get(inEvent.pointerId); if (start && this.shouldTap(inEvent, start)) { // up.relatedTarget is target currently under finger var t = scope.targetFinding.LCA(start.target, inEvent.relatedTarget); if (t) { var e = eventFactory.makeGestureEvent('tap', { bubbles: true, cancelable: true, x: inEvent.clientX, y: inEvent.clientY, detail: inEvent.detail, pointerType: inEvent.pointerType, pointerId: inEvent.pointerId, altKey: inEvent.altKey, ctrlKey: inEvent.ctrlKey, metaKey: inEvent.metaKey, shiftKey: inEvent.shiftKey, _source: 'tap' }); t.dispatchEvent(e); } } pointermap.delete(inEvent.pointerId); } }; // patch eventFactory to remove id from tap's pointermap for preventTap calls eventFactory.preventTap = function(e) { return function() { e.tapPrevented = true; pointermap.delete(e.pointerId); }; }; dispatcher.registerGesture('tap', tap); })(window.PolymerGestures); /* * Basic strategy: find the farthest apart points, use as diameter of circle * react to size change and rotation of the chord */ /** * @module pointer-gestures * @submodule Events * @class pinch */ /** * Scale of the pinch zoom gesture * @property scale * @type Number */ /** * Center X position of pointers causing pinch * @property centerX * @type Number */ /** * Center Y position of pointers causing pinch * @property centerY * @type Number */ /** * @module pointer-gestures * @submodule Events * @class rotate */ /** * Angle (in degrees) of rotation. Measured from starting positions of pointers. * @property angle * @type Number */ /** * Center X position of pointers causing rotation * @property centerX * @type Number */ /** * Center Y position of pointers causing rotation * @property centerY * @type Number */ (function(scope) { var dispatcher = scope.dispatcher; var eventFactory = scope.eventFactory; var pointermap = new scope.PointerMap(); var RAD_TO_DEG = 180 / Math.PI; var pinch = { events: [ 'down', 'up', 'move', 'cancel' ], exposes: [ 'pinchstart', 'pinch', 'pinchend', 'rotate' ], defaultActions: { 'pinch': 'none', 'rotate': 'none' }, reference: {}, down: function(inEvent) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() == 2) { var points = this.calcChord(); var angle = this.calcAngle(points); this.reference = { angle: angle, diameter: points.diameter, target: scope.targetFinding.LCA(points.a.target, points.b.target) }; this.firePinch('pinchstart', points.diameter, points); } }, up: function(inEvent) { var p = pointermap.get(inEvent.pointerId); var num = pointermap.pointers(); if (p) { if (num === 2) { // fire 'pinchend' before deleting pointer var points = this.calcChord(); this.firePinch('pinchend', points.diameter, points); } pointermap.delete(inEvent.pointerId); } }, move: function(inEvent) { if (pointermap.has(inEvent.pointerId)) { pointermap.set(inEvent.pointerId, inEvent); if (pointermap.pointers() > 1) { this.calcPinchRotate(); } } }, cancel: function(inEvent) { this.up(inEvent); }, firePinch: function(type, diameter, points) { var zoom = diameter / this.reference.diameter; var e = eventFactory.makeGestureEvent(type, { bubbles: true, cancelable: true, scale: zoom, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, fireRotate: function(angle, points) { var diff = Math.round((angle - this.reference.angle) % 360); var e = eventFactory.makeGestureEvent('rotate', { bubbles: true, cancelable: true, angle: diff, centerX: points.center.x, centerY: points.center.y, _source: 'pinch' }); this.reference.target.dispatchEvent(e); }, calcPinchRotate: function() { var points = this.calcChord(); var diameter = points.diameter; var angle = this.calcAngle(points); if (diameter != this.reference.diameter) { this.firePinch('pinch', diameter, points); } if (angle != this.reference.angle) { this.fireRotate(angle, points); } }, calcChord: function() { var pointers = []; pointermap.forEach(function(p) { pointers.push(p); }); var dist = 0; // start with at least two pointers var points = {a: pointers[0], b: pointers[1]}; var x, y, d; for (var i = 0; i < pointers.length; i++) { var a = pointers[i]; for (var j = i + 1; j < pointers.length; j++) { var b = pointers[j]; x = Math.abs(a.clientX - b.clientX); y = Math.abs(a.clientY - b.clientY); d = x + y; if (d > dist) { dist = d; points = {a: a, b: b}; } } } x = Math.abs(points.a.clientX + points.b.clientX) / 2; y = Math.abs(points.a.clientY + points.b.clientY) / 2; points.center = { x: x, y: y }; points.diameter = dist; return points; }, calcAngle: function(points) { var x = points.a.clientX - points.b.clientX; var y = points.a.clientY - points.b.clientY; return (360 + Math.atan2(y, x) * RAD_TO_DEG) % 360; } }; dispatcher.registerGesture('pinch', pinch); })(window.PolymerGestures); (function (global) { 'use strict'; var Token, TokenName, Syntax, Messages, source, index, length, delegate, lookahead, state; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8 }; 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'; Syntax = { ArrayExpression: 'ArrayExpression', BinaryExpression: 'BinaryExpression', CallExpression: 'CallExpression', ConditionalExpression: 'ConditionalExpression', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', Identifier: 'Identifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ThisExpression: 'ThisExpression', UnaryExpression: 'UnaryExpression' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared' }; // 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) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } // 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 } 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 } // 7.6.1.1 Keywords function isKeyword(id) { return (id === 'this') } // 7.4 Comments function skipWhitespace() { while (index < length && isWhiteSpace(source.charCodeAt(index))) { ++index; } } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; id = 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, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2; switch (code) { // Check for most common single-character punctuators. case 46: // . dot 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: // ? ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), 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 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), 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), range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; // Other 2-character punctuators: && || if (ch1 === ch2 && ('&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals 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'. if (number === '0') { // 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), range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, 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 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: str += ch; break; } } else { if (ch === '\r' && source[index] === '\n') { ++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, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advance() { var ch; skipWhitespace(); if (index >= length) { return { type: Token.EOF, range: [index, index] }; } 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) { return scanStringLiteral(); } 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(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lookahead = advance(); index = token.range[1]; return token; } function peek() { var pos; pos = index; lookahead = advance(); index = pos; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); error = new Error(msg); error.index = index; error.description = msg; throw error; } // Throw an exception because of the token. function throwUnexpected(token) { 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); } } // 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) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } function consumeSemicolon() { // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } skipWhitespace(); if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseExpression()); if (!match(']')) { expect(','); } } } expect(']'); return delegate.createArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token; skipWhitespace(); token = lex(); // 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) { return delegate.createLiteral(token); } return delegate.createIdentifier(token.value); } function parseObjectProperty() { var token, key; token = lookahead; skipWhitespace(); if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } key = parseObjectPropertyKey(); expect(':'); return delegate.createProperty('init', key, parseExpression()); } function parseObjectInitialiser() { var properties = []; expect('{'); while (!match('}')) { properties.push(parseObjectProperty()); if (!match('}')) { expect(','); } } expect('}'); return delegate.createObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var type, token, expr; if (match('(')) { return parseGroupExpression(); } type = lookahead.type; if (type === Token.Identifier) { expr = delegate.createIdentifier(lex().value); } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { expr = delegate.createLiteral(lex()); } else if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); expr = delegate.createThisExpression(); } } else if (type === Token.BooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = delegate.createLiteral(token); } else if (type === Token.NullLiteral) { token = lex(); token.value = null; expr = delegate.createLiteral(token); } else if (match('[')) { expr = parseArrayInitialiser(); } else if (match('{')) { expr = parseObjectInitialiser(); } if (expr) { return expr; } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token; token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return delegate.createIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseLeftHandSideExpression() { var expr, args, property; expr = parsePrimaryExpression(); while (true) { if (match('[')) { property = parseComputedMember(); expr = delegate.createMemberExpression('[', expr, property); } else if (match('.')) { property = parseNonComputedMember(); expr = delegate.createMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = delegate.createCallExpression(expr, args); } else { break; } } return expr; } // 11.3 Postfix Expressions var parsePostfixExpression = parseLeftHandSideExpression; // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { expr = parsePostfixExpression(); } else if (match('+') || match('-') || match('!')) { token = lex(); expr = parseUnaryExpression(); expr = delegate.createUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throwError({}, Messages.UnexpectedToken); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token) { 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 '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = 7; 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, stack, right, operator, left, i; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token); if (prec === 0) { return left; } token.prec = prec; lex(); right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead)) > 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); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); consequent = parseConditionalExpression(); expect(':'); alternate = parseConditionalExpression(); expr = delegate.createConditionalExpression(expr, consequent, alternate); } return expr; } // Simplification since we do not support AssignmentExpression. var parseExpression = parseConditionalExpression; // Polymer Syntax extensions // Filter :: // Identifier // Identifier "(" ")" // Identifier "(" FilterArguments ")" function parseFilter() { var identifier, args; identifier = lex(); if (identifier.type !== Token.Identifier) { throwUnexpected(identifier); } args = match('(') ? parseArguments() : []; return delegate.createFilter(identifier.value, args); } // Filters :: // "|" Filter // Filters "|" Filter function parseFilters() { while (match('|')) { lex(); parseFilter(); } } // TopLevel :: // LabelledExpressions // AsExpression // InExpression // FilterExpression // AsExpression :: // FilterExpression as Identifier // InExpression :: // Identifier, Identifier in FilterExpression // Identifier in FilterExpression // FilterExpression :: // Expression // Expression Filters function parseTopLevel() { skipWhitespace(); peek(); var expr = parseExpression(); if (expr) { if (lookahead.value === ',' || lookahead.value == 'in' && expr.type === Syntax.Identifier) { parseInExpression(expr); } else { parseFilters(); if (lookahead.value === 'as') { parseAsExpression(expr); } else { delegate.createTopLevel(expr); } } } if (lookahead.type !== Token.EOF) { throwUnexpected(lookahead); } } function parseAsExpression(expr) { lex(); // as var identifier = lex().value; delegate.createAsExpression(expr, identifier); } function parseInExpression(identifier) { var indexName; if (lookahead.value === ',') { lex(); if (lookahead.type !== Token.Identifier) throwUnexpected(lookahead); indexName = lex().value; } lex(); // in var expr = parseExpression(); parseFilters(); delegate.createInExpression(identifier.name, indexName, expr); } function parse(code, inDelegate) { delegate = inDelegate; source = code; index = 0; length = source.length; lookahead = null; state = { labelSet: {} }; return parseTopLevel(); } global.esprima = { parse: parse }; })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function (global) { 'use strict'; function prepareBinding(expressionText, name, node, filterRegistry) { var expression; try { expression = getExpression(expressionText); if (expression.scopeIdent && (node.nodeType !== Node.ELEMENT_NODE || node.tagName !== 'TEMPLATE' || (name !== 'bind' && name !== 'repeat'))) { throw Error('as and in can only be used within <template bind/repeat>'); } } catch (ex) { console.error('Invalid expression syntax: ' + expressionText, ex); return; } return function(model, node, oneTime) { var binding = expression.getBinding(model, filterRegistry, oneTime); if (expression.scopeIdent && binding) { node.polymerExpressionScopeIdent_ = expression.scopeIdent; if (expression.indexIdent) node.polymerExpressionIndexIdent_ = expression.indexIdent; } return binding; } } // TODO(rafaelw): Implement simple LRU. var expressionParseCache = Object.create(null); function getExpression(expressionText) { var expression = expressionParseCache[expressionText]; if (!expression) { var delegate = new ASTDelegate(); esprima.parse(expressionText, delegate); expression = new Expression(delegate); expressionParseCache[expressionText] = expression; } return expression; } function Literal(value) { this.value = value; this.valueFn_ = undefined; } Literal.prototype = { valueFn: function() { if (!this.valueFn_) { var value = this.value; this.valueFn_ = function() { return value; } } return this.valueFn_; } } function IdentPath(name) { this.name = name; this.path = Path.get(name); } IdentPath.prototype = { valueFn: function() { if (!this.valueFn_) { var name = this.name; var path = this.path; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.path.length == 1) model = findScope(model, this.path[0]); return this.path.setValueFrom(model, newValue); } }; function MemberExpression(object, property, accessor) { this.computed = accessor == '['; this.dynamicDeps = typeof object == 'function' || object.dynamicDeps || (this.computed && !(property instanceof Literal)); this.simplePath = !this.dynamicDeps && (property instanceof IdentPath || property instanceof Literal) && (object instanceof MemberExpression || object instanceof IdentPath); this.object = this.simplePath ? object : getFn(object); this.property = !this.computed || this.simplePath ? property : getFn(property); } MemberExpression.prototype = { get fullPath() { if (!this.fullPath_) { var parts = this.object instanceof MemberExpression ? this.object.fullPath.slice() : [this.object.name]; parts.push(this.property instanceof IdentPath ? this.property.name : this.property.value); this.fullPath_ = Path.get(parts); } return this.fullPath_; }, valueFn: function() { if (!this.valueFn_) { var object = this.object; if (this.simplePath) { var path = this.fullPath; this.valueFn_ = function(model, observer) { if (observer) observer.addPath(model, path); return path.getValueFrom(model); }; } else if (!this.computed) { var path = Path.get(this.property.name); this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); if (observer) observer.addPath(context, path); return path.getValueFrom(context); } } else { // Computed property. var property = this.property; this.valueFn_ = function(model, observer, filterRegistry) { var context = object(model, observer, filterRegistry); var propName = property(model, observer, filterRegistry); if (observer) observer.addPath(context, [propName]); return context ? context[propName] : undefined; }; } } return this.valueFn_; }, setValue: function(model, newValue) { if (this.simplePath) { this.fullPath.setValueFrom(model, newValue); return newValue; } var object = this.object(model); var propName = this.property instanceof IdentPath ? this.property.name : this.property(model); return object[propName] = newValue; } }; function Filter(name, args) { this.name = name; this.args = []; for (var i = 0; i < args.length; i++) { this.args[i] = getFn(args[i]); } } Filter.prototype = { transform: function(model, observer, filterRegistry, toModelDirection, initialArgs) { var fn = filterRegistry[this.name]; var context = model; if (fn) { context = undefined; } else { fn = context[this.name]; if (!fn) { console.error('Cannot find function or filter: ' + this.name); return; } } // If toModelDirection is falsey, then the "normal" (dom-bound) direction // is used. Otherwise, it looks for a 'toModel' property function on the // object. if (toModelDirection) { fn = fn.toModel; } else if (typeof fn.toDOM == 'function') { fn = fn.toDOM; } if (typeof fn != 'function') { console.error('Cannot find function or filter: ' + this.name); return; } var args = initialArgs || []; for (var i = 0; i < this.args.length; i++) { args.push(getFn(this.args[i])(model, observer, filterRegistry)); } return fn.apply(context, args); } }; function notImplemented() { throw Error('Not Implemented'); } var unaryOperators = { '+': function(v) { return +v; }, '-': function(v) { return -v; }, '!': function(v) { return !v; } }; var binaryOperators = { '+': function(l, r) { return l+r; }, '-': function(l, r) { return l-r; }, '*': function(l, r) { return l*r; }, '/': function(l, r) { return l/r; }, '%': function(l, r) { return l%r; }, '<': function(l, r) { return l<r; }, '>': function(l, r) { return l>r; }, '<=': function(l, r) { return l<=r; }, '>=': function(l, r) { return l>=r; }, '==': function(l, r) { return l==r; }, '!=': function(l, r) { return l!=r; }, '===': function(l, r) { return l===r; }, '!==': function(l, r) { return l!==r; }, '&&': function(l, r) { return l&&r; }, '||': function(l, r) { return l||r; }, }; function getFn(arg) { return typeof arg == 'function' ? arg : arg.valueFn(); } function ASTDelegate() { this.expression = null; this.filters = []; this.deps = {}; this.currentPath = undefined; this.scopeIdent = undefined; this.indexIdent = undefined; this.dynamicDeps = false; } ASTDelegate.prototype = { createUnaryExpression: function(op, argument) { if (!unaryOperators[op]) throw Error('Disallowed operator: ' + op); argument = getFn(argument); return function(model, observer, filterRegistry) { return unaryOperators[op](argument(model, observer, filterRegistry)); }; }, createBinaryExpression: function(op, left, right) { if (!binaryOperators[op]) throw Error('Disallowed operator: ' + op); left = getFn(left); right = getFn(right); switch (op) { case '||': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) || right(model, observer, filterRegistry); }; case '&&': this.dynamicDeps = true; return function(model, observer, filterRegistry) { return left(model, observer, filterRegistry) && right(model, observer, filterRegistry); }; } return function(model, observer, filterRegistry) { return binaryOperators[op](left(model, observer, filterRegistry), right(model, observer, filterRegistry)); }; }, createConditionalExpression: function(test, consequent, alternate) { test = getFn(test); consequent = getFn(consequent); alternate = getFn(alternate); this.dynamicDeps = true; return function(model, observer, filterRegistry) { return test(model, observer, filterRegistry) ? consequent(model, observer, filterRegistry) : alternate(model, observer, filterRegistry); } }, createIdentifier: function(name) { var ident = new IdentPath(name); ident.type = 'Identifier'; return ident; }, createMemberExpression: function(accessor, object, property) { var ex = new MemberExpression(object, property, accessor); if (ex.dynamicDeps) this.dynamicDeps = true; return ex; }, createCallExpression: function(expression, args) { if (!(expression instanceof IdentPath)) throw Error('Only identifier function invocations are allowed'); var filter = new Filter(expression.name, args); return function(model, observer, filterRegistry) { return filter.transform(model, observer, filterRegistry, false); }; }, createLiteral: function(token) { return new Literal(token.value); }, createArrayExpression: function(elements) { for (var i = 0; i < elements.length; i++) elements[i] = getFn(elements[i]); return function(model, observer, filterRegistry) { var arr = [] for (var i = 0; i < elements.length; i++) arr.push(elements[i](model, observer, filterRegistry)); return arr; } }, createProperty: function(kind, key, value) { return { key: key instanceof IdentPath ? key.name : key.value, value: value }; }, createObjectExpression: function(properties) { for (var i = 0; i < properties.length; i++) properties[i].value = getFn(properties[i].value); return function(model, observer, filterRegistry) { var obj = {}; for (var i = 0; i < properties.length; i++) obj[properties[i].key] = properties[i].value(model, observer, filterRegistry); return obj; } }, createFilter: function(name, args) { this.filters.push(new Filter(name, args)); }, createAsExpression: function(expression, scopeIdent) { this.expression = expression; this.scopeIdent = scopeIdent; }, createInExpression: function(scopeIdent, indexIdent, expression) { this.expression = expression; this.scopeIdent = scopeIdent; this.indexIdent = indexIdent; }, createTopLevel: function(expression) { this.expression = expression; }, createThisExpression: notImplemented } function ConstantObservable(value) { this.value_ = value; } ConstantObservable.prototype = { open: function() { return this.value_; }, discardChanges: function() { return this.value_; }, deliver: function() {}, close: function() {}, } function Expression(delegate) { this.scopeIdent = delegate.scopeIdent; this.indexIdent = delegate.indexIdent; if (!delegate.expression) throw Error('No expression found.'); this.expression = delegate.expression; getFn(this.expression); // forces enumeration of path dependencies this.filters = delegate.filters; this.dynamicDeps = delegate.dynamicDeps; } Expression.prototype = { getBinding: function(model, filterRegistry, oneTime) { if (oneTime) return this.getValue(model, undefined, filterRegistry); var observer = new CompoundObserver(); // captures deps. var firstValue = this.getValue(model, observer, filterRegistry); var firstTime = true; var self = this; function valueFn() { // deps cannot have changed on first value retrieval. if (firstTime) { firstTime = false; return firstValue; } if (self.dynamicDeps) observer.startReset(); var value = self.getValue(model, self.dynamicDeps ? observer : undefined, filterRegistry); if (self.dynamicDeps) observer.finishReset(); return value; } function setValueFn(newValue) { self.setValue(model, newValue, filterRegistry); return newValue; } return new ObserverTransform(observer, valueFn, setValueFn, true); }, getValue: function(model, observer, filterRegistry) { var value = getFn(this.expression)(model, observer, filterRegistry); for (var i = 0; i < this.filters.length; i++) { value = this.filters[i].transform(model, observer, filterRegistry, false, [value]); } return value; }, setValue: function(model, newValue, filterRegistry) { var count = this.filters ? this.filters.length : 0; while (count-- > 0) { newValue = this.filters[count].transform(model, undefined, filterRegistry, true, [newValue]); } if (this.expression.setValue) return this.expression.setValue(model, newValue); } } /** * Converts a style property name to a css property name. For example: * "WebkitUserSelect" to "-webkit-user-select" */ function convertStylePropertyName(name) { return String(name).replace(/[A-Z]/g, function(c) { return '-' + c.toLowerCase(); }); } var parentScopeName = '@' + Math.random().toString(36).slice(2); // Single ident paths must bind directly to the appropriate scope object. // I.e. Pushed values in two-bindings need to be assigned to the actual model // object. function findScope(model, prop) { while (model[parentScopeName] && !Object.prototype.hasOwnProperty.call(model, prop)) { model = model[parentScopeName]; } return model; } function isLiteralExpression(pathString) { switch (pathString) { case '': return false; case 'false': case 'null': case 'true': return true; } if (!isNaN(Number(pathString))) return true; return false; }; function PolymerExpressions() {} PolymerExpressions.prototype = { // "built-in" filters styleObject: function(value) { var parts = []; for (var key in value) { parts.push(convertStylePropertyName(key) + ': ' + value[key]); } return parts.join('; '); }, tokenList: function(value) { var tokens = []; for (var key in value) { if (value[key]) tokens.push(key); } return tokens.join(' '); }, // binding delegate API prepareInstancePositionChanged: function(template) { var indexIdent = template.polymerExpressionIndexIdent_; if (!indexIdent) return; return function(templateInstance, index) { templateInstance.model[indexIdent] = index; }; }, prepareBinding: function(pathString, name, node) { var path = Path.get(pathString); if (!isLiteralExpression(pathString) && path.valid) { if (path.length == 1) { return function(model, node, oneTime) { if (oneTime) return path.getValueFrom(model); var scope = findScope(model, path[0]); return new PathObserver(scope, path); }; } return; // bail out early if pathString is simple path. } return prepareBinding(pathString, name, node, this); }, prepareInstanceModel: function(template) { var scopeName = template.polymerExpressionScopeIdent_; if (!scopeName) return; var parentScope = template.templateInstance ? template.templateInstance.model : template.model; var indexName = template.polymerExpressionIndexIdent_; return function(model) { return createScopeObject(parentScope, model, scopeName, indexName); }; } }; var createScopeObject = ('__proto__' in {}) ? function(parentScope, model, scopeName, indexName) { var scope = {}; scope[scopeName] = model; scope[indexName] = undefined; scope[parentScopeName] = parentScope; scope.__proto__ = parentScope; return scope; } : function(parentScope, model, scopeName, indexName) { var scope = Object.create(parentScope); Object.defineProperty(scope, scopeName, { value: model, configurable: true, writable: true }); Object.defineProperty(scope, indexName, { value: undefined, configurable: true, writable: true }); Object.defineProperty(scope, parentScopeName, { value: parentScope, configurable: true, writable: true }); return scope; }; global.PolymerExpressions = PolymerExpressions; PolymerExpressions.getExpression = getExpression; })(this); Polymer = { version: '0.5.1' }; // TODO(sorvell): this ensures Polymer is an object and not a function // Platform is currently defining it as a function to allow for async loading // of polymer; once we refine the loading process this likely goes away. if (typeof window.Polymer === 'function') { Polymer = {}; } (function(scope) { function withDependencies(task, depends) { depends = depends || []; if (!depends.map) { depends = [depends]; } return task.apply(this, depends.map(marshal)); } function module(name, dependsOrFactory, moduleFactory) { var module; switch (arguments.length) { case 0: return; case 1: module = null; break; case 2: // dependsOrFactory is `factory` in this case module = dependsOrFactory.apply(this); break; default: // dependsOrFactory is `depends` in this case module = withDependencies(moduleFactory, dependsOrFactory); break; } modules[name] = module; }; function marshal(name) { return modules[name]; } var modules = {}; function using(depends, task) { HTMLImports.whenImportsReady(function() { withDependencies(task, depends); }); }; // exports scope.marshal = marshal; // `module` confuses commonjs detectors scope.modularize = module; scope.using = using; })(window); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ if (!window.WebComponents) { /* On supported platforms, platform.js is not needed. To retain compatibility with the polyfills, we stub out minimal functionality. */ if (!window.WebComponents) { WebComponents = { flush: function() {}, flags: {log: {}} }; Platform = WebComponents; CustomElements = { useNative: true, ready: true, takeRecords: function() {}, instanceof: function(obj, base) { return obj instanceof base; } }; HTMLImports = { useNative: true }; addEventListener('HTMLImportsLoaded', function() { document.dispatchEvent( new CustomEvent('WebComponentsReady', {bubbles: true}) ); }); // ShadowDOM ShadowDOMPolyfill = null; wrap = unwrap = function(n){ return n; }; } /* Create polyfill scope and feature detect native support. */ window.HTMLImports = window.HTMLImports || {flags:{}}; (function(scope) { /** Basic setup and simple module executer. We collect modules and then execute the code later, only if it's necessary for polyfilling. */ var IMPORT_LINK_TYPE = 'import'; var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement('link')); /** Support `currentScript` on all browsers as `document._currentScript.` NOTE: We cannot polyfill `document.currentScript` because it's not possible both to override and maintain the ability to capture the native value. Therefore we choose to expose `_currentScript` both when native imports and the polyfill are in use. */ // NOTE: ShadowDOMPolyfill intrusion. var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill); var wrap = function(node) { return hasShadowDOMPolyfill ? ShadowDOMPolyfill.wrapIfNeeded(node) : node; }; var rootDocument = wrap(document); var currentScriptDescriptor = { get: function() { var script = HTMLImports.currentScript || document.currentScript || // NOTE: only works when called in synchronously executing code. // readyState should check if `loading` but IE10 is // interactive when scripts run so we cheat. (document.readyState !== 'complete' ? document.scripts[document.scripts.length - 1] : null); return wrap(script); }, configurable: true }; Object.defineProperty(document, '_currentScript', currentScriptDescriptor); Object.defineProperty(rootDocument, '_currentScript', currentScriptDescriptor); /** Add support for the `HTMLImportsLoaded` event and the `HTMLImports.whenReady` method. This api is necessary because unlike the native implementation, script elements do not force imports to resolve. Instead, users should wrap code in either an `HTMLImportsLoaded` hander or after load time in an `HTMLImports.whenReady(callback)` call. NOTE: This module also supports these apis under the native implementation. Therefore, if this file is loaded, the same code can be used under both the polyfill and native implementation. */ var isIE = /Trident/.test(navigator.userAgent); // call a callback when all HTMLImports in the document at call time // (or at least document ready) have loaded. // 1. ensure the document is in a ready state (has dom), then // 2. watch for loading of imports and call callback when done function whenReady(callback, doc) { doc = doc || rootDocument; // if document is loading, wait and try again whenDocumentReady(function() { watchImportsLoad(callback, doc); }, doc); } // call the callback when the document is in a ready state (has dom) var requiredReadyState = isIE ? 'complete' : 'interactive'; var READY_EVENT = 'readystatechange'; function isDocumentReady(doc) { return (doc.readyState === 'complete' || doc.readyState === requiredReadyState); } // call <callback> when we ensure the document is in a ready state function whenDocumentReady(callback, doc) { if (!isDocumentReady(doc)) { var checkReady = function() { if (doc.readyState === 'complete' || doc.readyState === requiredReadyState) { doc.removeEventListener(READY_EVENT, checkReady); whenDocumentReady(callback, doc); } }; doc.addEventListener(READY_EVENT, checkReady); } else if (callback) { callback(); } } function markTargetLoaded(event) { event.target.__loaded = true; } // call <callback> when we ensure all imports have loaded function watchImportsLoad(callback, doc) { var imports = doc.querySelectorAll('link[rel=import]'); var loaded = 0, l = imports.length; function checkDone(d) { if ((loaded == l) && callback) { callback(); } } function loadedImport(e) { markTargetLoaded(e); loaded++; checkDone(); } if (l) { for (var i=0, imp; (i<l) && (imp=imports[i]); i++) { if (isImportLoaded(imp)) { loadedImport.call(imp, {target: imp}); } else { imp.addEventListener('load', loadedImport); imp.addEventListener('error', loadedImport); } } } else { checkDone(); } } // NOTE: test for native imports loading is based on explicitly watching // all imports (see below). // However, we cannot rely on this entirely without watching the entire document // for import links. For perf reasons, currently only head is watched. // Instead, we fallback to checking if the import property is available // and the document is not itself loading. function isImportLoaded(link) { return useNative ? link.__loaded || (link.import && link.import.readyState !== 'loading') : link.__importParsed; } // TODO(sorvell): Workaround for // https://www.w3.org/Bugs/Public/show_bug.cgi?id=25007, should be removed when // this bug is addressed. // (1) Install a mutation observer to see when HTMLImports have loaded // (2) if this script is run during document load it will watch any existing // imports for loading. // // NOTE: The workaround has restricted functionality: (1) it's only compatible // with imports that are added to document.head since the mutation observer // watches only head for perf reasons, (2) it requires this script // to run before any imports have completed loading. if (useNative) { new MutationObserver(function(mxns) { for (var i=0, l=mxns.length, m; (i < l) && (m=mxns[i]); i++) { if (m.addedNodes) { handleImports(m.addedNodes); } } }).observe(document.head, {childList: true}); function handleImports(nodes) { for (var i=0, l=nodes.length, n; (i<l) && (n=nodes[i]); i++) { if (isImport(n)) { handleImport(n); } } } function isImport(element) { return element.localName === 'link' && element.rel === 'import'; } function handleImport(element) { var loaded = element.import; if (loaded) { markTargetLoaded({target: element}); } else { element.addEventListener('load', markTargetLoaded); element.addEventListener('error', markTargetLoaded); } } // make sure to catch any imports that are in the process of loading // when this script is run. (function() { if (document.readyState === 'loading') { var imports = document.querySelectorAll('link[rel=import]'); for (var i=0, l=imports.length, imp; (i<l) && (imp=imports[i]); i++) { handleImport(imp); } } })(); } // Fire the 'HTMLImportsLoaded' event when imports in document at load time // have loaded. This event is required to simulate the script blocking // behavior of native imports. A main document script that needs to be sure // imports have loaded should wait for this event. whenReady(function() { HTMLImports.ready = true; HTMLImports.readyTime = new Date().getTime(); rootDocument.dispatchEvent( new CustomEvent('HTMLImportsLoaded', {bubbles: true}) ); }); // exports scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE; scope.useNative = useNative; scope.rootDocument = rootDocument; scope.whenReady = whenReady; scope.isIE = isIE; })(HTMLImports); (function(scope) { // TODO(sorvell): It's desireable to provide a default stylesheet // that's convenient for styling unresolved elements, but // it's cumbersome to have to include this manually in every page. // It would make sense to put inside some HTMLImport but // the HTMLImports polyfill does not allow loading of stylesheets // that block rendering. Therefore this injection is tolerated here. var style = document.createElement('style'); style.textContent = '' + 'body {' + 'transition: opacity ease-in 0.2s;' + ' } \n' + 'body[unresolved] {' + 'opacity: 0; display: block; overflow: hidden;' + ' } \n' ; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); })(Platform); /* Build only script. Ensures scripts needed for basic x-platform compatibility will be run when platform.js is not loaded. */ } (function(global) { 'use strict'; var testingExposeCycleCount = global.testingExposeCycleCount; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } // Firefox OS Apps do not allow eval. This feature detection is very hacky // but even if some other platform adds support for this function this code // will continue to work. if (typeof navigator != 'undefined' && navigator.getDeviceStorage) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); function isIndex(s) { return +s === s >>> 0 && s !== ''; } function toNumber(s) { return +s; } function isObject(obj) { return obj === Object(obj); } var numberIsNaN = global.Number.isNaN || function(value) { return typeof value === 'number' && global.isNaN(value); } function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var identStart = '[\$_a-zA-Z]'; var identPart = '[\$_a-zA-Z0-9]'; var identRegExp = new RegExp('^' + identStart + '+' + identPart + '*' + '$'); function getPathCharType(char) { if (char === undefined) return 'eof'; var code = char.charCodeAt(0); switch(code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return char; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if ((0x61 <= code && code <= 0x7A) || (0x41 <= code && code <= 0x5A)) return 'ident'; // 1-9 if (0x31 <= code && code <= 0x39) return 'number'; return 'else'; } var pathStateMachine = { 'beforePath': { 'ws': ['beforePath'], 'ident': ['inIdent', 'append'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'inPath': { 'ws': ['inPath'], '.': ['beforeIdent'], '[': ['beforeElement'], 'eof': ['afterPath'] }, 'beforeIdent': { 'ws': ['beforeIdent'], 'ident': ['inIdent', 'append'] }, 'inIdent': { 'ident': ['inIdent', 'append'], '0': ['inIdent', 'append'], 'number': ['inIdent', 'append'], 'ws': ['inPath', 'push'], '.': ['beforeIdent', 'push'], '[': ['beforeElement', 'push'], 'eof': ['afterPath', 'push'] }, 'beforeElement': { 'ws': ['beforeElement'], '0': ['afterZero', 'append'], 'number': ['inIndex', 'append'], "'": ['inSingleQuote', 'append', ''], '"': ['inDoubleQuote', 'append', ''] }, 'afterZero': { 'ws': ['afterElement', 'push'], ']': ['inPath', 'push'] }, 'inIndex': { '0': ['inIndex', 'append'], 'number': ['inIndex', 'append'], 'ws': ['afterElement'], ']': ['inPath', 'push'] }, 'inSingleQuote': { "'": ['afterElement'], 'eof': ['error'], 'else': ['inSingleQuote', 'append'] }, 'inDoubleQuote': { '"': ['afterElement'], 'eof': ['error'], 'else': ['inDoubleQuote', 'append'] }, 'afterElement': { 'ws': ['afterElement'], ']': ['inPath', 'push'] } } function noop() {} function parsePath(path) { var keys = []; var index = -1; var c, newChar, key, type, transition, action, typeMap, mode = 'beforePath'; var actions = { push: function() { if (key === undefined) return; keys.push(key); key = undefined; }, append: function() { if (key === undefined) key = newChar else key += newChar; } }; function maybeUnescapeQuote() { if (index >= path.length) return; var nextChar = path[index + 1]; if ((mode == 'inSingleQuote' && nextChar == "'") || (mode == 'inDoubleQuote' && nextChar == '"')) { index++; newChar = nextChar; actions.append(); return true; } } while (mode) { index++; c = path[index]; if (c == '\\' && maybeUnescapeQuote(mode)) continue; type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || 'error'; if (transition == 'error') return; // parse error; mode = transition[0]; action = actions[transition[1]] || noop; newChar = transition[2] === undefined ? c : transition[2]; action(); if (mode === 'afterPath') { return keys; } } return; // parse error } function isIdent(s) { return identRegExp.test(s); } var constructorIsPrivate = {}; function Path(parts, privateToken) { if (privateToken !== constructorIsPrivate) throw Error('Use Path.get to retrieve path objects'); for (var i = 0; i < parts.length; i++) { this.push(String(parts[i])); } if (hasEval && this.length) { this.getValueFrom = this.compiledGetValueFromFn(); } } // TODO(rafaelw): Make simple LRU cache var pathCache = {}; function getPath(pathString) { if (pathString instanceof Path) return pathString; if (pathString == null || pathString.length == 0) pathString = ''; if (typeof pathString != 'string') { if (isIndex(pathString.length)) { // Constructed with array-like (pre-parsed) keys return new Path(pathString, constructorIsPrivate); } pathString = String(pathString); } var path = pathCache[pathString]; if (path) return path; var parts = parsePath(pathString); if (!parts) return invalidPath; var path = new Path(parts, constructorIsPrivate); pathCache[pathString] = path; return path; } Path.get = getPath; function formatAccessor(key) { if (isIndex(key)) { return '[' + key + ']'; } else { return '["' + key.replace(/"/g, '\\"') + '"]'; } } Path.prototype = createObject({ __proto__: [], valid: true, toString: function() { var pathString = ''; for (var i = 0; i < this.length; i++) { var key = this[i]; if (isIdent(key)) { pathString += i ? '.' + key : key; } else { pathString += formatAccessor(key); } } return pathString; }, getValueFrom: function(obj, directObserver) { for (var i = 0; i < this.length; i++) { if (obj == null) return; obj = obj[this[i]]; } return obj; }, iterateObjects: function(obj, observe) { for (var i = 0; i < this.length; i++) { if (i) obj = obj[this[i - 1]]; if (!isObject(obj)) return; observe(obj, this[i]); } }, compiledGetValueFromFn: function() { var str = ''; var pathString = 'obj'; str += 'if (obj != null'; var i = 0; var key; for (; i < (this.length - 1); i++) { key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' &&\n ' + pathString + ' != null'; } str += ')\n'; var key = this[i]; pathString += isIdent(key) ? '.' + key : formatAccessor(key); str += ' return ' + pathString + ';\nelse\n return undefined;'; return new Function('obj', str); }, setValueFrom: function(obj, value) { if (!this.length) return false; for (var i = 0; i < this.length - 1; i++) { if (!isObject(obj)) return false; obj = obj[this[i]]; } if (!isObject(obj)) return false; obj[this[i]] = value; return true; } }); var invalidPath = new Path('', constructorIsPrivate); invalidPath.valid = false; invalidPath.getValueFrom = invalidPath.setValueFrom = function() {}; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function diffObjectFromOldObject(object, oldObject) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (newValue !== undefined && newValue === oldObject[prop]) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ return function(fn) { return Promise.resolve().then(fn); } })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var observedSetCache = []; function newObservedSet() { var observerCount = 0; var observers = []; var objects = []; var rootObj; var rootObjProps; function observe(obj, prop) { if (!obj) return; if (obj === rootObj) rootObjProps[prop] = true; if (objects.indexOf(obj) < 0) { objects.push(obj); Object.observe(obj, callback); } observe(Object.getPrototypeOf(obj), prop); } function allRootObjNonObservedProps(recs) { for (var i = 0; i < recs.length; i++) { var rec = recs[i]; if (rec.object !== rootObj || rootObjProps[rec.name] || rec.type === 'setPrototype') { return false; } } return true; } function callback(recs) { if (allRootObjNonObservedProps(recs)) return; var observer; for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.iterateObjects_(observe); } } for (var i = 0; i < observers.length; i++) { observer = observers[i]; if (observer.state_ == OPENED) { observer.check_(); } } } var record = { objects: objects, get rootObject() { return rootObj; }, set rootObject(value) { rootObj = value; rootObjProps = {}; }, open: function(obs, object) { observers.push(obs); observerCount++; obs.iterateObjects_(observe); }, close: function(obs) { observerCount--; if (observerCount > 0) { return; } for (var i = 0; i < objects.length; i++) { Object.unobserve(objects[i], callback); Observer.unobservedCount++; } observers.length = 0; objects.length = 0; rootObj = undefined; rootObjProps = undefined; observedSetCache.push(this); if (lastObservedSet === this) lastObservedSet = null; }, }; return record; } var lastObservedSet; function getObservedSet(observer, obj) { if (!lastObservedSet || lastObservedSet.rootObject !== obj) { lastObservedSet = observedSetCache.pop() || newObservedSet(); lastObservedSet.rootObject = obj; } lastObservedSet.open(observer, obj); return lastObservedSet; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var RESETTING = 3; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); function ArrayObserver(array) { if (!Array.isArray(array)) throw Error('Provided object is not an Array'); ObjectObserver.call(this, array); } ArrayObserver.prototype = createObject({ __proto__: ObjectObserver.prototype, arrayObserve: true, copyObject: function(arr) { return arr.slice(); }, check_: function(changeRecords) { var splices; if (hasObserve) { if (!changeRecords) return false; splices = projectArraySplices(this.value_, changeRecords); } else { splices = calcSplices(this.value_, 0, this.value_.length, this.oldObject_, 0, this.oldObject_.length); } if (!splices || !splices.length) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([splices]); return true; } }); ArrayObserver.applySplices = function(previous, current, splices) { splices.forEach(function(splice) { var spliceArgs = [splice.index, splice.removed.length]; var addIndex = splice.index; while (addIndex < splice.index + splice.addedCount) { spliceArgs.push(current[addIndex]); addIndex++; } Array.prototype.splice.apply(previous, spliceArgs); }); }; function PathObserver(object, path) { Observer.call(this); this.object_ = object; this.path_ = getPath(path); this.directObserver_ = undefined; } PathObserver.prototype = createObject({ __proto__: Observer.prototype, get path() { return this.path_; }, connect_: function() { if (hasObserve) this.directObserver_ = getObservedSet(this, this.object_); this.check_(undefined, true); }, disconnect_: function() { this.value_ = undefined; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, iterateObjects_: function(observe) { this.path_.iterateObjects(this.object_, observe); }, check_: function(changeRecords, skipChanges) { var oldValue = this.value_; this.value_ = this.path_.getValueFrom(this.object_); if (skipChanges || areSameValue(this.value_, oldValue)) return false; this.report_([this.value_, oldValue, this]); return true; }, setValue: function(newValue) { if (this.path_) this.path_.setValueFrom(this.object_, newValue); } }); function CompoundObserver(reportChangesOnOpen) { Observer.call(this); this.reportChangesOnOpen_ = reportChangesOnOpen; this.value_ = []; this.directObserver_ = undefined; this.observed_ = []; } var observerSentinel = {}; CompoundObserver.prototype = createObject({ __proto__: Observer.prototype, connect_: function() { if (hasObserve) { var object; var needsDirectObserver = false; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) { needsDirectObserver = true; break; } } if (needsDirectObserver) this.directObserver_ = getObservedSet(this, object); } this.check_(undefined, !this.reportChangesOnOpen_); }, disconnect_: function() { for (var i = 0; i < this.observed_.length; i += 2) { if (this.observed_[i] === observerSentinel) this.observed_[i + 1].close(); } this.observed_.length = 0; this.value_.length = 0; if (this.directObserver_) { this.directObserver_.close(this); this.directObserver_ = undefined; } }, addPath: function(object, path) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add paths once started.'); var path = getPath(path); this.observed_.push(object, path); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = path.getValueFrom(object); }, addObserver: function(observer) { if (this.state_ != UNOPENED && this.state_ != RESETTING) throw Error('Cannot add observers once started.'); this.observed_.push(observerSentinel, observer); if (!this.reportChangesOnOpen_) return; var index = this.observed_.length / 2 - 1; this.value_[index] = observer.open(this.deliver, this); }, startReset: function() { if (this.state_ != OPENED) throw Error('Can only reset while open'); this.state_ = RESETTING; this.disconnect_(); }, finishReset: function() { if (this.state_ != RESETTING) throw Error('Can only finishReset after startReset'); this.state_ = OPENED; this.connect_(); return this.value_; }, iterateObjects_: function(observe) { var object; for (var i = 0; i < this.observed_.length; i += 2) { object = this.observed_[i] if (object !== observerSentinel) this.observed_[i + 1].iterateObjects(object, observe) } }, check_: function(changeRecords, skipChanges) { var oldValues; for (var i = 0; i < this.observed_.length; i += 2) { var object = this.observed_[i]; var path = this.observed_[i+1]; var value; if (object === observerSentinel) { var observable = path; value = this.state_ === UNOPENED ? observable.open(this.deliver, this) : observable.discardChanges(); } else { value = path.getValueFrom(object); } if (skipChanges) { this.value_[i / 2] = value; continue; } if (areSameValue(value, this.value_[i / 2])) continue; oldValues = oldValues || []; oldValues[i / 2] = this.value_[i / 2]; this.value_[i / 2] = value; } if (!oldValues) return false; // TODO(rafaelw): Having observed_ as the third callback arg here is // pretty lame API. Fix. this.report_([this.value_, oldValues, this.observed_]); return true; } }); function identFn(value) { return value; } function ObserverTransform(observable, getValueFn, setValueFn, dontPassThroughSet) { this.callback_ = undefined; this.target_ = undefined; this.value_ = undefined; this.observable_ = observable; this.getValueFn_ = getValueFn || identFn; this.setValueFn_ = setValueFn || identFn; // TODO(rafaelw): This is a temporary hack. PolymerExpressions needs this // at the moment because of a bug in it's dependency tracking. this.dontPassThroughSet_ = dontPassThroughSet; } ObserverTransform.prototype = { open: function(callback, target) { this.callback_ = callback; this.target_ = target; this.value_ = this.getValueFn_(this.observable_.open(this.observedCallback_, this)); return this.value_; }, observedCallback_: function(value) { value = this.getValueFn_(value); if (areSameValue(value, this.value_)) return; var oldValue = this.value_; this.value_ = value; this.callback_.call(this.target_, this.value_, oldValue); }, discardChanges: function() { this.value_ = this.getValueFn_(this.observable_.discardChanges()); return this.value_; }, deliver: function() { return this.observable_.deliver(); }, setValue: function(value) { value = this.setValueFn_(value); if (!this.dontPassThroughSet_ && this.observable_.setValue) return this.observable_.setValue(value); }, close: function() { if (this.observable_) this.observable_.close(); this.callback_ = undefined; this.target_ = undefined; this.observable_ = undefined; this.value_ = undefined; this.getValueFn_ = undefined; this.setValueFn_ = undefined; } } var expectedRecordTypes = { add: true, update: true, delete: true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } function newSplice(index, removed, addedCount) { return { index: index, removed: removed, addedCount: addedCount }; } var EDIT_LEAVE = 0; var EDIT_UPDATE = 1; var EDIT_ADD = 2; var EDIT_DELETE = 3; function ArraySplice() {} ArraySplice.prototype = { // Note: This function is *based* on the computation of the Levenshtein // "edit" distance. The one change is that "updates" are treated as two // edits - not one. With Array splices, an update is really a delete // followed by an add. By retaining this, we optimize for "keeping" the // maximum array items in the original array. For example: // // 'xxxx123' -> '123yyyy' // // With 1-edit updates, the shortest path would be just to update all seven // characters. With 2-edit updates, we delete 4, leave 3, and add 4. This // leaves the substring '123' intact. calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { // "Deletion" columns var rowCount = oldEnd - oldStart + 1; var columnCount = currentEnd - currentStart + 1; var distances = new Array(rowCount); // "Addition" rows. Initialize null column. for (var i = 0; i < rowCount; i++) { distances[i] = new Array(columnCount); distances[i][0] = i; } // Initialize null row for (var j = 0; j < columnCount; j++) distances[0][j] = j; for (var i = 1; i < rowCount; i++) { for (var j = 1; j < columnCount; j++) { if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else { var north = distances[i - 1][j] + 1; var west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; }, // This starts at the final weight, and walks "backward" by finding // the minimum previous weight recursively until the origin of the weight // matrix. spliceOperationsFromEditDistances: function(distances) { var i = distances.length - 1; var j = distances[0].length - 1; var current = distances[i][j]; var edits = []; while (i > 0 || j > 0) { if (i == 0) { edits.push(EDIT_ADD); j--; continue; } if (j == 0) { edits.push(EDIT_DELETE); i--; continue; } var northWest = distances[i - 1][j - 1]; var west = distances[i - 1][j]; var north = distances[i][j - 1]; var min; if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest; if (min == northWest) { if (northWest == current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min == west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; }, /** * Splice Projection functions: * * A splice map is a representation of how a previous array of items * was transformed into a new array of items. Conceptually it is a list of * tuples of * * <index, removed, addedCount> * * which are kept in ascending index order of. The tuple represents that at * the |index|, |removed| sequence of items were removed, and counting forward * from |index|, |addedCount| items were added. */ /** * Lacking individual splice mutation information, the minimal set of * splices can be synthesized given the previous state and final state of an * array. The basic approach is to calculate the edit distance matrix and * choose the shortest path through it. * * Complexity: O(l * p) * l: The length of the current array * p: The length of the old array */ calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) { var prefixCount = 0; var suffixCount = 0; var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength); if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return []; if (currentStart == currentEnd) { var splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) splice.removed.push(old[oldStart++]); return [ splice ]; } else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ]; var ops = this.spliceOperationsFromEditDistances( this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); var splice = undefined; var splices = []; var index = currentStart; var oldIndex = oldStart; for (var i = 0; i < ops.length; i++) { switch(ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) splice = newSplice(index, [], 0); splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) splice = newSplice(index, [], 0); splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }, sharedPrefix: function(current, old, searchLength) { for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i; return searchLength; }, sharedSuffix: function(current, old, searchLength) { var index1 = current.length; var index2 = old.length; var count = 0; while (count < searchLength && this.equals(current[--index1], old[--index2])) count++; return count; }, calculateSplices: function(current, previous) { return this.calcSplices(current, 0, current.length, previous, 0, previous.length); }, equals: function(currentValue, previousValue) { return currentValue === previousValue; } }; var arraySplice = new ArraySplice(); function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); } function intersect(start1, end1, start2, end2) { // Disjoint if (end1 < start2 || end2 < start1) return -1; // Adjacent if (end1 == start2 || end2 == start1) return 0; // Non-zero intersect, span1 first if (start1 < start2) { if (end1 < end2) return end1 - start2; // Overlap else return end2 - start2; // Contained } else { // Non-zero intersect, span2 first if (end2 < end1) return end2 - start1; // Overlap else return end1 - start1; // Contained } } function mergeSplice(splices, index, removed, addedCount) { var splice = newSplice(index, removed, addedCount); var inserted = false; var insertionOffset = 0; for (var i = 0; i < splices.length; i++) { var current = splices[i]; current.index += insertionOffset; if (inserted) continue; var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); if (intersectCount >= 0) { // Merge the two splices splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; var deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { // merged splice is a noop. discard. inserted = true; } else { var removed = current.removed; if (splice.index < current.index) { // some prefix of splice.removed is prepended to current.removed. var prepend = splice.removed.slice(0, current.index - splice.index); Array.prototype.push.apply(prepend, removed); removed = prepend; } if (splice.index + splice.removed.length > current.index + current.addedCount) { // some suffix of splice.removed is appended to current.removed. var append = splice.removed.slice(current.index + current.addedCount - splice.index); Array.prototype.push.apply(removed, append); } splice.removed = removed; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { // Insert splice here. inserted = true; splices.splice(i, 0, splice); i++; var offset = splice.addedCount - splice.removed.length current.index += offset; insertionOffset += offset; } } if (!inserted) splices.push(splice); } function createInitialSplices(array, changeRecords) { var splices = []; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; switch(record.type) { case 'splice': mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); break; case 'add': case 'update': case 'delete': if (!isIndex(record.name)) continue; var index = toNumber(record.name); if (index < 0) continue; mergeSplice(splices, index, [record.oldValue], 1); break; default: console.error('Unexpected record type: ' + JSON.stringify(record)); break; } } return splices; } function projectArraySplices(array, changeRecords) { var splices = []; createInitialSplices(array, changeRecords).forEach(function(splice) { if (splice.addedCount == 1 && splice.removed.length == 1) { if (splice.removed[0] !== array[splice.index]) splices.push(splice); return }; splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); }); return splices; } // Export the observe-js object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, export as a global object. var expose = global; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { expose = exports = module.exports; } expose = exports; } expose.Observer = Observer; expose.Observer.runEOM_ = runEOM; expose.Observer.observerSentinel_ = observerSentinel; // for testing. expose.Observer.hasObjectObserve = hasObserve; expose.ArrayObserver = ArrayObserver; expose.ArrayObserver.calculateSplices = function(current, previous) { return arraySplice.calculateSplices(current, previous); }; expose.ArraySplice = ArraySplice; expose.ObjectObserver = ObjectObserver; expose.PathObserver = PathObserver; expose.CompoundObserver = CompoundObserver; expose.Path = Path; expose.ObserverTransform = ObserverTransform; })(typeof global !== 'undefined' && global && typeof module !== 'undefined' && module ? global : this || window); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; var filter = Array.prototype.filter.call.bind(Array.prototype.filter); function getTreeScope(node) { while (node.parentNode) { node = node.parentNode; } return typeof node.getElementById === 'function' ? node : null; } Node.prototype.bind = function(name, observable) { console.error('Unhandled binding to Node: ', this, name, observable); }; Node.prototype.bindFinished = function() {}; function updateBindings(node, name, binding) { var bindings = node.bindings_; if (!bindings) bindings = node.bindings_ = {}; if (bindings[name]) binding[name].close(); return bindings[name] = binding; } function returnBinding(node, name, binding) { return binding; } function sanitizeValue(value) { return value == null ? '' : value; } function updateText(node, value) { node.data = sanitizeValue(value); } function textBinding(node) { return function(value) { return updateText(node, value); }; } var maybeUpdateBindings = returnBinding; Object.defineProperty(Platform, 'enableBindingsReflection', { get: function() { return maybeUpdateBindings === updateBindings; }, set: function(enable) { maybeUpdateBindings = enable ? updateBindings : returnBinding; return enable; }, configurable: true }); Text.prototype.bind = function(name, value, oneTime) { if (name !== 'textContent') return Node.prototype.bind.call(this, name, value, oneTime); if (oneTime) return updateText(this, value); var observable = value; updateText(this, observable.open(textBinding(this))); return maybeUpdateBindings(this, name, observable); } function updateAttribute(el, name, conditional, value) { if (conditional) { if (value) el.setAttribute(name, ''); else el.removeAttribute(name); return; } el.setAttribute(name, sanitizeValue(value)); } function attributeBinding(el, name, conditional) { return function(value) { updateAttribute(el, name, conditional, value); }; } Element.prototype.bind = function(name, value, oneTime) { var conditional = name[name.length - 1] == '?'; if (conditional) { this.removeAttribute(name); name = name.slice(0, -1); } if (oneTime) return updateAttribute(this, name, conditional, value); var observable = value; updateAttribute(this, name, conditional, observable.open(attributeBinding(this, name, conditional))); return maybeUpdateBindings(this, name, observable); }; var checkboxEventType; (function() { // Attempt to feature-detect which event (change or click) is fired first // for checkboxes. var div = document.createElement('div'); var checkbox = div.appendChild(document.createElement('input')); checkbox.setAttribute('type', 'checkbox'); var first; var count = 0; checkbox.addEventListener('click', function(e) { count++; first = first || 'click'; }); checkbox.addEventListener('change', function() { count++; first = first || 'change'; }); var event = document.createEvent('MouseEvent'); event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); checkbox.dispatchEvent(event); // WebKit/Blink don't fire the change event if the element is outside the // document, so assume 'change' for that case. checkboxEventType = count == 1 ? 'change' : first; })(); function getEventForInputType(element) { switch (element.type) { case 'checkbox': return checkboxEventType; case 'radio': case 'select-multiple': case 'select-one': return 'change'; case 'range': if (/Trident|MSIE/.test(navigator.userAgent)) return 'change'; default: return 'input'; } } function updateInput(input, property, value, santizeFn) { input[property] = (santizeFn || sanitizeValue)(value); } function inputBinding(input, property, santizeFn) { return function(value) { return updateInput(input, property, value, santizeFn); } } function noop() {} function bindInputEvent(input, property, observable, postEventFn) { var eventType = getEventForInputType(input); function eventHandler() { observable.setValue(input[property]); observable.discardChanges(); (postEventFn || noop)(input); Platform.performMicrotaskCheckpoint(); } input.addEventListener(eventType, eventHandler); return { close: function() { input.removeEventListener(eventType, eventHandler); observable.close(); }, observable_: observable } } function booleanSanitize(value) { return Boolean(value); } // |element| is assumed to be an HTMLInputElement with |type| == 'radio'. // Returns an array containing all radio buttons other than |element| that // have the same |name|, either in the form that |element| belongs to or, // if no form, in the document tree to which |element| belongs. // // This implementation is based upon the HTML spec definition of a // "radio button group": // http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#radio-button-group // function getAssociatedRadioButtons(element) { if (element.form) { return filter(element.form.elements, function(el) { return el != element && el.tagName == 'INPUT' && el.type == 'radio' && el.name == element.name; }); } else { var treeScope = getTreeScope(element); if (!treeScope) return []; var radios = treeScope.querySelectorAll( 'input[type="radio"][name="' + element.name + '"]'); return filter(radios, function(el) { return el != element && !el.form; }); } } function checkedPostEvent(input) { // Only the radio button that is getting checked gets an event. We // therefore find all the associated radio buttons and update their // check binding manually. if (input.tagName === 'INPUT' && input.type === 'radio') { getAssociatedRadioButtons(input).forEach(function(radio) { var checkedBinding = radio.bindings_.checked; if (checkedBinding) { // Set the value directly to avoid an infinite call stack. checkedBinding.observable_.setValue(false); } }); } } HTMLInputElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value' && name !== 'checked') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); var sanitizeFn = name == 'checked' ? booleanSanitize : sanitizeValue; var postEventFn = name == 'checked' ? checkedPostEvent : noop; if (oneTime) return updateInput(this, name, value, sanitizeFn); var observable = value; var binding = bindInputEvent(this, name, observable, postEventFn); updateInput(this, name, observable.open(inputBinding(this, name, sanitizeFn)), sanitizeFn); // Checkboxes may need to update bindings of other checkboxes. return updateBindings(this, name, binding); } HTMLTextAreaElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateInput(this, 'value', value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateInput(this, 'value', observable.open(inputBinding(this, 'value', sanitizeValue))); return maybeUpdateBindings(this, name, binding); } function updateOption(option, value) { var parentNode = option.parentNode;; var select; var selectBinding; var oldValue; if (parentNode instanceof HTMLSelectElement && parentNode.bindings_ && parentNode.bindings_.value) { select = parentNode; selectBinding = select.bindings_.value; oldValue = select.value; } option.value = sanitizeValue(value); if (select && select.value != oldValue) { selectBinding.observable_.setValue(select.value); selectBinding.observable_.discardChanges(); Platform.performMicrotaskCheckpoint(); } } function optionBinding(option) { return function(value) { updateOption(option, value); } } HTMLOptionElement.prototype.bind = function(name, value, oneTime) { if (name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute('value'); if (oneTime) return updateOption(this, value); var observable = value; var binding = bindInputEvent(this, 'value', observable); updateOption(this, observable.open(optionBinding(this))); return maybeUpdateBindings(this, name, binding); } HTMLSelectElement.prototype.bind = function(name, value, oneTime) { if (name === 'selectedindex') name = 'selectedIndex'; if (name !== 'selectedIndex' && name !== 'value') return HTMLElement.prototype.bind.call(this, name, value, oneTime); this.removeAttribute(name); if (oneTime) return updateInput(this, name, value); var observable = value; var binding = bindInputEvent(this, name, observable); updateInput(this, name, observable.open(inputBinding(this, name))); // Option update events may need to access select bindings. return updateBindings(this, name, binding); } })(this); // Copyright (c) 2014 The Polymer Project Authors. All rights reserved. // This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt // The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt // The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt // Code distributed by Google as part of the polymer project is also // subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt (function(global) { 'use strict'; function assert(v) { if (!v) throw new Error('Assertion failed'); } var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach); function getFragmentRoot(node) { var p; while (p = node.parentNode) { node = p; } return node; } function searchRefId(node, id) { if (!id) return; var ref; var selector = '#' + id; while (!ref) { node = getFragmentRoot(node); if (node.protoContent_) ref = node.protoContent_.querySelector(selector); else if (node.getElementById) ref = node.getElementById(id); if (ref || !node.templateCreator_) break node = node.templateCreator_; } return ref; } function getInstanceRoot(node) { while (node.parentNode) { node = node.parentNode; } return node.templateCreator_ ? node : null; } var Map; if (global.Map && typeof global.Map.prototype.forEach === 'function') { Map = global.Map; } else { Map = function() { this.keys = []; this.values = []; }; Map.prototype = { set: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) { this.keys.push(key); this.values.push(value); } else { this.values[index] = value; } }, get: function(key) { var index = this.keys.indexOf(key); if (index < 0) return; return this.values[index]; }, delete: function(key, value) { var index = this.keys.indexOf(key); if (index < 0) return false; this.keys.splice(index, 1); this.values.splice(index, 1); return true; }, forEach: function(f, opt_this) { for (var i = 0; i < this.keys.length; i++) f.call(opt_this || this, this.values[i], this.keys[i], this); } }; } // JScript does not have __proto__. We wrap all object literals with // createObject which uses Object.create, Object.defineProperty and // Object.getOwnPropertyDescriptor to create a new object that does the exact // same thing. The main downside to this solution is that we have to extract // all those property descriptors for IE. var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; // IE does not support have Document.prototype.contains. if (typeof document.contains != 'function') { Document.prototype.contains = function(node) { if (node === this || node.parentNode === this) return true; return this.documentElement.contains(node); } } var BIND = 'bind'; var REPEAT = 'repeat'; var IF = 'if'; var templateAttributeDirectives = { 'template': true, 'repeat': true, 'bind': true, 'ref': true }; var semanticTemplateElements = { 'THEAD': true, 'TBODY': true, 'TFOOT': true, 'TH': true, 'TR': true, 'TD': true, 'COLGROUP': true, 'COL': true, 'CAPTION': true, 'OPTION': true, 'OPTGROUP': true }; var hasTemplateElement = typeof HTMLTemplateElement !== 'undefined'; if (hasTemplateElement) { // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. (function() { var t = document.createElement('template'); var d = t.content.ownerDocument; var html = d.appendChild(d.createElement('html')); var head = html.appendChild(d.createElement('head')); var base = d.createElement('base'); base.href = document.baseURI; head.appendChild(base); })(); } var allTemplatesSelectors = 'template, ' + Object.keys(semanticTemplateElements).map(function(tagName) { return tagName.toLowerCase() + '[template]'; }).join(', '); function isSVGTemplate(el) { return el.tagName == 'template' && el.namespaceURI == 'http://www.w3.org/2000/svg'; } function isHTMLTemplate(el) { return el.tagName == 'TEMPLATE' && el.namespaceURI == 'http://www.w3.org/1999/xhtml'; } function isAttributeTemplate(el) { return Boolean(semanticTemplateElements[el.tagName] && el.hasAttribute('template')); } function isTemplate(el) { if (el.isTemplate_ === undefined) el.isTemplate_ = el.tagName == 'TEMPLATE' || isAttributeTemplate(el); return el.isTemplate_; } // FIXME: Observe templates being added/removed from documents // FIXME: Expose imperative API to decorate and observe templates in // "disconnected tress" (e.g. ShadowRoot) document.addEventListener('DOMContentLoaded', function(e) { bootstrapTemplatesRecursivelyFrom(document); // FIXME: Is this needed? Seems like it shouldn't be. Platform.performMicrotaskCheckpoint(); }, false); function forAllTemplatesFrom(node, fn) { var subTemplates = node.querySelectorAll(allTemplatesSelectors); if (isTemplate(node)) fn(node) forEach(subTemplates, fn); } function bootstrapTemplatesRecursivelyFrom(node) { function bootstrap(template) { if (!HTMLTemplateElement.decorate(template)) bootstrapTemplatesRecursivelyFrom(template.content); } forAllTemplatesFrom(node, bootstrap); } if (!hasTemplateElement) { /** * This represents a <template> element. * @constructor * @extends {HTMLElement} */ global.HTMLTemplateElement = function() { throw TypeError('Illegal constructor'); }; } var hasProto = '__proto__' in {}; function mixin(to, from) { Object.getOwnPropertyNames(from).forEach(function(name) { Object.defineProperty(to, name, Object.getOwnPropertyDescriptor(from, name)); }); } // http://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html#dfn-template-contents-owner function getOrCreateTemplateContentsOwner(template) { var doc = template.ownerDocument if (!doc.defaultView) return doc; var d = doc.templateContentsOwner_; if (!d) { // TODO(arv): This should either be a Document or HTMLDocument depending // on doc. d = doc.implementation.createHTMLDocument(''); while (d.lastChild) { d.removeChild(d.lastChild); } doc.templateContentsOwner_ = d; } return d; } function getTemplateStagingDocument(template) { if (!template.stagingDocument_) { var owner = template.ownerDocument; if (!owner.stagingDocument_) { owner.stagingDocument_ = owner.implementation.createHTMLDocument(''); owner.stagingDocument_.isStagingDocument = true; // TODO(rafaelw): Remove when fix for // https://codereview.chromium.org/164803002/ // makes it to Chrome release. var base = owner.stagingDocument_.createElement('base'); base.href = document.baseURI; owner.stagingDocument_.head.appendChild(base); owner.stagingDocument_.stagingDocument_ = owner.stagingDocument_; } template.stagingDocument_ = owner.stagingDocument_; } return template.stagingDocument_; } // For non-template browsers, the parser will disallow <template> in certain // locations, so we allow "attribute templates" which combine the template // element with the top-level container node of the content, e.g. // // <tr template repeat="{{ foo }}"" class="bar"><td>Bar</td></tr> // // becomes // // <template repeat="{{ foo }}"> // + #document-fragment // + <tr class="bar"> // + <td>Bar</td> // function extractTemplateFromAttributeTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; if (templateAttributeDirectives[attrib.name]) { if (attrib.name !== 'template') template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } } return template; } function extractTemplateFromSVGTemplate(el) { var template = el.ownerDocument.createElement('template'); el.parentNode.insertBefore(template, el); var attribs = el.attributes; var count = attribs.length; while (count-- > 0) { var attrib = attribs[count]; template.setAttribute(attrib.name, attrib.value); el.removeAttribute(attrib.name); } el.parentNode.removeChild(el); return template; } function liftNonNativeTemplateChildrenIntoContent(template, el, useRoot) { var content = template.content; if (useRoot) { content.appendChild(el); return; } var child; while (child = el.firstChild) { content.appendChild(child); } } var templateObserver; if (typeof MutationObserver == 'function') { templateObserver = new MutationObserver(function(records) { for (var i = 0; i < records.length; i++) { records[i].target.refChanged_(); } }); } /** * Ensures proper API and content model for template elements. * @param {HTMLTemplateElement} opt_instanceRef The template element which * |el| template element will return as the value of its ref(), and whose * content will be used as source when createInstance() is invoked. */ HTMLTemplateElement.decorate = function(el, opt_instanceRef) { if (el.templateIsDecorated_) return false; var templateElement = el; templateElement.templateIsDecorated_ = true; var isNativeHTMLTemplate = isHTMLTemplate(templateElement) && hasTemplateElement; var bootstrapContents = isNativeHTMLTemplate; var liftContents = !isNativeHTMLTemplate; var liftRoot = false; if (!isNativeHTMLTemplate) { if (isAttributeTemplate(templateElement)) { assert(!opt_instanceRef); templateElement = extractTemplateFromAttributeTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; liftRoot = true; } else if (isSVGTemplate(templateElement)) { templateElement = extractTemplateFromSVGTemplate(el); templateElement.templateIsDecorated_ = true; isNativeHTMLTemplate = hasTemplateElement; } } if (!isNativeHTMLTemplate) { fixTemplateElementPrototype(templateElement); var doc = getOrCreateTemplateContentsOwner(templateElement); templateElement.content_ = doc.createDocumentFragment(); } if (opt_instanceRef) { // template is contained within an instance, its direct content must be // empty templateElement.instanceRef_ = opt_instanceRef; } else if (liftContents) { liftNonNativeTemplateChildrenIntoContent(templateElement, el, liftRoot); } else if (bootstrapContents) { bootstrapTemplatesRecursivelyFrom(templateElement.content); } return true; }; // TODO(rafaelw): This used to decorate recursively all templates from a given // node. This happens by default on 'DOMContentLoaded', but may be needed // in subtrees not descendent from document (e.g. ShadowRoot). // Review whether this is the right public API. HTMLTemplateElement.bootstrap = bootstrapTemplatesRecursivelyFrom; var htmlElement = global.HTMLUnknownElement || HTMLElement; var contentDescriptor = { get: function() { return this.content_; }, enumerable: true, configurable: true }; if (!hasTemplateElement) { // Gecko is more picky with the prototype than WebKit. Make sure to use the // same prototype as created in the constructor. HTMLTemplateElement.prototype = Object.create(htmlElement.prototype); Object.defineProperty(HTMLTemplateElement.prototype, 'content', contentDescriptor); } function fixTemplateElementPrototype(el) { if (hasProto) el.__proto__ = HTMLTemplateElement.prototype; else mixin(el, HTMLTemplateElement.prototype); } function ensureSetModelScheduled(template) { if (!template.setModelFn_) { template.setModelFn_ = function() { template.setModelFnScheduled_ = false; var map = getBindings(template, template.delegate_ && template.delegate_.prepareBinding); processBindings(template, map, template.model_); }; } if (!template.setModelFnScheduled_) { template.setModelFnScheduled_ = true; Observer.runEOM_(template.setModelFn_); } } mixin(HTMLTemplateElement.prototype, { bind: function(name, value, oneTime) { if (name != 'ref') return Element.prototype.bind.call(this, name, value, oneTime); var self = this; var ref = oneTime ? value : value.open(function(ref) { self.setAttribute('ref', ref); self.refChanged_(); }); this.setAttribute('ref', ref); this.refChanged_(); if (oneTime) return; if (!this.bindings_) { this.bindings_ = { ref: value }; } else { this.bindings_.ref = value; } return value; }, processBindingDirectives_: function(directives) { if (this.iterator_) this.iterator_.closeDeps(); if (!directives.if && !directives.bind && !directives.repeat) { if (this.iterator_) { this.iterator_.close(); this.iterator_ = undefined; } return; } if (!this.iterator_) { this.iterator_ = new TemplateIterator(this); } this.iterator_.updateDependencies(directives, this.model_); if (templateObserver) { templateObserver.observe(this, { attributes: true, attributeFilter: ['ref'] }); } return this.iterator_; }, createInstance: function(model, bindingDelegate, delegate_) { if (bindingDelegate) delegate_ = this.newDelegate_(bindingDelegate); else if (!delegate_) delegate_ = this.delegate_; if (!this.refContent_) this.refContent_ = this.ref_.content; var content = this.refContent_; if (content.firstChild === null) return emptyInstance; var map = getInstanceBindingMap(content, delegate_); var stagingDocument = getTemplateStagingDocument(this); var instance = stagingDocument.createDocumentFragment(); instance.templateCreator_ = this; instance.protoContent_ = content; instance.bindings_ = []; instance.terminator_ = null; var instanceRecord = instance.templateInstance_ = { firstNode: null, lastNode: null, model: model }; var i = 0; var collectTerminator = false; for (var child = content.firstChild; child; child = child.nextSibling) { // The terminator of the instance is the clone of the last child of the // content. If the last child is an active template, it may produce // instances as a result of production, so simply collecting the last // child of the instance after it has finished producing may be wrong. if (child.nextSibling === null) collectTerminator = true; var clone = cloneAndBindInstance(child, instance, stagingDocument, map.children[i++], model, delegate_, instance.bindings_); clone.templateInstance_ = instanceRecord; if (collectTerminator) instance.terminator_ = clone; } instanceRecord.firstNode = instance.firstChild; instanceRecord.lastNode = instance.lastChild; instance.templateCreator_ = undefined; instance.protoContent_ = undefined; return instance; }, get model() { return this.model_; }, set model(model) { this.model_ = model; ensureSetModelScheduled(this); }, get bindingDelegate() { return this.delegate_ && this.delegate_.raw; }, refChanged_: function() { if (!this.iterator_ || this.refContent_ === this.ref_.content) return; this.refContent_ = undefined; this.iterator_.valueChanged(); this.iterator_.updateIteratedValue(this.iterator_.getUpdatedValue()); }, clear: function() { this.model_ = undefined; this.delegate_ = undefined; if (this.bindings_ && this.bindings_.ref) this.bindings_.ref.close() this.refContent_ = undefined; if (!this.iterator_) return; this.iterator_.valueChanged(); this.iterator_.close() this.iterator_ = undefined; }, setDelegate_: function(delegate) { this.delegate_ = delegate; this.bindingMap_ = undefined; if (this.iterator_) { this.iterator_.instancePositionChangedFn_ = undefined; this.iterator_.instanceModelFn_ = undefined; } }, newDelegate_: function(bindingDelegate) { if (!bindingDelegate) return; function delegateFn(name) { var fn = bindingDelegate && bindingDelegate[name]; if (typeof fn != 'function') return; return function() { return fn.apply(bindingDelegate, arguments); }; } return { bindingMaps: {}, raw: bindingDelegate, prepareBinding: delegateFn('prepareBinding'), prepareInstanceModel: delegateFn('prepareInstanceModel'), prepareInstancePositionChanged: delegateFn('prepareInstancePositionChanged') }; }, set bindingDelegate(bindingDelegate) { if (this.delegate_) { throw Error('Template must be cleared before a new bindingDelegate ' + 'can be assigned'); } this.setDelegate_(this.newDelegate_(bindingDelegate)); }, get ref_() { var ref = searchRefId(this, this.getAttribute('ref')); if (!ref) ref = this.instanceRef_; if (!ref) return this; var nextRef = ref.ref_; return nextRef ? nextRef : ref; } }); // Returns // a) undefined if there are no mustaches. // b) [TEXT, (ONE_TIME?, PATH, DELEGATE_FN, TEXT)+] if there is at least one mustache. function parseMustaches(s, name, node, prepareBindingFn) { if (!s || !s.length) return; var tokens; var length = s.length; var startIndex = 0, lastIndex = 0, endIndex = 0; var onlyOneTime = true; while (lastIndex < length) { var startIndex = s.indexOf('{{', lastIndex); var oneTimeStart = s.indexOf('[[', lastIndex); var oneTime = false; var terminator = '}}'; if (oneTimeStart >= 0 && (startIndex < 0 || oneTimeStart < startIndex)) { startIndex = oneTimeStart; oneTime = true; terminator = ']]'; } endIndex = startIndex < 0 ? -1 : s.indexOf(terminator, startIndex + 2); if (endIndex < 0) { if (!tokens) return; tokens.push(s.slice(lastIndex)); // TEXT break; } tokens = tokens || []; tokens.push(s.slice(lastIndex, startIndex)); // TEXT var pathString = s.slice(startIndex + 2, endIndex).trim(); tokens.push(oneTime); // ONE_TIME? onlyOneTime = onlyOneTime && oneTime; var delegateFn = prepareBindingFn && prepareBindingFn(pathString, name, node); // Don't try to parse the expression if there's a prepareBinding function if (delegateFn == null) { tokens.push(Path.get(pathString)); // PATH } else { tokens.push(null); } tokens.push(delegateFn); // DELEGATE_FN lastIndex = endIndex + 2; } if (lastIndex === length) tokens.push(''); // TEXT tokens.hasOnePath = tokens.length === 5; tokens.isSimplePath = tokens.hasOnePath && tokens[0] == '' && tokens[4] == ''; tokens.onlyOneTime = onlyOneTime; tokens.combinator = function(values) { var newValue = tokens[0]; for (var i = 1; i < tokens.length; i += 4) { var value = tokens.hasOnePath ? values : values[(i - 1) / 4]; if (value !== undefined) newValue += value; newValue += tokens[i + 3]; } return newValue; } return tokens; }; function processOneTimeBinding(name, tokens, node, model) { if (tokens.hasOnePath) { var delegateFn = tokens[3]; var value = delegateFn ? delegateFn(model, node, true) : tokens[2].getValueFrom(model); return tokens.isSimplePath ? value : tokens.combinator(value); } var values = []; for (var i = 1; i < tokens.length; i += 4) { var delegateFn = tokens[i + 2]; values[(i - 1) / 4] = delegateFn ? delegateFn(model, node) : tokens[i + 1].getValueFrom(model); } return tokens.combinator(values); } function processSinglePathBinding(name, tokens, node, model) { var delegateFn = tokens[3]; var observer = delegateFn ? delegateFn(model, node, false) : new PathObserver(model, tokens[2]); return tokens.isSimplePath ? observer : new ObserverTransform(observer, tokens.combinator); } function processBinding(name, tokens, node, model) { if (tokens.onlyOneTime) return processOneTimeBinding(name, tokens, node, model); if (tokens.hasOnePath) return processSinglePathBinding(name, tokens, node, model); var observer = new CompoundObserver(); for (var i = 1; i < tokens.length; i += 4) { var oneTime = tokens[i]; var delegateFn = tokens[i + 2]; if (delegateFn) { var value = delegateFn(model, node, oneTime); if (oneTime) observer.addPath(value) else observer.addObserver(value); continue; } var path = tokens[i + 1]; if (oneTime) observer.addPath(path.getValueFrom(model)) else observer.addPath(model, path); } return new ObserverTransform(observer, tokens.combinator); } function processBindings(node, bindings, model, instanceBindings) { for (var i = 0; i < bindings.length; i += 2) { var name = bindings[i] var tokens = bindings[i + 1]; var value = processBinding(name, tokens, node, model); var binding = node.bind(name, value, tokens.onlyOneTime); if (binding && instanceBindings) instanceBindings.push(binding); } node.bindFinished(); if (!bindings.isTemplate) return; node.model_ = model; var iter = node.processBindingDirectives_(bindings); if (instanceBindings && iter) instanceBindings.push(iter); } function parseWithDefault(el, name, prepareBindingFn) { var v = el.getAttribute(name); return parseMustaches(v == '' ? '{{}}' : v, name, el, prepareBindingFn); } function parseAttributeBindings(element, prepareBindingFn) { assert(element); var bindings = []; var ifFound = false; var bindFound = false; for (var i = 0; i < element.attributes.length; i++) { var attr = element.attributes[i]; var name = attr.name; var value = attr.value; // Allow bindings expressed in attributes to be prefixed with underbars. // We do this to allow correct semantics for browsers that don't implement // <template> where certain attributes might trigger side-effects -- and // for IE which sanitizes certain attributes, disallowing mustache // replacements in their text. while (name[0] === '_') { name = name.substring(1); } if (isTemplate(element) && (name === IF || name === BIND || name === REPEAT)) { continue; } var tokens = parseMustaches(value, name, element, prepareBindingFn); if (!tokens) continue; bindings.push(name, tokens); } if (isTemplate(element)) { bindings.isTemplate = true; bindings.if = parseWithDefault(element, IF, prepareBindingFn); bindings.bind = parseWithDefault(element, BIND, prepareBindingFn); bindings.repeat = parseWithDefault(element, REPEAT, prepareBindingFn); if (bindings.if && !bindings.bind && !bindings.repeat) bindings.bind = parseMustaches('{{}}', BIND, element, prepareBindingFn); } return bindings; } function getBindings(node, prepareBindingFn) { if (node.nodeType === Node.ELEMENT_NODE) return parseAttributeBindings(node, prepareBindingFn); if (node.nodeType === Node.TEXT_NODE) { var tokens = parseMustaches(node.data, 'textContent', node, prepareBindingFn); if (tokens) return ['textContent', tokens]; } return []; } function cloneAndBindInstance(node, parent, stagingDocument, bindings, model, delegate, instanceBindings, instanceRecord) { var clone = parent.appendChild(stagingDocument.importNode(node, false)); var i = 0; for (var child = node.firstChild; child; child = child.nextSibling) { cloneAndBindInstance(child, clone, stagingDocument, bindings.children[i++], model, delegate, instanceBindings); } if (bindings.isTemplate) { HTMLTemplateElement.decorate(clone, node); if (delegate) clone.setDelegate_(delegate); } processBindings(clone, bindings, model, instanceBindings); return clone; } function createInstanceBindingMap(node, prepareBindingFn) { var map = getBindings(node, prepareBindingFn); map.children = {}; var index = 0; for (var child = node.firstChild; child; child = child.nextSibling) { map.children[index++] = createInstanceBindingMap(child, prepareBindingFn); } return map; } var contentUidCounter = 1; // TODO(rafaelw): Setup a MutationObserver on content which clears the id // so that bindingMaps regenerate when the template.content changes. function getContentUid(content) { var id = content.id_; if (!id) id = content.id_ = contentUidCounter++; return id; } // Each delegate is associated with a set of bindingMaps, one for each // content which may be used by a template. The intent is that each binding // delegate gets the opportunity to prepare the instance (via the prepare* // delegate calls) once across all uses. // TODO(rafaelw): Separate out the parse map from the binding map. In the // current implementation, if two delegates need a binding map for the same // content, the second will have to reparse. function getInstanceBindingMap(content, delegate_) { var contentId = getContentUid(content); if (delegate_) { var map = delegate_.bindingMaps[contentId]; if (!map) { map = delegate_.bindingMaps[contentId] = createInstanceBindingMap(content, delegate_.prepareBinding) || []; } return map; } var map = content.bindingMap_; if (!map) { map = content.bindingMap_ = createInstanceBindingMap(content, undefined) || []; } return map; } Object.defineProperty(Node.prototype, 'templateInstance', { get: function() { var instance = this.templateInstance_; return instance ? instance : (this.parentNode ? this.parentNode.templateInstance : undefined); } }); var emptyInstance = document.createDocumentFragment(); emptyInstance.bindings_ = []; emptyInstance.terminator_ = null; function TemplateIterator(templateElement) { this.closed = false; this.templateElement_ = templateElement; this.instances = []; this.deps = undefined; this.iteratedValue = []; this.presentValue = undefined; this.arrayObserver = undefined; } TemplateIterator.prototype = { closeDeps: function() { var deps = this.deps; if (deps) { if (deps.ifOneTime === false) deps.ifValue.close(); if (deps.oneTime === false) deps.value.close(); } }, updateDependencies: function(directives, model) { this.closeDeps(); var deps = this.deps = {}; var template = this.templateElement_; var ifValue = true; if (directives.if) { deps.hasIf = true; deps.ifOneTime = directives.if.onlyOneTime; deps.ifValue = processBinding(IF, directives.if, template, model); ifValue = deps.ifValue; // oneTime if & predicate is false. nothing else to do. if (deps.ifOneTime && !ifValue) { this.valueChanged(); return; } if (!deps.ifOneTime) ifValue = ifValue.open(this.updateIfValue, this); } if (directives.repeat) { deps.repeat = true; deps.oneTime = directives.repeat.onlyOneTime; deps.value = processBinding(REPEAT, directives.repeat, template, model); } else { deps.repeat = false; deps.oneTime = directives.bind.onlyOneTime; deps.value = processBinding(BIND, directives.bind, template, model); } var value = deps.value; if (!deps.oneTime) value = value.open(this.updateIteratedValue, this); if (!ifValue) { this.valueChanged(); return; } this.updateValue(value); }, /** * Gets the updated value of the bind/repeat. This can potentially call * user code (if a bindingDelegate is set up) so we try to avoid it if we * already have the value in hand (from Observer.open). */ getUpdatedValue: function() { var value = this.deps.value; if (!this.deps.oneTime) value = value.discardChanges(); return value; }, updateIfValue: function(ifValue) { if (!ifValue) { this.valueChanged(); return; } this.updateValue(this.getUpdatedValue()); }, updateIteratedValue: function(value) { if (this.deps.hasIf) { var ifValue = this.deps.ifValue; if (!this.deps.ifOneTime) ifValue = ifValue.discardChanges(); if (!ifValue) { this.valueChanged(); return; } } this.updateValue(value); }, updateValue: function(value) { if (!this.deps.repeat) value = [value]; var observe = this.deps.repeat && !this.deps.oneTime && Array.isArray(value); this.valueChanged(value, observe); }, valueChanged: function(value, observeValue) { if (!Array.isArray(value)) value = []; if (value === this.iteratedValue) return; this.unobserve(); this.presentValue = value; if (observeValue) { this.arrayObserver = new ArrayObserver(this.presentValue); this.arrayObserver.open(this.handleSplices, this); } this.handleSplices(ArrayObserver.calculateSplices(this.presentValue, this.iteratedValue)); }, getLastInstanceNode: function(index) { if (index == -1) return this.templateElement_; var instance = this.instances[index]; var terminator = instance.terminator_; if (!terminator) return this.getLastInstanceNode(index - 1); if (terminator.nodeType !== Node.ELEMENT_NODE || this.templateElement_ === terminator) { return terminator; } var subtemplateIterator = terminator.iterator_; if (!subtemplateIterator) return terminator; return subtemplateIterator.getLastTemplateNode(); }, getLastTemplateNode: function() { return this.getLastInstanceNode(this.instances.length - 1); }, insertInstanceAt: function(index, fragment) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var parent = this.templateElement_.parentNode; this.instances.splice(index, 0, fragment); parent.insertBefore(fragment, previousInstanceLast.nextSibling); }, extractInstanceAt: function(index) { var previousInstanceLast = this.getLastInstanceNode(index - 1); var lastNode = this.getLastInstanceNode(index); var parent = this.templateElement_.parentNode; var instance = this.instances.splice(index, 1)[0]; while (lastNode !== previousInstanceLast) { var node = previousInstanceLast.nextSibling; if (node == lastNode) lastNode = previousInstanceLast; instance.appendChild(parent.removeChild(node)); } return instance; }, getDelegateFn: function(fn) { fn = fn && fn(this.templateElement_); return typeof fn === 'function' ? fn : null; }, handleSplices: function(splices) { if (this.closed || !splices.length) return; var template = this.templateElement_; if (!template.parentNode) { this.close(); return; } ArrayObserver.applySplices(this.iteratedValue, this.presentValue, splices); var delegate = template.delegate_; if (this.instanceModelFn_ === undefined) { this.instanceModelFn_ = this.getDelegateFn(delegate && delegate.prepareInstanceModel); } if (this.instancePositionChangedFn_ === undefined) { this.instancePositionChangedFn_ = this.getDelegateFn(delegate && delegate.prepareInstancePositionChanged); } // Instance Removals var instanceCache = new Map; var removeDelta = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var removed = splice.removed; for (var j = 0; j < removed.length; j++) { var model = removed[j]; var instance = this.extractInstanceAt(splice.index + removeDelta); if (instance !== emptyInstance) { instanceCache.set(model, instance); } } removeDelta -= splice.addedCount; } // Instance Insertions for (var i = 0; i < splices.length; i++) { var splice = splices[i]; var addIndex = splice.index; for (; addIndex < splice.index + splice.addedCount; addIndex++) { var model = this.iteratedValue[addIndex]; var instance = instanceCache.get(model); if (instance) { instanceCache.delete(model); } else { if (this.instanceModelFn_) { model = this.instanceModelFn_(model); } if (model === undefined) { instance = emptyInstance; } else { instance = template.createInstance(model, undefined, delegate); } } this.insertInstanceAt(addIndex, instance); } } instanceCache.forEach(function(instance) { this.closeInstanceBindings(instance); }, this); if (this.instancePositionChangedFn_) this.reportInstancesMoved(splices); }, reportInstanceMoved: function(index) { var instance = this.instances[index]; if (instance === emptyInstance) return; this.instancePositionChangedFn_(instance.templateInstance_, index); }, reportInstancesMoved: function(splices) { var index = 0; var offset = 0; for (var i = 0; i < splices.length; i++) { var splice = splices[i]; if (offset != 0) { while (index < splice.index) { this.reportInstanceMoved(index); index++; } } else { index = splice.index; } while (index < splice.index + splice.addedCount) { this.reportInstanceMoved(index); index++; } offset += splice.addedCount - splice.removed.length; } if (offset == 0) return; var length = this.instances.length; while (index < length) { this.reportInstanceMoved(index); index++; } }, closeInstanceBindings: function(instance) { var bindings = instance.bindings_; for (var i = 0; i < bindings.length; i++) { bindings[i].close(); } }, unobserve: function() { if (!this.arrayObserver) return; this.arrayObserver.close(); this.arrayObserver = undefined; }, close: function() { if (this.closed) return; this.unobserve(); for (var i = 0; i < this.instances.length; i++) { this.closeInstanceBindings(this.instances[i]); } this.instances.length = 0; this.closeDeps(); this.templateElement_.iterator_ = undefined; this.closed = true; } }; // Polyfill-specific API. HTMLTemplateElement.forAllTemplatesFrom_ = forAllTemplatesFrom; })(this); (function(scope) { 'use strict'; // feature detect for URL constructor var hasWorkingUrl = false; if (!scope.forceJURL) { try { var u = new URL('b', 'http://a'); hasWorkingUrl = u.href === 'http://a/b'; } catch(e) {} } if (hasWorkingUrl) return; var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' == h) { invalid.call(this) } // XXX return h.toLowerCase() } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message) } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' == c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' == this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme == this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF == c) { break loop; } else { err('Code point not allowed in scheme: ' + c) break loop; } break; case 'scheme data': if ('?' == c) { query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' == c && '/' == input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue } break; case 'relative': this._isRelative = true; if ('file' != this._scheme) this._scheme = base._scheme; if (EOF == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; break loop; } else if ('/' == c || '\\' == c) { if ('\\' == c) err('\\ is an invalid code point.'); state = 'relative slash'; } else if ('?' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; state = 'query'; } else if ('#' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; state = 'fragment'; } else { var nextC = input[cursor+1] var nextNextC = input[cursor+2] if ( 'file' != this._scheme || !ALPHA.test(c) || (nextC != ':' && nextC != '|') || (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' == c || '\\' == c) { if ('\\' == c) { err('\\ is an invalid code point.'); } if ('file' == this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' != this._scheme) { this._host = base._host; this._port = base._port; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' == c) { state = 'authority second slash'; } else { err("Expected '/', got: " + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' != c) { err("Expected '/', got: " + c); continue; } break; case 'authority ignore slashes': if ('/' != c && '\\' != c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' == c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' == cp || '\n' == cp || '\r' == cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' == cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); (null !== this._password) ? this._password += tempC : this._username += tempC; } buffer = ''; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { state = 'relative path'; } else if (buffer.length == 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' == c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' == stateOverride) { break loop; } } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' != c && '\n' != c && '\r' != c) { if ('[' == c) { seenBracket = true; } else if (']' == c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { if ('' != buffer) { var temp = parseInt(buffer, 10); if (temp != relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' == c) err("'\\' not allowed in path."); state = 'relative path'; if ('/' != c && '\\' != c) { continue; } break; case 'relative path': if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { if ('\\' == c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' == buffer) { this._path.pop(); if ('/' != c && '\\' != c) { this._path.push(''); } } else if ('.' == buffer && '/' != c && '\\' != c) { this._path.push(''); } else if ('.' != buffer) { if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' != c && '\n' != c && '\r' != c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' == c) { this._fragment = '#'; state = 'fragment'; } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function jURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } jURL.prototype = { get href() { if (this._isInvalid) return this._url; var authority = ''; if ('' != this._username || null != this._password) { authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) return; parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) return; parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) return; parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) return; parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) return; this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) return; this._query = '?'; if ('?' == search[0]) search = search.slice(1); parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) return; this._fragment = '#'; if ('#' == hash[0]) hash = hash.slice(1); parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { jURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; jURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = jURL; })(this); (function(scope) { var iterations = 0; var callbacks = []; var twiddle = document.createTextNode(''); function endOfMicrotask(callback) { twiddle.textContent = iterations++; callbacks.push(callback); } function atEndOfMicrotask() { while (callbacks.length) { callbacks.shift()(); } } new (window.MutationObserver || JsMutationObserver)(atEndOfMicrotask) .observe(twiddle, {characterData: true}) ; // exports scope.endOfMicrotask = endOfMicrotask; // bc Platform.endOfMicrotask = endOfMicrotask; })(Polymer); (function(scope) { /** * @class Polymer */ // imports var endOfMicrotask = scope.endOfMicrotask; // logging var log = window.WebComponents ? WebComponents.flags.log : {}; // inject style sheet var style = document.createElement('style'); style.textContent = 'template {display: none !important;} /* injected by platform.js */'; var head = document.querySelector('head'); head.insertBefore(style, head.firstChild); /** * Force any pending data changes to be observed before * the next task. Data changes are processed asynchronously but are guaranteed * to be processed, for example, before painting. This method should rarely be * needed. It does nothing when Object.observe is available; * when Object.observe is not available, Polymer automatically flushes data * changes approximately every 1/10 second. * Therefore, `flush` should only be used when a data mutation should be * observed sooner than this. * * @method flush */ // flush (with logging) var flushing; function flush() { if (!flushing) { flushing = true; endOfMicrotask(function() { flushing = false; log.data && console.group('flush'); Platform.performMicrotaskCheckpoint(); log.data && console.groupEnd(); }); } }; // polling dirty checker // flush periodically if platform does not have object observe. if (!Observer.hasObjectObserve) { var FLUSH_POLL_INTERVAL = 125; window.addEventListener('WebComponentsReady', function() { flush(); // watch document visiblity to toggle dirty-checking var visibilityHandler = function() { // only flush if the page is visibile if (document.visibilityState === 'hidden') { if (scope.flushPoll) { clearInterval(scope.flushPoll); } } else { scope.flushPoll = setInterval(flush, FLUSH_POLL_INTERVAL); } }; if (typeof document.visibilityState === 'string') { document.addEventListener('visibilitychange', visibilityHandler); } visibilityHandler(); }); } else { // make flush a no-op when we have Object.observe flush = function() {}; } if (window.CustomElements && !CustomElements.useNative) { var originalImportNode = Document.prototype.importNode; Document.prototype.importNode = function(node, deep) { var imported = originalImportNode.call(this, node, deep); CustomElements.upgradeAll(imported); return imported; }; } // exports scope.flush = flush; // bc Platform.flush = flush; })(window.Polymer); (function(scope) { var urlResolver = { resolveDom: function(root, url) { url = url || baseUrl(root); this.resolveAttributes(root, url); this.resolveStyles(root, url); // handle template.content var templates = root.querySelectorAll('template'); if (templates) { for (var i = 0, l = templates.length, t; (i < l) && (t = templates[i]); i++) { if (t.content) { this.resolveDom(t.content, url); } } } }, resolveTemplate: function(template) { this.resolveDom(template.content, baseUrl(template)); }, resolveStyles: function(root, url) { var styles = root.querySelectorAll('style'); if (styles) { for (var i = 0, l = styles.length, s; (i < l) && (s = styles[i]); i++) { this.resolveStyle(s, url); } } }, resolveStyle: function(style, url) { url = url || baseUrl(style); style.textContent = this.resolveCssText(style.textContent, url); }, resolveCssText: function(cssText, baseUrl, keepAbsolute) { cssText = replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_URL_REGEXP); return replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, CSS_IMPORT_REGEXP); }, resolveAttributes: function(root, url) { if (root.hasAttributes && root.hasAttributes()) { this.resolveElementAttributes(root, url); } // search for attributes that host urls var nodes = root && root.querySelectorAll(URL_ATTRS_SELECTOR); if (nodes) { for (var i = 0, l = nodes.length, n; (i < l) && (n = nodes[i]); i++) { this.resolveElementAttributes(n, url); } } }, resolveElementAttributes: function(node, url) { url = url || baseUrl(node); URL_ATTRS.forEach(function(v) { var attr = node.attributes[v]; var value = attr && attr.value; var replacement; if (value && value.search(URL_TEMPLATE_SEARCH) < 0) { if (v === 'style') { replacement = replaceUrlsInCssText(value, url, false, CSS_URL_REGEXP); } else { replacement = resolveRelativeUrl(url, value); } attr.value = replacement; } }); } }; var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g; var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g; var URL_ATTRS = ['href', 'src', 'action', 'style', 'url']; var URL_ATTRS_SELECTOR = '[' + URL_ATTRS.join('],[') + ']'; var URL_TEMPLATE_SEARCH = '{{.*}}'; var URL_HASH = '#'; function baseUrl(node) { var u = new URL(node.ownerDocument.baseURI); u.search = ''; u.hash = ''; return u; } function replaceUrlsInCssText(cssText, baseUrl, keepAbsolute, regexp) { return cssText.replace(regexp, function(m, pre, url, post) { var urlPath = url.replace(/["']/g, ''); urlPath = resolveRelativeUrl(baseUrl, urlPath, keepAbsolute); return pre + '\'' + urlPath + '\'' + post; }); } function resolveRelativeUrl(baseUrl, url, keepAbsolute) { // do not resolve '/' absolute urls if (url && url[0] === '/') { return url; } var u = new URL(url, baseUrl); return keepAbsolute ? u.href : makeDocumentRelPath(u.href); } function makeDocumentRelPath(url) { var root = baseUrl(document.documentElement); var u = new URL(url, root); if (u.host === root.host && u.port === root.port && u.protocol === root.protocol) { return makeRelPath(root, u); } else { return url; } } // make a relative path from source to target function makeRelPath(sourceUrl, targetUrl) { var source = sourceUrl.pathname; var target = targetUrl.pathname; var s = source.split('/'); var t = target.split('/'); while (s.length && s[0] === t[0]){ s.shift(); t.shift(); } for (var i = 0, l = s.length - 1; i < l; i++) { t.unshift('..'); } // empty '#' is discarded but we need to preserve it. var hash = (targetUrl.href.slice(-1) === URL_HASH) ? URL_HASH : targetUrl.hash; return t.join('/') + targetUrl.search + hash; } // exports scope.urlResolver = urlResolver; })(Polymer); (function(scope) { var endOfMicrotask = Polymer.endOfMicrotask; // Generic url loader function Loader(regex) { this.cache = Object.create(null); this.map = Object.create(null); this.requests = 0; this.regex = regex; } Loader.prototype = { // TODO(dfreedm): there may be a better factoring here // extract absolute urls from the text (full of relative urls) extractUrls: function(text, base) { var matches = []; var matched, u; while ((matched = this.regex.exec(text))) { u = new URL(matched[1], base); matches.push({matched: matched[0], url: u.href}); } return matches; }, // take a text blob, a root url, and a callback and load all the urls found within the text // returns a map of absolute url to text process: function(text, root, callback) { var matches = this.extractUrls(text, root); // every call to process returns all the text this loader has ever received var done = callback.bind(null, this.map); this.fetch(matches, done); }, // build a mapping of url -> text from matches fetch: function(matches, callback) { var inflight = matches.length; // return early if there is no fetching to be done if (!inflight) { return callback(); } // wait for all subrequests to return var done = function() { if (--inflight === 0) { callback(); } }; // start fetching all subrequests var m, req, url; for (var i = 0; i < inflight; i++) { m = matches[i]; url = m.url; req = this.cache[url]; // if this url has already been requested, skip requesting it again if (!req) { req = this.xhr(url); req.match = m; this.cache[url] = req; } // wait for the request to process its subrequests req.wait(done); } }, handleXhr: function(request) { var match = request.match; var url = match.url; // handle errors with an empty string var response = request.response || request.responseText || ''; this.map[url] = response; this.fetch(this.extractUrls(response, url), request.resolve); }, xhr: function(url) { this.requests++; var request = new XMLHttpRequest(); request.open('GET', url, true); request.send(); request.onerror = request.onload = this.handleXhr.bind(this, request); // queue of tasks to run after XHR returns request.pending = []; request.resolve = function() { var pending = request.pending; for(var i = 0; i < pending.length; i++) { pending[i](); } request.pending = null; }; // if we have already resolved, pending is null, async call the callback request.wait = function(fn) { if (request.pending) { request.pending.push(fn); } else { endOfMicrotask(fn); } }; return request; } }; scope.Loader = Loader; })(Polymer); (function(scope) { var urlResolver = scope.urlResolver; var Loader = scope.Loader; function StyleResolver() { this.loader = new Loader(this.regex); } StyleResolver.prototype = { regex: /@import\s+(?:url)?["'\(]*([^'"\)]*)['"\)]*;/g, // Recursively replace @imports with the text at that url resolve: function(text, url, callback) { var done = function(map) { callback(this.flatten(text, url, map)); }.bind(this); this.loader.process(text, url, done); }, // resolve the textContent of a style node resolveNode: function(style, url, callback) { var text = style.textContent; var done = function(text) { style.textContent = text; callback(style); }; this.resolve(text, url, done); }, // flatten all the @imports to text flatten: function(text, base, map) { var matches = this.loader.extractUrls(text, base); var match, url, intermediate; for (var i = 0; i < matches.length; i++) { match = matches[i]; url = match.url; // resolve any css text to be relative to the importer, keep absolute url intermediate = urlResolver.resolveCssText(map[url], url, true); // flatten intermediate @imports intermediate = this.flatten(intermediate, base, map); text = text.replace(match.matched, intermediate); } return text; }, loadStyles: function(styles, base, callback) { var loaded=0, l = styles.length; // called in the context of the style function loadedStyle(style) { loaded++; if (loaded === l && callback) { callback(); } } for (var i=0, s; (i<l) && (s=styles[i]); i++) { this.resolveNode(s, base, loadedStyle); } } }; var styleResolver = new StyleResolver(); // exports scope.styleResolver = styleResolver; })(Polymer); (function(scope) { // copy own properties from 'api' to 'prototype, with name hinting for 'super' function extend(prototype, api) { if (prototype && api) { // use only own properties of 'api' Object.getOwnPropertyNames(api).forEach(function(n) { // acquire property descriptor var pd = Object.getOwnPropertyDescriptor(api, n); if (pd) { // clone property via descriptor Object.defineProperty(prototype, n, pd); // cache name-of-method for 'super' engine if (typeof pd.value == 'function') { // hint the 'super' engine pd.value.nom = n; } } }); } return prototype; } // mixin // copy all properties from inProps (et al) to inObj function mixin(inObj/*, inProps, inMoreProps, ...*/) { var obj = inObj || {}; for (var i = 1; i < arguments.length; i++) { var p = arguments[i]; try { for (var n in p) { copyProperty(n, p, obj); } } catch(x) { } } return obj; } // copy property inName from inSource object to inTarget object function copyProperty(inName, inSource, inTarget) { var pd = getPropertyDescriptor(inSource, inName); Object.defineProperty(inTarget, inName, pd); } // get property descriptor for inName on inObject, even if // inName exists on some link in inObject's prototype chain function getPropertyDescriptor(inObject, inName) { if (inObject) { var pd = Object.getOwnPropertyDescriptor(inObject, inName); return pd || getPropertyDescriptor(Object.getPrototypeOf(inObject), inName); } } // exports scope.extend = extend; scope.mixin = mixin; // for bc Platform.mixin = mixin; })(Polymer); (function(scope) { // usage // invoke cb.call(this) in 100ms, unless the job is re-registered, // which resets the timer // // this.myJob = this.job(this.myJob, cb, 100) // // returns a job handle which can be used to re-register a job var Job = function(inContext) { this.context = inContext; this.boundComplete = this.complete.bind(this) }; Job.prototype = { go: function(callback, wait) { this.callback = callback; var h; if (!wait) { h = requestAnimationFrame(this.boundComplete); this.handle = function() { cancelAnimationFrame(h); } } else { h = setTimeout(this.boundComplete, wait); this.handle = function() { clearTimeout(h); } } }, stop: function() { if (this.handle) { this.handle(); this.handle = null; } }, complete: function() { if (this.handle) { this.stop(); this.callback.call(this.context); } } }; function job(job, callback, wait) { if (job) { job.stop(); } else { job = new Job(this); } job.go(callback, wait); return job; } // exports scope.job = job; })(Polymer); (function(scope) { // dom polyfill, additions, and utility methods var registry = {}; HTMLElement.register = function(tag, prototype) { registry[tag] = prototype; }; // get prototype mapped to node <tag> HTMLElement.getPrototypeForTag = function(tag) { var prototype = !tag ? HTMLElement.prototype : registry[tag]; // TODO(sjmiles): creating <tag> is likely to have wasteful side-effects return prototype || Object.getPrototypeOf(document.createElement(tag)); }; // we have to flag propagation stoppage for the event dispatcher var originalStopPropagation = Event.prototype.stopPropagation; Event.prototype.stopPropagation = function() { this.cancelBubble = true; originalStopPropagation.apply(this, arguments); }; // polyfill DOMTokenList // * add/remove: allow these methods to take multiple classNames // * toggle: add a 2nd argument which forces the given state rather // than toggling. var add = DOMTokenList.prototype.add; var remove = DOMTokenList.prototype.remove; DOMTokenList.prototype.add = function() { for (var i = 0; i < arguments.length; i++) { add.call(this, arguments[i]); } }; DOMTokenList.prototype.remove = function() { for (var i = 0; i < arguments.length; i++) { remove.call(this, arguments[i]); } }; DOMTokenList.prototype.toggle = function(name, bool) { if (arguments.length == 1) { bool = !this.contains(name); } bool ? this.add(name) : this.remove(name); }; DOMTokenList.prototype.switch = function(oldName, newName) { oldName && this.remove(oldName); newName && this.add(newName); }; // add array() to NodeList, NamedNodeMap, HTMLCollection var ArraySlice = function() { return Array.prototype.slice.call(this); }; var namedNodeMap = (window.NamedNodeMap || window.MozNamedAttrMap || {}); NodeList.prototype.array = ArraySlice; namedNodeMap.prototype.array = ArraySlice; HTMLCollection.prototype.array = ArraySlice; // utility function createDOM(inTagOrNode, inHTML, inAttrs) { var dom = typeof inTagOrNode == 'string' ? document.createElement(inTagOrNode) : inTagOrNode.cloneNode(true); dom.innerHTML = inHTML; if (inAttrs) { for (var n in inAttrs) { dom.setAttribute(n, inAttrs[n]); } } return dom; } // exports scope.createDOM = createDOM; })(Polymer); (function(scope) { // super // `arrayOfArgs` is an optional array of args like one might pass // to `Function.apply` // TODO(sjmiles): // $super must be installed on an instance or prototype chain // as `super`, and invoked via `this`, e.g. // `this.super();` // will not work if function objects are not unique, for example, // when using mixins. // The memoization strategy assumes each function exists on only one // prototype chain i.e. we use the function object for memoizing) // perhaps we can bookkeep on the prototype itself instead function $super(arrayOfArgs) { // since we are thunking a method call, performance is important here: // memoize all lookups, once memoized the fast path calls no other // functions // // find the caller (cannot be `strict` because of 'caller') var caller = $super.caller; // memoized 'name of method' var nom = caller.nom; // memoized next implementation prototype var _super = caller._super; if (!_super) { if (!nom) { nom = caller.nom = nameInThis.call(this, caller); } if (!nom) { console.warn('called super() on a method not installed declaratively (has no .nom property)'); } // super prototype is either cached or we have to find it // by searching __proto__ (at the 'top') // invariant: because we cache _super on fn below, we never reach // here from inside a series of calls to super(), so it's ok to // start searching from the prototype of 'this' (at the 'top') // we must never memoize a null super for this reason _super = memoizeSuper(caller, nom, getPrototypeOf(this)); } // our super function var fn = _super[nom]; if (fn) { // memoize information so 'fn' can call 'super' if (!fn._super) { // must not memoize null, or we lose our invariant above memoizeSuper(fn, nom, _super); } // invoke the inherited method // if 'fn' is not function valued, this will throw return fn.apply(this, arrayOfArgs || []); } } function nameInThis(value) { var p = this.__proto__; while (p && p !== HTMLElement.prototype) { // TODO(sjmiles): getOwnPropertyNames is absurdly expensive var n$ = Object.getOwnPropertyNames(p); for (var i=0, l=n$.length, n; i<l && (n=n$[i]); i++) { var d = Object.getOwnPropertyDescriptor(p, n); if (typeof d.value === 'function' && d.value === value) { return n; } } p = p.__proto__; } } function memoizeSuper(method, name, proto) { // find and cache next prototype containing `name` // we need the prototype so we can do another lookup // from here var s = nextSuper(proto, name, method); if (s[name]) { // `s` is a prototype, the actual method is `s[name]` // tag super method with it's name for quicker lookups s[name].nom = name; } return method._super = s; } function nextSuper(proto, name, caller) { // look for an inherited prototype that implements name while (proto) { if ((proto[name] !== caller) && proto[name]) { return proto; } proto = getPrototypeOf(proto); } // must not return null, or we lose our invariant above // in this case, a super() call was invoked where no superclass // method exists // TODO(sjmiles): thow an exception? return Object; } // NOTE: In some platforms (IE10) the prototype chain is faked via // __proto__. Therefore, always get prototype via __proto__ instead of // the more standard Object.getPrototypeOf. function getPrototypeOf(prototype) { return prototype.__proto__; } // utility function to precompute name tags for functions // in a (unchained) prototype function hintSuper(prototype) { // tag functions with their prototype name to optimize // super call invocations for (var n in prototype) { var pd = Object.getOwnPropertyDescriptor(prototype, n); if (pd && typeof pd.value === 'function') { pd.value.nom = n; } } } // exports scope.super = $super; })(Polymer); (function(scope) { function noopHandler(value) { return value; } // helper for deserializing properties of various types to strings var typeHandlers = { string: noopHandler, 'undefined': noopHandler, date: function(value) { return new Date(Date.parse(value) || Date.now()); }, boolean: function(value) { if (value === '') { return true; } return value === 'false' ? false : !!value; }, number: function(value) { var n = parseFloat(value); // hex values like "0xFFFF" parseFloat as 0 if (n === 0) { n = parseInt(value); } return isNaN(n) ? value : n; // this code disabled because encoded values (like "0xFFFF") // do not round trip to their original format //return (String(floatVal) === value) ? floatVal : value; }, object: function(value, currentValue) { if (currentValue === null) { return value; } try { // If the string is an object, we can parse is with the JSON library. // include convenience replace for single-quotes. If the author omits // quotes altogether, parse will fail. return JSON.parse(value.replace(/'/g, '"')); } catch(e) { // The object isn't valid JSON, return the raw value return value; } }, // avoid deserialization of functions 'function': function(value, currentValue) { return currentValue; } }; function deserializeValue(value, currentValue) { // attempt to infer type from default value var inferredType = typeof currentValue; // invent 'date' type value for Date if (currentValue instanceof Date) { inferredType = 'date'; } // delegate deserialization via type string return typeHandlers[inferredType](value, currentValue); } // exports scope.deserializeValue = deserializeValue; })(Polymer); (function(scope) { // imports var extend = scope.extend; // module var api = {}; api.declaration = {}; api.instance = {}; api.publish = function(apis, prototype) { for (var n in apis) { extend(prototype, apis[n]); } }; // exports scope.api = api; })(Polymer); (function(scope) { /** * @class polymer-base */ var utils = { /** * Invokes a function asynchronously. The context of the callback * function is bound to 'this' automatically. Returns a handle which may * be passed to <a href="#cancelAsync">cancelAsync</a> to cancel the * asynchronous call. * * @method async * @param {Function|String} method * @param {any|Array} args * @param {number} timeout */ async: function(method, args, timeout) { // when polyfilling Object.observe, ensure changes // propagate before executing the async method Polymer.flush(); // second argument to `apply` must be an array args = (args && args.length) ? args : [args]; // function to invoke var fn = function() { (this[method] || method).apply(this, args); }.bind(this); // execute `fn` sooner or later var handle = timeout ? setTimeout(fn, timeout) : requestAnimationFrame(fn); // NOTE: switch on inverting handle to determine which time is used. return timeout ? handle : ~handle; }, /** * Cancels a pending callback that was scheduled via * <a href="#async">async</a>. * * @method cancelAsync * @param {handle} handle Handle of the `async` to cancel. */ cancelAsync: function(handle) { if (handle < 0) { cancelAnimationFrame(~handle); } else { clearTimeout(handle); } }, /** * Fire an event. * * @method fire * @returns {Object} event * @param {string} type An event name. * @param {any} detail * @param {Node} onNode Target node. * @param {Boolean} bubbles Set false to prevent bubbling, defaults to true * @param {Boolean} cancelable Set false to prevent cancellation, defaults to true */ fire: function(type, detail, onNode, bubbles, cancelable) { var node = onNode || this; var detail = detail === null || detail === undefined ? {} : detail; var event = new CustomEvent(type, { bubbles: bubbles !== undefined ? bubbles : true, cancelable: cancelable !== undefined ? cancelable : true, detail: detail }); node.dispatchEvent(event); return event; }, /** * Fire an event asynchronously. * * @method asyncFire * @param {string} type An event name. * @param detail * @param {Node} toNode Target node. */ asyncFire: function(/*inType, inDetail*/) { this.async("fire", arguments); }, /** * Remove class from old, add class to anew, if they exist. * * @param classFollows * @param anew A node. * @param old A node * @param className */ classFollows: function(anew, old, className) { if (old) { old.classList.remove(className); } if (anew) { anew.classList.add(className); } }, /** * Inject HTML which contains markup bound to this element into * a target element (replacing target element content). * * @param String html to inject * @param Element target element */ injectBoundHTML: function(html, element) { var template = document.createElement('template'); template.innerHTML = html; var fragment = this.instanceTemplate(template); if (element) { element.textContent = ''; element.appendChild(fragment); } return fragment; } }; // no-operation function for handy stubs var nop = function() {}; // null-object for handy stubs var nob = {}; // deprecated utils.asyncMethod = utils.async; // exports scope.api.instance.utils = utils; scope.nop = nop; scope.nob = nob; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var EVENT_PREFIX = 'on-'; // instance events api var events = { // read-only EVENT_PREFIX: EVENT_PREFIX, // event listeners on host addHostListeners: function() { var events = this.eventDelegates; log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events); // NOTE: host events look like bindings but really are not; // (1) we don't want the attribute to be set and (2) we want to support // multiple event listeners ('host' and 'instance') and Node.bind // by default supports 1 thing being bound. for (var type in events) { var methodName = events[type]; PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName)); } }, // call 'method' or function method on 'obj' with 'args', if the method exists dispatchMethod: function(obj, method, args) { if (obj) { log.events && console.group('[%s] dispatch [%s]', obj.localName, method); var fn = typeof method === 'function' ? method : obj[method]; if (fn) { fn[args ? 'apply' : 'call'](obj, args); } log.events && console.groupEnd(); // NOTE: dirty check right after calling method to ensure // changes apply quickly; in a very complicated app using high // frequency events, this can be a perf concern; in this case, // imperative handlers can be used to avoid flushing. Polymer.flush(); } } }; // exports scope.api.instance.events = events; /** * @class Polymer */ /** * Add a gesture aware event handler to the given `node`. Can be used * in place of `element.addEventListener` and ensures gestures will function * as expected on mobile platforms. Please note that Polymer's declarative * event handlers include this functionality by default. * * @method addEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ // alias PolymerGestures event listener logic scope.addEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.addEventListener(wrap(node), eventType, handlerFn, capture); }; /** * Remove a gesture aware event handler on the given `node`. To remove an * event listener, the exact same arguments are required that were passed * to `Polymer.addEventListener`. * * @method removeEventListener * @param {Node} node node on which to listen * @param {String} eventType name of the event * @param {Function} handlerFn event handler function * @param {Boolean} capture set to true to invoke event capturing * @type Function */ scope.removeEventListener = function(node, eventType, handlerFn, capture) { PolymerGestures.removeEventListener(wrap(node), eventType, handlerFn, capture); }; })(Polymer); (function(scope) { // instance api for attributes var attributes = { // copy attributes defined in the element declaration to the instance // e.g. <polymer-element name="x-foo" tabIndex="0"> tabIndex is copied // to the element instance here. copyInstanceAttributes: function () { var a$ = this._instanceAttributes; for (var k in a$) { if (!this.hasAttribute(k)) { this.setAttribute(k, a$[k]); } } }, // for each attribute on this, deserialize value to property as needed takeAttributes: function() { // if we have no publish lookup table, we have no attributes to take // TODO(sjmiles): ad hoc if (this._publishLC) { for (var i=0, a$=this.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { this.attributeToProperty(a.name, a.value); } } }, // if attribute 'name' is mapped to a property, deserialize // 'value' into that property attributeToProperty: function(name, value) { // try to match this attribute to a property (attributes are // all lower-case, so this is case-insensitive search) var name = this.propertyForAttribute(name); if (name) { // filter out 'mustached' values, these are to be // replaced with bound-data and are not yet values // themselves if (value && value.search(scope.bindPattern) >= 0) { return; } // get original value var currentValue = this[name]; // deserialize Boolean or Number values from attribute var value = this.deserializeValue(value, currentValue); // only act if the value has changed if (value !== currentValue) { // install new value (has side-effects) this[name] = value; } } }, // return the published property matching name, or undefined propertyForAttribute: function(name) { var match = this._publishLC && this._publishLC[name]; return match; }, // convert representation of `stringValue` based on type of `currentValue` deserializeValue: function(stringValue, currentValue) { return scope.deserializeValue(stringValue, currentValue); }, // convert to a string value based on the type of `inferredType` serializeValue: function(value, inferredType) { if (inferredType === 'boolean') { return value ? '' : undefined; } else if (inferredType !== 'object' && inferredType !== 'function' && value !== undefined) { return value; } }, // serializes `name` property value and updates the corresponding attribute // note that reflection is opt-in. reflectPropertyToAttribute: function(name) { var inferredType = typeof this[name]; // try to intelligently serialize property value var serializedValue = this.serializeValue(this[name], inferredType); // boolean properties must reflect as boolean attributes if (serializedValue !== undefined) { this.setAttribute(name, serializedValue); // TODO(sorvell): we should remove attr for all properties // that have undefined serialization; however, we will need to // refine the attr reflection system to achieve this; pica, for example, // relies on having inferredType object properties not removed as // attrs. } else if (inferredType === 'boolean') { this.removeAttribute(name); } } }; // exports scope.api.instance.attributes = attributes; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // magic words var OBSERVE_SUFFIX = 'Changed'; // element api var empty = []; var updateRecord = { object: undefined, type: 'update', name: undefined, oldValue: undefined }; var numberIsNaN = Number.isNaN || function(value) { return typeof value === 'number' && isNaN(value); }; function areSameValue(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; if (numberIsNaN(left) && numberIsNaN(right)) return true; return left !== left && right !== right; } // capture A's value if B's value is null or undefined, // otherwise use B's value function resolveBindingValue(oldValue, value) { if (value === undefined && oldValue === null) { return value; } return (value === null || value === undefined) ? oldValue : value; } var properties = { // creates a CompoundObserver to observe property changes // NOTE, this is only done there are any properties in the `observe` object createPropertyObserver: function() { var n$ = this._observeNames; if (n$ && n$.length) { var o = this._propertyObserver = new CompoundObserver(true); this.registerObserver(o); // TODO(sorvell): may not be kosher to access the value here (this[n]); // previously we looked at the descriptor on the prototype // this doesn't work for inheritance and not for accessors without // a value property for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { o.addPath(this, n); this.observeArrayValue(n, this[n], null); } } }, // start observing property changes openPropertyObserver: function() { if (this._propertyObserver) { this._propertyObserver.open(this.notifyPropertyChanges, this); } }, // handler for property changes; routes changes to observing methods // note: array valued properties are observed for array splices notifyPropertyChanges: function(newValues, oldValues, paths) { var name, method, called = {}; for (var i in oldValues) { // note: paths is of form [object, path, object, path] name = paths[2 * i + 1]; method = this.observe[name]; if (method) { var ov = oldValues[i], nv = newValues[i]; // observes the value if it is an array this.observeArrayValue(name, nv, ov); if (!called[method]) { // only invoke change method if one of ov or nv is not (undefined | null) if ((ov !== undefined && ov !== null) || (nv !== undefined && nv !== null)) { called[method] = true; // TODO(sorvell): call method with the set of values it's expecting; // e.g. 'foo bar': 'invalidate' expects the new and old values for // foo and bar. Currently we give only one of these and then // deliver all the arguments. this.invokeMethod(method, [ov, nv, arguments]); } } } } }, // call method iff it exists. invokeMethod: function(method, args) { var fn = this[method] || method; if (typeof fn === 'function') { fn.apply(this, args); } }, /** * Force any pending property changes to synchronously deliver to * handlers specified in the `observe` object. * Note, normally changes are processed at microtask time. * * @method deliverChanges */ deliverChanges: function() { if (this._propertyObserver) { this._propertyObserver.deliver(); } }, observeArrayValue: function(name, value, old) { // we only care if there are registered side-effects var callbackName = this.observe[name]; if (callbackName) { // if we are observing the previous value, stop if (Array.isArray(old)) { log.observe && console.log('[%s] observeArrayValue: unregister observer [%s]', this.localName, name); this.closeNamedObserver(name + '__array'); } // if the new value is an array, being observing it if (Array.isArray(value)) { log.observe && console.log('[%s] observeArrayValue: register observer [%s]', this.localName, name, value); var observer = new ArrayObserver(value); observer.open(function(splices) { this.invokeMethod(callbackName, [splices]); }, this); this.registerNamedObserver(name + '__array', observer); } } }, emitPropertyChangeRecord: function(name, value, oldValue) { var object = this; if (areSameValue(value, oldValue)) { return; } // invoke property change side effects this._propertyChanged(name, value, oldValue); // emit change record if (!Observer.hasObjectObserve) { return; } var notifier = this._objectNotifier; if (!notifier) { notifier = this._objectNotifier = Object.getNotifier(this); } updateRecord.object = this; updateRecord.name = name; updateRecord.oldValue = oldValue; notifier.notify(updateRecord); }, _propertyChanged: function(name, value, oldValue) { if (this.reflect[name]) { this.reflectPropertyToAttribute(name); } }, // creates a property binding (called via bind) to a published property. bindProperty: function(property, observable, oneTime) { if (oneTime) { this[property] = observable; return; } var computed = this.element.prototype.computed; // Binding an "out-only" value to a computed property. Note that // since this observer isn't opened, it doesn't need to be closed on // cleanup. if (computed && computed[property]) { var privateComputedBoundValue = property + 'ComputedBoundObservable_'; this[privateComputedBoundValue] = observable; return; } return this.bindToAccessor(property, observable, resolveBindingValue); }, // NOTE property `name` must be published. This makes it an accessor. bindToAccessor: function(name, observable, resolveFn) { var privateName = name + '_'; var privateObservable = name + 'Observable_'; // Present for properties which are computed and published and have a // bound value. var privateComputedBoundValue = name + 'ComputedBoundObservable_'; this[privateObservable] = observable; var oldValue = this[privateName]; // observable callback var self = this; function updateValue(value, oldValue) { self[privateName] = value; var setObserveable = self[privateComputedBoundValue]; if (setObserveable && typeof setObserveable.setValue == 'function') { setObserveable.setValue(value); } self.emitPropertyChangeRecord(name, value, oldValue); } // resolve initial value var value = observable.open(updateValue); if (resolveFn && !areSameValue(oldValue, value)) { var resolvedValue = resolveFn(oldValue, value); if (!areSameValue(value, resolvedValue)) { value = resolvedValue; if (observable.setValue) { observable.setValue(value); } } } updateValue(value, oldValue); // register and return observable var observer = { close: function() { observable.close(); self[privateObservable] = undefined; self[privateComputedBoundValue] = undefined; } }; this.registerObserver(observer); return observer; }, createComputedProperties: function() { if (!this._computedNames) { return; } for (var i = 0; i < this._computedNames.length; i++) { var name = this._computedNames[i]; var expressionText = this.computed[name]; try { var expression = PolymerExpressions.getExpression(expressionText); var observable = expression.getBinding(this, this.element.syntax); this.bindToAccessor(name, observable); } catch (ex) { console.error('Failed to create computed property', ex); } } }, // property bookkeeping registerObserver: function(observer) { if (!this._observers) { this._observers = [observer]; return; } this._observers.push(observer); }, closeObservers: function() { if (!this._observers) { return; } // observer array items are arrays of observers. var observers = this._observers; for (var i = 0; i < observers.length; i++) { var observer = observers[i]; if (observer && typeof observer.close == 'function') { observer.close(); } } this._observers = []; }, // bookkeeping observers for memory management registerNamedObserver: function(name, observer) { var o$ = this._namedObservers || (this._namedObservers = {}); o$[name] = observer; }, closeNamedObserver: function(name) { var o$ = this._namedObservers; if (o$ && o$[name]) { o$[name].close(); o$[name] = null; return true; } }, closeNamedObservers: function() { if (this._namedObservers) { for (var i in this._namedObservers) { this.closeNamedObserver(i); } this._namedObservers = {}; } } }; // logging var LOG_OBSERVE = '[%s] watching [%s]'; var LOG_OBSERVED = '[%s#%s] watch: [%s] now [%s] was [%s]'; var LOG_CHANGED = '[%s#%s] propertyChanged: [%s] now [%s] was [%s]'; // exports scope.api.instance.properties = properties; })(Polymer); (function(scope) { /** * @class polymer-base */ // imports var log = window.WebComponents ? WebComponents.flags.log : {}; // element api supporting mdv var mdv = { /** * Creates dom cloned from the given template, instantiating bindings * with this element as the template model and `PolymerExpressions` as the * binding delegate. * * @method instanceTemplate * @param {Template} template source template from which to create dom. */ instanceTemplate: function(template) { // ensure template is decorated (lets' things like <tr template ...> work) HTMLTemplateElement.decorate(template); // ensure a default bindingDelegate var syntax = this.syntax || (!template.bindingDelegate && this.element.syntax); var dom = template.createInstance(this, syntax); var observers = dom.bindings_; for (var i = 0; i < observers.length; i++) { this.registerObserver(observers[i]); } return dom; }, // Called by TemplateBinding/NodeBind to setup a binding to the given // property. It's overridden here to support property bindings // in addition to attribute bindings that are supported by default. bind: function(name, observable, oneTime) { var property = this.propertyForAttribute(name); if (!property) { // TODO(sjmiles): this mixin method must use the special form // of `super` installed by `mixinMethod` in declaration/prototype.js return this.mixinSuper(arguments); } else { // use n-way Polymer binding var observer = this.bindProperty(property, observable, oneTime); // NOTE: reflecting binding information is typically required only for // tooling. It has a performance cost so it's opt-in in Node.bind. if (Platform.enableBindingsReflection && observer) { observer.path = observable.path_; this._recordBinding(property, observer); } if (this.reflect[property]) { this.reflectPropertyToAttribute(property); } return observer; } }, _recordBinding: function(name, observer) { this.bindings_ = this.bindings_ || {}; this.bindings_[name] = observer; }, // Called by TemplateBinding when all bindings on an element have been // executed. This signals that all element inputs have been gathered // and it's safe to ready the element, create shadow-root and start // data-observation. bindFinished: function() { this.makeElementReady(); }, // called at detached time to signal that an element's bindings should be // cleaned up. This is done asynchronously so that users have the chance // to call `cancelUnbindAll` to prevent unbinding. asyncUnbindAll: function() { if (!this._unbound) { log.unbind && console.log('[%s] asyncUnbindAll', this.localName); this._unbindAllJob = this.job(this._unbindAllJob, this.unbindAll, 0); } }, /** * This method should rarely be used and only if * <a href="#cancelUnbindAll">`cancelUnbindAll`</a> has been called to * prevent element unbinding. In this case, the element's bindings will * not be automatically cleaned up and it cannot be garbage collected * by the system. If memory pressure is a concern or a * large amount of elements need to be managed in this way, `unbindAll` * can be called to deactivate the element's bindings and allow its * memory to be reclaimed. * * @method unbindAll */ unbindAll: function() { if (!this._unbound) { this.closeObservers(); this.closeNamedObservers(); this._unbound = true; } }, /** * Call in `detached` to prevent the element from unbinding when it is * detached from the dom. The element is unbound as a cleanup step that * allows its memory to be reclaimed. * If `cancelUnbindAll` is used, consider calling * <a href="#unbindAll">`unbindAll`</a> when the element is no longer * needed. This will allow its memory to be reclaimed. * * @method cancelUnbindAll */ cancelUnbindAll: function() { if (this._unbound) { log.unbind && console.warn('[%s] already unbound, cannot cancel unbindAll', this.localName); return; } log.unbind && console.log('[%s] cancelUnbindAll', this.localName); if (this._unbindAllJob) { this._unbindAllJob = this._unbindAllJob.stop(); } } }; function unbindNodeTree(node) { forNodeTree(node, _nodeUnbindAll); } function _nodeUnbindAll(node) { node.unbindAll(); } function forNodeTree(node, callback) { if (node) { callback(node); for (var child = node.firstChild; child; child = child.nextSibling) { forNodeTree(child, callback); } } } var mustachePattern = /\{\{([^{}]*)}}/; // exports scope.bindPattern = mustachePattern; scope.api.instance.mdv = mdv; })(Polymer); (function(scope) { /** * Common prototype for all Polymer Elements. * * @class polymer-base * @homepage polymer.github.io */ var base = { /** * Tags this object as the canonical Base prototype. * * @property PolymerBase * @type boolean * @default true */ PolymerBase: true, /** * Debounce signals. * * Call `job` to defer a named signal, and all subsequent matching signals, * until a wait time has elapsed with no new signal. * * debouncedClickAction: function(e) { * // processClick only when it's been 100ms since the last click * this.job('click', function() { * this.processClick; * }, 100); * } * * @method job * @param String {String} job A string identifier for the job to debounce. * @param Function {Function} callback A function that is called (with `this` context) when the wait time elapses. * @param Number {Number} wait Time in milliseconds (ms) after the last signal that must elapse before invoking `callback` * @type Handle */ job: function(job, callback, wait) { if (typeof job === 'string') { var n = '___' + job; this[n] = Polymer.job.call(this, this[n], callback, wait); } else { // TODO(sjmiles): suggest we deprecate this call signature return Polymer.job.call(this, job, callback, wait); } }, /** * Invoke a superclass method. * * Use `super()` to invoke the most recently overridden call to the * currently executing function. * * To pass arguments through, use the literal `arguments` as the parameter * to `super()`. * * nextPageAction: function(e) { * // invoke the superclass version of `nextPageAction` * this.super(arguments); * } * * To pass custom arguments, arrange them in an array. * * appendSerialNo: function(value, serial) { * // prefix the superclass serial number with our lot # before * // invoking the superlcass * return this.super([value, this.lotNo + serial]) * } * * @method super * @type Any * @param {args) An array of arguments to use when calling the superclass method, or null. */ super: Polymer.super, /** * Lifecycle method called when the element is instantiated. * * Override `created` to perform custom create-time tasks. No need to call * super-class `created` unless you are extending another Polymer element. * Created is called before the element creates `shadowRoot` or prepares * data-observation. * * @method created * @type void */ created: function() { }, /** * Lifecycle method called when the element has populated it's `shadowRoot`, * prepared data-observation, and made itself ready for API interaction. * * @method ready * @type void */ ready: function() { }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `created` * instead, which is called immediately after `createdCallback`. * * @method createdCallback */ createdCallback: function() { if (this.templateInstance && this.templateInstance.model) { console.warn('Attributes on ' + this.localName + ' were data bound ' + 'prior to Polymer upgrading the element. This may result in ' + 'incorrect binding types.'); } this.created(); this.prepareElement(); if (!this.ownerDocument.isStagingDocument) { this.makeElementReady(); } }, // system entry point, do not override prepareElement: function() { if (this._elementPrepared) { console.warn('Element already prepared', this.localName); return; } this._elementPrepared = true; // storage for shadowRoots info this.shadowRoots = {}; // install property observers this.createPropertyObserver(); this.openPropertyObserver(); // install boilerplate attributes this.copyInstanceAttributes(); // process input attributes this.takeAttributes(); // add event listeners this.addHostListeners(); }, // system entry point, do not override makeElementReady: function() { if (this._readied) { return; } this._readied = true; this.createComputedProperties(); this.parseDeclarations(this.__proto__); // NOTE: Support use of the `unresolved` attribute to help polyfill // custom elements' `:unresolved` feature. this.removeAttribute('unresolved'); // user entry point this.ready(); }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom tasks in your element, implement `attributeChanged` * instead, which is called immediately after `attributeChangedCallback`. * * @method attributeChangedCallback */ attributeChangedCallback: function(name, oldValue) { // TODO(sjmiles): adhoc filter if (name !== 'class' && name !== 'style') { this.attributeToProperty(name, this.getAttribute(name)); } if (this.attributeChanged) { this.attributeChanged.apply(this, arguments); } }, /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `attached` * instead, which is called immediately after `attachedCallback`. * * @method attachedCallback */ attachedCallback: function() { // when the element is attached, prevent it from unbinding. this.cancelUnbindAll(); // invoke user action if (this.attached) { this.attached(); } if (!this.hasBeenAttached) { this.hasBeenAttached = true; if (this.domReady) { this.async('domReady'); } } }, /** * Implement to access custom elements in dom descendants, ancestors, * or siblings. Because custom elements upgrade in document order, * elements accessed in `ready` or `attached` may not be upgraded. When * `domReady` is called, all registered custom elements are guaranteed * to have been upgraded. * * @method domReady */ /** * Low-level lifecycle method called as part of standard Custom Elements * operation. Polymer implements this method to provide basic default * functionality. For custom create-time tasks, implement `detached` * instead, which is called immediately after `detachedCallback`. * * @method detachedCallback */ detachedCallback: function() { if (!this.preventDispose) { this.asyncUnbindAll(); } // invoke user action if (this.detached) { this.detached(); } // TODO(sorvell): bc if (this.leftView) { this.leftView(); } }, /** * Walks the prototype-chain of this element and allows specific * classes a chance to process static declarations. * * In particular, each polymer-element has it's own `template`. * `parseDeclarations` is used to accumulate all element `template`s * from an inheritance chain. * * `parseDeclaration` static methods implemented in the chain are called * recursively, oldest first, with the `<polymer-element>` associated * with the current prototype passed as an argument. * * An element may override this method to customize shadow-root generation. * * @method parseDeclarations */ parseDeclarations: function(p) { if (p && p.element) { this.parseDeclarations(p.__proto__); p.parseDeclaration.call(this, p.element); } }, /** * Perform init-time actions based on static information in the * `<polymer-element>` instance argument. * * For example, the standard implementation locates the template associated * with the given `<polymer-element>` and stamps it into a shadow-root to * implement shadow inheritance. * * An element may override this method for custom behavior. * * @method parseDeclaration */ parseDeclaration: function(elementElement) { var template = this.fetchTemplate(elementElement); if (template) { var root = this.shadowFromTemplate(template); this.shadowRoots[elementElement.name] = root; } }, /** * Given a `<polymer-element>`, find an associated template (if any) to be * used for shadow-root generation. * * An element may override this method for custom behavior. * * @method fetchTemplate */ fetchTemplate: function(elementElement) { return elementElement.querySelector('template'); }, /** * Create a shadow-root in this host and stamp `template` as it's * content. * * An element may override this method for custom behavior. * * @method shadowFromTemplate */ shadowFromTemplate: function(template) { if (template) { // make a shadow root var root = this.createShadowRoot(); // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom root.appendChild(dom); // perform post-construction initialization tasks on shadow root this.shadowRootReady(root, template); // return the created shadow root return root; } }, // utility function that stamps a <template> into light-dom lightFromTemplate: function(template, refNode) { if (template) { // TODO(sorvell): mark this element as an eventController so that // event listeners on bound nodes inside it will be called on it. // Note, the expectation here is that events on all descendants // should be handled by this element. this.eventController = this; // stamp template // which includes parsing and applying MDV bindings before being // inserted (to avoid {{}} in attribute values) // e.g. to prevent <img src="images/{{icon}}"> from generating a 404. var dom = this.instanceTemplate(template); // append to shadow dom if (refNode) { this.insertBefore(dom, refNode); } else { this.appendChild(dom); } // perform post-construction initialization tasks on ahem, light root this.shadowRootReady(this); // return the created shadow root return dom; } }, shadowRootReady: function(root) { // locate nodes with id and store references to them in this.$ hash this.marshalNodeReferences(root); }, // locate nodes with id and store references to them in this.$ hash marshalNodeReferences: function(root) { // establish $ instance variable var $ = this.$ = this.$ || {}; // populate $ from nodes with ID from the LOCAL tree if (root) { var n$ = root.querySelectorAll("[id]"); for (var i=0, l=n$.length, n; (i<l) && (n=n$[i]); i++) { $[n.id] = n; }; } }, /** * Register a one-time callback when a child-list or sub-tree mutation * occurs on node. * * For persistent callbacks, call onMutation from your listener. * * @method onMutation * @param Node {Node} node Node to watch for mutations. * @param Function {Function} listener Function to call on mutation. The function is invoked as `listener.call(this, observer, mutations);` where `observer` is the MutationObserver that triggered the notification, and `mutations` is the native mutation list. */ onMutation: function(node, listener) { var observer = new MutationObserver(function(mutations) { listener.call(this, observer, mutations); observer.disconnect(); }.bind(this)); observer.observe(node, {childList: true, subtree: true}); } }; /** * @class Polymer */ /** * Returns true if the object includes <a href="#polymer-base">polymer-base</a> in it's prototype chain. * * @method isBase * @param Object {Object} object Object to test. * @type Boolean */ function isBase(object) { return object.hasOwnProperty('PolymerBase') } // name a base constructor for dev tools /** * The Polymer base-class constructor. * * @property Base * @type Function */ function PolymerBase() {}; PolymerBase.prototype = base; base.constructor = PolymerBase; // exports scope.Base = PolymerBase; scope.isBase = isBase; scope.api.instance.base = base; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SCOPE_ATTRIBUTE = 'element'; var STYLE_CONTROLLER_SCOPE = 'controller'; var styles = { STYLE_SCOPE_ATTRIBUTE: STYLE_SCOPE_ATTRIBUTE, /** * Installs external stylesheets and <style> elements with the attribute * polymer-scope='controller' into the scope of element. This is intended * to be a called during custom element construction. */ installControllerStyles: function() { // apply controller styles, but only if they are not yet applied var scope = this.findStyleScope(); if (scope && !this.scopeHasNamedStyle(scope, this.localName)) { // allow inherited controller styles var proto = getPrototypeOf(this), cssText = ''; while (proto && proto.element) { cssText += proto.element.cssTextForScope(STYLE_CONTROLLER_SCOPE); proto = getPrototypeOf(proto); } if (cssText) { this.installScopeCssText(cssText, scope); } } }, installScopeStyle: function(style, name, scope) { var scope = scope || this.findStyleScope(), name = name || ''; if (scope && !this.scopeHasNamedStyle(scope, this.localName + name)) { var cssText = ''; if (style instanceof Array) { for (var i=0, l=style.length, s; (i<l) && (s=style[i]); i++) { cssText += s.textContent + '\n\n'; } } else { cssText = style.textContent; } this.installScopeCssText(cssText, scope, name); } }, installScopeCssText: function(cssText, scope, name) { scope = scope || this.findStyleScope(); name = name || ''; if (!scope) { return; } if (hasShadowDOMPolyfill) { cssText = shimCssText(cssText, scope.host); } var style = this.element.cssTextToScopeStyle(cssText, STYLE_CONTROLLER_SCOPE); Polymer.applyStyleToScope(style, scope); // cache that this style has been applied this.styleCacheForScope(scope)[this.localName + name] = true; }, findStyleScope: function(node) { // find the shadow root that contains this element var n = node || this; while (n.parentNode) { n = n.parentNode; } return n; }, scopeHasNamedStyle: function(scope, name) { var cache = this.styleCacheForScope(scope); return cache[name]; }, styleCacheForScope: function(scope) { if (hasShadowDOMPolyfill) { var scopeName = scope.host ? scope.host.localName : scope.localName; return polyfillScopeStyleCache[scopeName] || (polyfillScopeStyleCache[scopeName] = {}); } else { return scope._scopeStyles = (scope._scopeStyles || {}); } } }; var polyfillScopeStyleCache = {}; // NOTE: use raw prototype traversal so that we ensure correct traversal // on platforms where the protoype chain is simulated via __proto__ (IE10) function getPrototypeOf(prototype) { return prototype.__proto__; } function shimCssText(cssText, host) { var name = '', is = false; if (host) { name = host.localName; is = host.hasAttribute('is'); } var selector = WebComponents.ShadowCSS.makeScopeSelector(name, is); return WebComponents.ShadowCSS.shimCssText(cssText, selector); } // exports scope.api.instance.styles = styles; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; // imperative implementation: Polymer() // specify an 'own' prototype for tag `name` function element(name, prototype) { if (typeof name !== 'string') { var script = prototype || document._currentScript; prototype = name; name = script && script.parentNode && script.parentNode.getAttribute ? script.parentNode.getAttribute('name') : ''; if (!name) { throw 'Element name could not be inferred.'; } } if (getRegisteredPrototype(name)) { throw 'Already registered (Polymer) prototype for element ' + name; } // cache the prototype registerPrototype(name, prototype); // notify the registrar waiting for 'name', if any notifyPrototype(name); } // async prototype source function waitingForPrototype(name, client) { waitPrototype[name] = client; } var waitPrototype = {}; function notifyPrototype(name) { if (waitPrototype[name]) { waitPrototype[name].registerWhenReady(); delete waitPrototype[name]; } } // utility and bookkeeping // maps tag names to prototypes, as registered with // Polymer. Prototypes associated with a tag name // using document.registerElement are available from // HTMLElement.getPrototypeForTag(). // If an element was fully registered by Polymer, then // Polymer.getRegisteredPrototype(name) === // HTMLElement.getPrototypeForTag(name) var prototypesByName = {}; function registerPrototype(name, prototype) { return prototypesByName[name] = prototype || {}; } function getRegisteredPrototype(name) { return prototypesByName[name]; } function instanceOfType(element, type) { if (typeof type !== 'string') { return false; } var proto = HTMLElement.getPrototypeForTag(type); var ctor = proto && proto.constructor; if (!ctor) { return false; } if (CustomElements.instanceof) { return CustomElements.instanceof(element, ctor); } return element instanceof ctor; } // exports scope.getRegisteredPrototype = getRegisteredPrototype; scope.waitingForPrototype = waitingForPrototype; scope.instanceOfType = instanceOfType; // namespace shenanigans so we can expose our scope on the registration // function // make window.Polymer reference `element()` window.Polymer = element; // TODO(sjmiles): find a way to do this that is less terrible // copy window.Polymer properties onto `element()` extend(Polymer, scope); // Under the HTMLImports polyfill, scripts in the main document // do not block on imports; we want to allow calls to Polymer in the main // document. WebComponents collects those calls until we can process them, which // we do here. if (WebComponents.consumeDeclarations) { WebComponents.consumeDeclarations(function(declarations) { if (declarations) { for (var i=0, l=declarations.length, d; (i<l) && (d=declarations[i]); i++) { element.apply(null, d); } } }); } })(Polymer); (function(scope) { /** * @class polymer-base */ /** * Resolve a url path to be relative to a `base` url. If unspecified, `base` * defaults to the element's ownerDocument url. Can be used to resolve * paths from element's in templates loaded in HTMLImports to be relative * to the document containing the element. Polymer automatically does this for * url attributes in element templates; however, if a url, for * example, contains a binding, then `resolvePath` can be used to ensure it is * relative to the element document. For example, in an element's template, * * <a href="{{resolvePath(path)}}">Resolved</a> * * @method resolvePath * @param {String} url Url path to resolve. * @param {String} base Optional base url against which to resolve, defaults * to the element's ownerDocument url. * returns {String} resolved url. */ var path = { resolveElementPaths: function(node) { Polymer.urlResolver.resolveDom(node); }, addResolvePathApi: function() { // let assetpath attribute modify the resolve path var assetPath = this.getAttribute('assetpath') || ''; var root = new URL(assetPath, this.ownerDocument.baseURI); this.prototype.resolvePath = function(urlPath, base) { var u = new URL(urlPath, base || root); return u.href; }; } }; // exports scope.api.declaration.path = path; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.styles; var STYLE_SCOPE_ATTRIBUTE = api.STYLE_SCOPE_ATTRIBUTE; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // magic words var STYLE_SELECTOR = 'style'; var STYLE_LOADABLE_MATCH = '@import'; var SHEET_SELECTOR = 'link[rel=stylesheet]'; var STYLE_GLOBAL_SCOPE = 'global'; var SCOPE_ATTR = 'polymer-scope'; var styles = { // returns true if resources are loading loadStyles: function(callback) { var template = this.fetchTemplate(); var content = template && this.templateContent(); if (content) { this.convertSheetsToStyles(content); var styles = this.findLoadableStyles(content); if (styles.length) { var templateUrl = template.ownerDocument.baseURI; return Polymer.styleResolver.loadStyles(styles, templateUrl, callback); } } if (callback) { callback(); } }, convertSheetsToStyles: function(root) { var s$ = root.querySelectorAll(SHEET_SELECTOR); for (var i=0, l=s$.length, s, c; (i<l) && (s=s$[i]); i++) { c = createStyleElement(importRuleForSheet(s, this.ownerDocument.baseURI), this.ownerDocument); this.copySheetAttributes(c, s); s.parentNode.replaceChild(c, s); } }, copySheetAttributes: function(style, link) { for (var i=0, a$=link.attributes, l=a$.length, a; (a=a$[i]) && i<l; i++) { if (a.name !== 'rel' && a.name !== 'href') { style.setAttribute(a.name, a.value); } } }, findLoadableStyles: function(root) { var loadables = []; if (root) { var s$ = root.querySelectorAll(STYLE_SELECTOR); for (var i=0, l=s$.length, s; (i<l) && (s=s$[i]); i++) { if (s.textContent.match(STYLE_LOADABLE_MATCH)) { loadables.push(s); } } } return loadables; }, /** * Install external stylesheets loaded in <polymer-element> elements into the * element's template. * @param elementElement The <element> element to style. */ installSheets: function() { this.cacheSheets(); this.cacheStyles(); this.installLocalSheets(); this.installGlobalStyles(); }, /** * Remove all sheets from element and store for later use. */ cacheSheets: function() { this.sheets = this.findNodes(SHEET_SELECTOR); this.sheets.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, cacheStyles: function() { this.styles = this.findNodes(STYLE_SELECTOR + '[' + SCOPE_ATTR + ']'); this.styles.forEach(function(s) { if (s.parentNode) { s.parentNode.removeChild(s); } }); }, /** * Takes external stylesheets loaded in an <element> element and moves * their content into a <style> element inside the <element>'s template. * The sheet is then removed from the <element>. This is done only so * that if the element is loaded in the main document, the sheet does * not become active. * Note, ignores sheets with the attribute 'polymer-scope'. * @param elementElement The <element> element to style. */ installLocalSheets: function () { var sheets = this.sheets.filter(function(s) { return !s.hasAttribute(SCOPE_ATTR); }); var content = this.templateContent(); if (content) { var cssText = ''; sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n'; }); if (cssText) { var style = createStyleElement(cssText, this.ownerDocument); content.insertBefore(style, content.firstChild); } } }, findNodes: function(selector, matcher) { var nodes = this.querySelectorAll(selector).array(); var content = this.templateContent(); if (content) { var templateNodes = content.querySelectorAll(selector).array(); nodes = nodes.concat(templateNodes); } return matcher ? nodes.filter(matcher) : nodes; }, /** * Promotes external stylesheets and <style> elements with the attribute * polymer-scope='global' into global scope. * This is particularly useful for defining @keyframe rules which * currently do not function in scoped or shadow style elements. * (See wkb.ug/72462) * @param elementElement The <element> element to style. */ // TODO(sorvell): remove when wkb.ug/72462 is addressed. installGlobalStyles: function() { var style = this.styleForScope(STYLE_GLOBAL_SCOPE); applyStyleToScope(style, document.head); }, cssTextForScope: function(scopeDescriptor) { var cssText = ''; // handle stylesheets var selector = '[' + SCOPE_ATTR + '=' + scopeDescriptor + ']'; var matcher = function(s) { return matchesSelector(s, selector); }; var sheets = this.sheets.filter(matcher); sheets.forEach(function(sheet) { cssText += cssTextFromSheet(sheet) + '\n\n'; }); // handle cached style elements var styles = this.styles.filter(matcher); styles.forEach(function(style) { cssText += style.textContent + '\n\n'; }); return cssText; }, styleForScope: function(scopeDescriptor) { var cssText = this.cssTextForScope(scopeDescriptor); return this.cssTextToScopeStyle(cssText, scopeDescriptor); }, cssTextToScopeStyle: function(cssText, scopeDescriptor) { if (cssText) { var style = createStyleElement(cssText); style.setAttribute(STYLE_SCOPE_ATTRIBUTE, this.getAttribute('name') + '-' + scopeDescriptor); return style; } } }; function importRuleForSheet(sheet, baseUrl) { var href = new URL(sheet.getAttribute('href'), baseUrl).href; return '@import \'' + href + '\';'; } function applyStyleToScope(style, scope) { if (style) { if (scope === document) { scope = document.head; } if (hasShadowDOMPolyfill) { scope = document.head; } // TODO(sorvell): necessary for IE // see https://connect.microsoft.com/IE/feedback/details/790212/ // cloning-a-style-element-and-adding-to-document-produces // -unexpected-result#details // var clone = style.cloneNode(true); var clone = createStyleElement(style.textContent); var attr = style.getAttribute(STYLE_SCOPE_ATTRIBUTE); if (attr) { clone.setAttribute(STYLE_SCOPE_ATTRIBUTE, attr); } // TODO(sorvell): probably too brittle; try to figure out // where to put the element. var refNode = scope.firstElementChild; if (scope === document.head) { var selector = 'style[' + STYLE_SCOPE_ATTRIBUTE + ']'; var s$ = document.head.querySelectorAll(selector); if (s$.length) { refNode = s$[s$.length-1].nextElementSibling; } } scope.insertBefore(clone, refNode); } } function createStyleElement(cssText, scope) { scope = scope || document; scope = scope.createElement ? scope : scope.ownerDocument; var style = scope.createElement('style'); style.textContent = cssText; return style; } function cssTextFromSheet(sheet) { return (sheet && sheet.__resource) || ''; } function matchesSelector(node, inSelector) { if (matches) { return matches.call(node, inSelector); } } var p = HTMLElement.prototype; var matches = p.matches || p.matchesSelector || p.webkitMatchesSelector || p.mozMatchesSelector; // exports scope.api.declaration.styles = styles; scope.applyStyleToScope = applyStyleToScope; })(Polymer); (function(scope) { // imports var log = window.WebComponents ? WebComponents.flags.log : {}; var api = scope.api.instance.events; var EVENT_PREFIX = api.EVENT_PREFIX; var mixedCaseEventTypes = {}; [ 'webkitAnimationStart', 'webkitAnimationEnd', 'webkitTransitionEnd', 'DOMFocusOut', 'DOMFocusIn', 'DOMMouseScroll' ].forEach(function(e) { mixedCaseEventTypes[e.toLowerCase()] = e; }); // polymer-element declarative api: events feature var events = { parseHostEvents: function() { // our delegates map var delegates = this.prototype.eventDelegates; // extract data from attributes into delegates this.addAttributeDelegates(delegates); }, addAttributeDelegates: function(delegates) { // for each attribute for (var i=0, a; a=this.attributes[i]; i++) { // does it have magic marker identifying it as an event delegate? if (this.hasEventPrefix(a.name)) { // if so, add the info to delegates delegates[this.removeEventPrefix(a.name)] = a.value.replace('{{', '') .replace('}}', '').trim(); } } }, // starts with 'on-' hasEventPrefix: function (n) { return n && (n[0] === 'o') && (n[1] === 'n') && (n[2] === '-'); }, removeEventPrefix: function(n) { return n.slice(prefixLength); }, findController: function(node) { while (node.parentNode) { if (node.eventController) { return node.eventController; } node = node.parentNode; } return node.host; }, getEventHandler: function(controller, target, method) { var events = this; return function(e) { if (!controller || !controller.PolymerBase) { controller = events.findController(target); } var args = [e, e.detail, e.currentTarget]; controller.dispatchMethod(controller, method, args); }; }, prepareEventBinding: function(pathString, name, node) { if (!this.hasEventPrefix(name)) return; var eventType = this.removeEventPrefix(name); eventType = mixedCaseEventTypes[eventType] || eventType; var events = this; return function(model, node, oneTime) { var handler = events.getEventHandler(undefined, node, pathString); PolymerGestures.addEventListener(node, eventType, handler); if (oneTime) return; // TODO(rafaelw): This is really pointless work. Aside from the cost // of these allocations, NodeBind is going to setAttribute back to its // current value. Fixing this would mean changing the TemplateBinding // binding delegate API. function bindingValue() { return '{{ ' + pathString + ' }}'; } return { open: bindingValue, discardChanges: bindingValue, close: function() { PolymerGestures.removeEventListener(node, eventType, handler); } }; }; } }; var prefixLength = EVENT_PREFIX.length; // exports scope.api.declaration.events = events; })(Polymer); (function(scope) { // element api var observationBlacklist = ['attribute']; var properties = { inferObservers: function(prototype) { // called before prototype.observe is chained to inherited object var observe = prototype.observe, property; for (var n in prototype) { if (n.slice(-7) === 'Changed') { property = n.slice(0, -7); if (this.canObserveProperty(property)) { if (!observe) { observe = (prototype.observe = {}); } observe[property] = observe[property] || n; } } } }, canObserveProperty: function(property) { return (observationBlacklist.indexOf(property) < 0); }, explodeObservers: function(prototype) { // called before prototype.observe is chained to inherited object var o = prototype.observe; if (o) { var exploded = {}; for (var n in o) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { exploded[ni] = o[n]; } } prototype.observe = exploded; } }, optimizePropertyMaps: function(prototype) { if (prototype.observe) { // construct name list var a = prototype._observeNames = []; for (var n in prototype.observe) { var names = n.split(' '); for (var i=0, ni; ni=names[i]; i++) { a.push(ni); } } } if (prototype.publish) { // construct name list var a = prototype._publishNames = []; for (var n in prototype.publish) { a.push(n); } } if (prototype.computed) { // construct name list var a = prototype._computedNames = []; for (var n in prototype.computed) { a.push(n); } } }, publishProperties: function(prototype, base) { // if we have any properties to publish var publish = prototype.publish; if (publish) { // transcribe `publish` entries onto own prototype this.requireProperties(publish, prototype, base); // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(publish); // construct map of lower-cased property names prototype._publishLC = this.lowerCaseMap(publish); } var computed = prototype.computed; if (computed) { // warn and remove accessor names that are broken on some browsers this.filterInvalidAccessorNames(computed); } }, // Publishing/computing a property where the name might conflict with a // browser property is not currently supported to help users of Polymer // avoid browser bugs: // // https://code.google.com/p/chromium/issues/detail?id=43394 // https://bugs.webkit.org/show_bug.cgi?id=49739 // // We can lift this restriction when those bugs are fixed. filterInvalidAccessorNames: function(propertyNames) { for (var name in propertyNames) { // Check if the name is in our blacklist. if (this.propertyNameBlacklist[name]) { console.warn('Cannot define property "' + name + '" for element "' + this.name + '" because it has the same name as an HTMLElement ' + 'property, and not all browsers support overriding that. ' + 'Consider giving it a different name.'); // Remove the invalid accessor from the list. delete propertyNames[name]; } } }, // // `name: value` entries in the `publish` object may need to generate // matching properties on the prototype. // // Values that are objects may have a `reflect` property, which // signals that the value describes property control metadata. // In metadata objects, the prototype default value (if any) // is encoded in the `value` property. // // publish: { // foo: 5, // bar: {value: true, reflect: true}, // zot: {} // } // // `reflect` metadata property controls whether changes to the property // are reflected back to the attribute (default false). // // A value is stored on the prototype unless it's === `undefined`, // in which case the base chain is checked for a value. // If the basal value is also undefined, `null` is stored on the prototype. // // The reflection data is stored on another prototype object, `reflect` // which also can be specified directly. // // reflect: { // foo: true // } // requireProperties: function(propertyInfos, prototype, base) { // per-prototype storage for reflected properties prototype.reflect = prototype.reflect || {}; // ensure a prototype value for each property // and update the property's reflect to attribute status for (var n in propertyInfos) { var value = propertyInfos[n]; // value has metadata if it has a `reflect` property if (value && value.reflect !== undefined) { prototype.reflect[n] = Boolean(value.reflect); value = value.value; } // only set a value if one is specified if (value !== undefined) { prototype[n] = value; } } }, lowerCaseMap: function(properties) { var map = {}; for (var n in properties) { map[n.toLowerCase()] = n; } return map; }, createPropertyAccessor: function(name, ignoreWrites) { var proto = this.prototype; var privateName = name + '_'; var privateObservable = name + 'Observable_'; proto[privateName] = proto[name]; Object.defineProperty(proto, name, { get: function() { var observable = this[privateObservable]; if (observable) observable.deliver(); return this[privateName]; }, set: function(value) { if (ignoreWrites) { return this[privateName]; } var observable = this[privateObservable]; if (observable) { observable.setValue(value); return; } var oldValue = this[privateName]; this[privateName] = value; this.emitPropertyChangeRecord(name, value, oldValue); return value; }, configurable: true }); }, createPropertyAccessors: function(prototype) { var n$ = prototype._computedNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { this.createPropertyAccessor(n, true); } } var n$ = prototype._publishNames; if (n$ && n$.length) { for (var i=0, l=n$.length, n, fn; (i<l) && (n=n$[i]); i++) { // If the property is computed and published, the accessor is created // above. if (!prototype.computed || !prototype.computed[n]) { this.createPropertyAccessor(n); } } } }, // This list contains some property names that people commonly want to use, // but won't work because of Chrome/Safari bugs. It isn't an exhaustive // list. In particular it doesn't contain any property names found on // subtypes of HTMLElement (e.g. name, value). Rather it attempts to catch // some common cases. propertyNameBlacklist: { children: 1, 'class': 1, id: 1, hidden: 1, style: 1, title: 1, } }; // exports scope.api.declaration.properties = properties; })(Polymer); (function(scope) { // magic words var ATTRIBUTES_ATTRIBUTE = 'attributes'; var ATTRIBUTES_REGEX = /\s|,/; // attributes api var attributes = { inheritAttributesObjects: function(prototype) { // chain our lower-cased publish map to the inherited version this.inheritObject(prototype, 'publishLC'); // chain our instance attributes map to the inherited version this.inheritObject(prototype, '_instanceAttributes'); }, publishAttributes: function(prototype, base) { // merge names from 'attributes' attribute into the 'publish' object var attributes = this.getAttribute(ATTRIBUTES_ATTRIBUTE); if (attributes) { // create a `publish` object if needed. // the `publish` object is only relevant to this prototype, the // publishing logic in `declaration/properties.js` is responsible for // managing property values on the prototype chain. // TODO(sjmiles): the `publish` object is later chained to it's // ancestor object, presumably this is only for // reflection or other non-library uses. var publish = prototype.publish || (prototype.publish = {}); // names='a b c' or names='a,b,c' var names = attributes.split(ATTRIBUTES_REGEX); // record each name for publishing for (var i=0, l=names.length, n; i<l; i++) { // remove excess ws n = names[i].trim(); // looks weird, but causes n to exist on `publish` if it does not; // a more careful test would need expensive `in` operator if (n && publish[n] === undefined) { publish[n] = undefined; } } } }, // record clonable attributes from <element> accumulateInstanceAttributes: function() { // inherit instance attributes var clonable = this.prototype._instanceAttributes; // merge attributes from element var a$ = this.attributes; for (var i=0, l=a$.length, a; (i<l) && (a=a$[i]); i++) { if (this.isInstanceAttribute(a.name)) { clonable[a.name] = a.value; } } }, isInstanceAttribute: function(name) { return !this.blackList[name] && name.slice(0,3) !== 'on-'; }, // do not clone these attributes onto instances blackList: { name: 1, 'extends': 1, constructor: 1, noscript: 1, assetpath: 1, 'cache-csstext': 1 } }; // add ATTRIBUTES_ATTRIBUTE to the blacklist attributes.blackList[ATTRIBUTES_ATTRIBUTE] = 1; // exports scope.api.declaration.attributes = attributes; })(Polymer); (function(scope) { // imports var events = scope.api.declaration.events; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; // Polymer takes a first crack at the binding to see if it's a declarative // event handler. syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; // declaration api supporting mdv var mdv = { syntax: syntax, fetchTemplate: function() { return this.querySelector('template'); }, templateContent: function() { var template = this.fetchTemplate(); return template && template.content; }, installBindingDelegate: function(template) { if (template) { template.bindingDelegate = this.syntax; } } }; // exports scope.api.declaration.mdv = mdv; })(Polymer); (function(scope) { // imports var api = scope.api; var isBase = scope.isBase; var extend = scope.extend; var hasShadowDOMPolyfill = window.ShadowDOMPolyfill; // prototype api var prototype = { register: function(name, extendeeName) { // build prototype combining extendee, Polymer base, and named api this.buildPrototype(name, extendeeName); // register our custom element with the platform this.registerPrototype(name, extendeeName); // reference constructor in a global named by 'constructor' attribute this.publishConstructor(); }, buildPrototype: function(name, extendeeName) { // get our custom prototype (before chaining) var extension = scope.getRegisteredPrototype(name); // get basal prototype var base = this.generateBasePrototype(extendeeName); // implement declarative features this.desugarBeforeChaining(extension, base); // join prototypes this.prototype = this.chainPrototypes(extension, base); // more declarative features this.desugarAfterChaining(name, extendeeName); }, desugarBeforeChaining: function(prototype, base) { // back reference declaration element // TODO(sjmiles): replace `element` with `elementElement` or `declaration` prototype.element = this; // transcribe `attributes` declarations onto own prototype's `publish` this.publishAttributes(prototype, base); // `publish` properties to the prototype and to attribute watch this.publishProperties(prototype, base); // infer observers for `observe` list based on method names this.inferObservers(prototype); // desugar compound observer syntax, e.g. 'a b c' this.explodeObservers(prototype); }, chainPrototypes: function(prototype, base) { // chain various meta-data objects to inherited versions this.inheritMetaData(prototype, base); // chain custom api to inherited var chained = this.chainObject(prototype, base); // x-platform fixup ensurePrototypeTraversal(chained); return chained; }, inheritMetaData: function(prototype, base) { // chain observe object to inherited this.inheritObject('observe', prototype, base); // chain publish object to inherited this.inheritObject('publish', prototype, base); // chain reflect object to inherited this.inheritObject('reflect', prototype, base); // chain our lower-cased publish map to the inherited version this.inheritObject('_publishLC', prototype, base); // chain our instance attributes map to the inherited version this.inheritObject('_instanceAttributes', prototype, base); // chain our event delegates map to the inherited version this.inheritObject('eventDelegates', prototype, base); }, // implement various declarative features desugarAfterChaining: function(name, extendee) { // build side-chained lists to optimize iterations this.optimizePropertyMaps(this.prototype); this.createPropertyAccessors(this.prototype); // install mdv delegate on template this.installBindingDelegate(this.fetchTemplate()); // install external stylesheets as if they are inline this.installSheets(); // adjust any paths in dom from imports this.resolveElementPaths(this); // compile list of attributes to copy to instances this.accumulateInstanceAttributes(); // parse on-* delegates declared on `this` element this.parseHostEvents(); // // install a helper method this.resolvePath to aid in // setting resource urls. e.g. // this.$.image.src = this.resolvePath('images/foo.png') this.addResolvePathApi(); // under ShadowDOMPolyfill, transforms to approximate missing CSS features if (hasShadowDOMPolyfill) { WebComponents.ShadowCSS.shimStyling(this.templateContent(), name, extendee); } // allow custom element access to the declarative context if (this.prototype.registerCallback) { this.prototype.registerCallback(this); } }, // if a named constructor is requested in element, map a reference // to the constructor to the given symbol publishConstructor: function() { var symbol = this.getAttribute('constructor'); if (symbol) { window[symbol] = this.ctor; } }, // build prototype combining extendee, Polymer base, and named api generateBasePrototype: function(extnds) { var prototype = this.findBasePrototype(extnds); if (!prototype) { // create a prototype based on tag-name extension var prototype = HTMLElement.getPrototypeForTag(extnds); // insert base api in inheritance chain (if needed) prototype = this.ensureBaseApi(prototype); // memoize this base memoizedBases[extnds] = prototype; } return prototype; }, findBasePrototype: function(name) { return memoizedBases[name]; }, // install Polymer instance api into prototype chain, as needed ensureBaseApi: function(prototype) { if (prototype.PolymerBase) { return prototype; } var extended = Object.create(prototype); // we need a unique copy of base api for each base prototype // therefore we 'extend' here instead of simply chaining api.publish(api.instance, extended); // TODO(sjmiles): sharing methods across prototype chains is // not supported by 'super' implementation which optimizes // by memoizing prototype relationships. // Probably we should have a version of 'extend' that is // share-aware: it could study the text of each function, // look for usage of 'super', and wrap those functions in // closures. // As of now, there is only one problematic method, so // we just patch it manually. // To avoid re-entrancy problems, the special super method // installed is called `mixinSuper` and the mixin method // must use this method instead of the default `super`. this.mixinMethod(extended, prototype, api.instance.mdv, 'bind'); // return buffed-up prototype return extended; }, mixinMethod: function(extended, prototype, api, name) { var $super = function(args) { return prototype[name].apply(this, args); }; extended[name] = function() { this.mixinSuper = $super; return api[name].apply(this, arguments); } }, // ensure prototype[name] inherits from a prototype.prototype[name] inheritObject: function(name, prototype, base) { // require an object var source = prototype[name] || {}; // chain inherited properties onto a new object prototype[name] = this.chainObject(source, base[name]); }, // register 'prototype' to custom element 'name', store constructor registerPrototype: function(name, extendee) { var info = { prototype: this.prototype } // native element must be specified in extends var typeExtension = this.findTypeExtension(extendee); if (typeExtension) { info.extends = typeExtension; } // register the prototype with HTMLElement for name lookup HTMLElement.register(name, this.prototype); // register the custom type this.ctor = document.registerElement(name, info); }, findTypeExtension: function(name) { if (name && name.indexOf('-') < 0) { return name; } else { var p = this.findBasePrototype(name); if (p.element) { return this.findTypeExtension(p.element.extends); } } } }; // memoize base prototypes var memoizedBases = {}; // implementation of 'chainObject' depends on support for __proto__ if (Object.__proto__) { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { object.__proto__ = inherited; } return object; } } else { prototype.chainObject = function(object, inherited) { if (object && inherited && object !== inherited) { var chained = Object.create(inherited); object = extend(chained, object); } return object; } } // On platforms that do not support __proto__ (versions of IE), the prototype // chain of a custom element is simulated via installation of __proto__. // Although custom elements manages this, we install it here so it's // available during desugaring. function ensurePrototypeTraversal(prototype) { if (!Object.__proto__) { var ancestor = Object.getPrototypeOf(prototype); prototype.__proto__ = ancestor; if (isBase(ancestor)) { ancestor.__proto__ = Object.getPrototypeOf(ancestor); } } } // exports api.declaration.prototype = prototype; })(Polymer); (function(scope) { /* Elements are added to a registration queue so that they register in the proper order at the appropriate time. We do this for a few reasons: * to enable elements to load resources (like stylesheets) asynchronously. We need to do this until the platform provides an efficient alternative. One issue is that remote @import stylesheets are re-fetched whenever stamped into a shadowRoot. * to ensure elements loaded 'at the same time' (e.g. via some set of imports) are registered as a batch. This allows elements to be enured from upgrade ordering as long as they query the dom tree 1 task after upgrade (aka domReady). This is a performance tradeoff. On the one hand, elements that could register while imports are loading are prevented from doing so. On the other, grouping upgrades into a single task means less incremental work (for example style recalcs), Also, we can ensure the document is in a known state at the single quantum of time when elements upgrade. */ var queue = { // tell the queue to wait for an element to be ready wait: function(element) { if (!element.__queue) { element.__queue = {}; elements.push(element); } }, // enqueue an element to the next spot in the queue. enqueue: function(element, check, go) { var shouldAdd = element.__queue && !element.__queue.check; if (shouldAdd) { queueForElement(element).push(element); element.__queue.check = check; element.__queue.go = go; } return (this.indexOf(element) !== 0); }, indexOf: function(element) { var i = queueForElement(element).indexOf(element); if (i >= 0 && document.contains(element)) { i += (HTMLImports.useNative || HTMLImports.ready) ? importQueue.length : 1e9; } return i; }, // tell the queue an element is ready to be registered go: function(element) { var readied = this.remove(element); if (readied) { element.__queue.flushable = true; this.addToFlushQueue(readied); this.check(); } }, remove: function(element) { var i = this.indexOf(element); if (i !== 0) { //console.warn('queue order wrong', i); return; } return queueForElement(element).shift(); }, check: function() { // next var element = this.nextElement(); if (element) { element.__queue.check.call(element); } if (this.canReady()) { this.ready(); return true; } }, nextElement: function() { return nextQueued(); }, canReady: function() { return !this.waitToReady && this.isEmpty(); }, isEmpty: function() { for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { return; } } return true; }, addToFlushQueue: function(element) { flushQueue.push(element); }, flush: function() { // prevent re-entrance if (this.flushing) { return; } this.flushing = true; var element; while (flushQueue.length) { element = flushQueue.shift(); element.__queue.go.call(element); element.__queue = null; } this.flushing = false; }, ready: function() { // TODO(sorvell): As an optimization, turn off CE polyfill upgrading // while registering. This way we avoid having to upgrade each document // piecemeal per registration and can instead register all elements // and upgrade once in a batch. Without this optimization, upgrade time // degrades significantly when SD polyfill is used. This is mainly because // querying the document tree for elements is slow under the SD polyfill. var polyfillWasReady = CustomElements.ready; CustomElements.ready = false; this.flush(); if (!CustomElements.useNative) { CustomElements.upgradeDocumentTree(document); } CustomElements.ready = polyfillWasReady; Polymer.flush(); requestAnimationFrame(this.flushReadyCallbacks); }, addReadyCallback: function(callback) { if (callback) { readyCallbacks.push(callback); } }, flushReadyCallbacks: function() { if (readyCallbacks) { var fn; while (readyCallbacks.length) { fn = readyCallbacks.shift(); fn(); } } }, /** Returns a list of elements that have had polymer-elements created but are not yet ready to register. The list is an array of element definitions. */ waitingFor: function() { var e$ = []; for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { e$.push(e); } } return e$; }, waitToReady: true }; var elements = []; var flushQueue = []; var importQueue = []; var mainQueue = []; var readyCallbacks = []; function queueForElement(element) { return document.contains(element) ? mainQueue : importQueue; } function nextQueued() { return importQueue.length ? importQueue[0] : mainQueue[0]; } function whenReady(callback) { queue.waitToReady = true; Polymer.endOfMicrotask(function() { HTMLImports.whenReady(function() { queue.addReadyCallback(callback); queue.waitToReady = false; queue.check(); }); }); } /** Forces polymer to register any pending elements. Can be used to abort waiting for elements that are partially defined. @param timeout {Integer} Optional timeout in milliseconds */ function forceReady(timeout) { if (timeout === undefined) { queue.ready(); return; } var handle = setTimeout(function() { queue.ready(); }, timeout); Polymer.whenReady(function() { clearTimeout(handle); }); } // exports scope.elements = elements; scope.waitingFor = queue.waitingFor.bind(queue); scope.forceReady = forceReady; scope.queue = queue; scope.whenReady = scope.whenPolymerReady = whenReady; })(Polymer); (function(scope) { // imports var extend = scope.extend; var api = scope.api; var queue = scope.queue; var whenReady = scope.whenReady; var getRegisteredPrototype = scope.getRegisteredPrototype; var waitingForPrototype = scope.waitingForPrototype; // declarative implementation: <polymer-element> var prototype = extend(Object.create(HTMLElement.prototype), { createdCallback: function() { if (this.getAttribute('name')) { this.init(); } }, init: function() { // fetch declared values this.name = this.getAttribute('name'); this.extends = this.getAttribute('extends'); queue.wait(this); // initiate any async resource fetches this.loadResources(); // register when all constraints are met this.registerWhenReady(); }, // TODO(sorvell): we currently queue in the order the prototypes are // registered, but we should queue in the order that polymer-elements // are registered. We are currently blocked from doing this based on // crbug.com/395686. registerWhenReady: function() { if (this.registered || this.waitingForPrototype(this.name) || this.waitingForQueue() || this.waitingForResources()) { return; } queue.go(this); }, _register: function() { //console.log('registering', this.name); // warn if extending from a custom element not registered via Polymer if (isCustomTag(this.extends) && !isRegistered(this.extends)) { console.warn('%s is attempting to extend %s, an unregistered element ' + 'or one that was not registered with Polymer.', this.name, this.extends); } this.register(this.name, this.extends); this.registered = true; }, waitingForPrototype: function(name) { if (!getRegisteredPrototype(name)) { // then wait for a prototype waitingForPrototype(name, this); // emulate script if user is not supplying one this.handleNoScript(name); // prototype not ready yet return true; } }, handleNoScript: function(name) { // if explicitly marked as 'noscript' if (this.hasAttribute('noscript') && !this.noscript) { this.noscript = true; // imperative element registration Polymer(name); } }, waitingForResources: function() { return this._needsResources; }, // NOTE: Elements must be queued in proper order for inheritance/composition // dependency resolution. Previously this was enforced for inheritance, // and by rule for composition. It's now entirely by rule. waitingForQueue: function() { return queue.enqueue(this, this.registerWhenReady, this._register); }, loadResources: function() { this._needsResources = true; this.loadStyles(function() { this._needsResources = false; this.registerWhenReady(); }.bind(this)); } }); // semi-pluggable APIs // TODO(sjmiles): should be fully pluggable (aka decoupled, currently // the various plugins are allowed to depend on each other directly) api.publish(api.declaration, prototype); // utility and bookkeeping function isRegistered(name) { return Boolean(HTMLElement.getPrototypeForTag(name)); } function isCustomTag(name) { return (name && name.indexOf('-') >= 0); } // boot tasks whenReady(function() { document.body.removeAttribute('unresolved'); document.dispatchEvent( new CustomEvent('polymer-ready', {bubbles: true}) ); }); // register polymer-element with document document.registerElement('polymer-element', {prototype: prototype}); })(Polymer); (function(scope) { /** * @class Polymer */ var whenReady = scope.whenReady; /** * Loads the set of HTMLImports contained in `node`. Notifies when all * the imports have loaded by calling the `callback` function argument. * This method can be used to lazily load imports. For example, given a * template: * * <template> * <link rel="import" href="my-import1.html"> * <link rel="import" href="my-import2.html"> * </template> * * Polymer.importElements(template.content, function() { * console.log('imports lazily loaded'); * }); * * @method importElements * @param {Node} node Node containing the HTMLImports to load. * @param {Function} callback Callback called when all imports have loaded. */ function importElements(node, callback) { if (node) { document.head.appendChild(node); whenReady(callback); } else if (callback) { callback(); } } /** * Loads an HTMLImport for each url specified in the `urls` array. * Notifies when all the imports have loaded by calling the `callback` * function argument. This method can be used to lazily load imports. * For example, * * Polymer.import(['my-import1.html', 'my-import2.html'], function() { * console.log('imports lazily loaded'); * }); * * @method import * @param {Array} urls Array of urls to load as HTMLImports. * @param {Function} callback Callback called when all imports have loaded. */ function _import(urls, callback) { if (urls && urls.length) { var frag = document.createDocumentFragment(); for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) { link = document.createElement('link'); link.rel = 'import'; link.href = url; frag.appendChild(link); } importElements(frag, callback); } else if (callback) { callback(); } } // exports scope.import = _import; scope.importElements = importElements; })(Polymer); /** * The `auto-binding` element extends the template element. It provides a quick * and easy way to do data binding without the need to setup a model. * The `auto-binding` element itself serves as the model and controller for the * elements it contains. Both data and event handlers can be bound. * * The `auto-binding` element acts just like a template that is bound to * a model. It stamps its content in the dom adjacent to itself. When the * content is stamped, the `template-bound` event is fired. * * Example: * * <template is="auto-binding"> * <div>Say something: <input value="{{value}}"></div> * <div>You said: {{value}}</div> * <button on-tap="{{buttonTap}}">Tap me!</button> * </template> * <script> * var template = document.querySelector('template'); * template.value = 'something'; * template.buttonTap = function() { * console.log('tap!'); * }; * </script> * * @module Polymer * @status stable */ (function() { var element = document.createElement('polymer-element'); element.setAttribute('name', 'auto-binding'); element.setAttribute('extends', 'template'); element.init(); Polymer('auto-binding', { createdCallback: function() { this.syntax = this.bindingDelegate = this.makeSyntax(); // delay stamping until polymer-ready so that auto-binding is not // required to load last. Polymer.whenPolymerReady(function() { this.model = this; this.setAttribute('bind', ''); // we don't bother with an explicit signal here, we could ust a MO // if necessary this.async(function() { // note: this will marshall *all* the elements in the parentNode // rather than just stamped ones. We'd need to use createInstance // to fix this or something else fancier. this.marshalNodeReferences(this.parentNode); // template stamping is asynchronous so stamping isn't complete // by polymer-ready; fire an event so users can use stamped elements this.fire('template-bound'); }); }.bind(this)); }, makeSyntax: function() { var events = Object.create(Polymer.api.declaration.events); var self = this; events.findController = function() { return self.model; }; var syntax = new PolymerExpressions(); var prepareBinding = syntax.prepareBinding; syntax.prepareBinding = function(pathString, name, node) { return events.prepareEventBinding(pathString, name, node) || prepareBinding.call(syntax, pathString, name, node); }; return syntax; } }); })();
fixtures/packaging/systemjs-builder/dev/input.js
AlmeroSteyn/react
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( React.createElement('h1', null, 'Hello World!'), document.getElementById('container') );
demo/src/components/App/App.js
moroshko/react-autosuggest
import styles from './App.less'; import React from 'react'; import Header from 'Header/Header'; import Features from 'Features/Features'; import Examples from 'Examples/Examples'; import Footer from 'Footer/Footer'; const App = () => ( <div className={styles.container}> <Header /> <Features /> <Examples /> <Footer /> </div> ); export default App;
frontend/app_v2/src/common/icons/UnfoldMore.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' /** * @summary UnfoldMore * @component * * @param {object} props * * @returns {node} jsx markup */ function UnfoldMore({ styling }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}> <path d="M0 0h24v24H0V0z" fill="none" /> <path d="M12 5.83L15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9 12 5.83zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15 12 18.17z" /> </svg> ) } // PROPTYPES const { string } = PropTypes UnfoldMore.propTypes = { styling: string, } export default UnfoldMore
dist/svg-icons/av/album.js
jacklam718/react-svg-iconx
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AvAlbum = function AvAlbum(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z' }) ); }; AvAlbum = (0, _pure2.default)(AvAlbum); AvAlbum.displayName = 'AvAlbum'; AvAlbum.muiName = 'SvgIcon'; exports.default = AvAlbum;
Contoso.Events.Web/Scripts/jquery-1.10.2.js
systemsymbiosis/Lab-20-532
/*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
files/algoliasearch.zendesk-hc/1.7.4/algoliasearch.zendesk-hc.min.js
Asaf-S/jsdelivr
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.algoliasearchZendeskHC=e()}}(function(){var e;return function t(e,n,r){function i(a,s){if(!n[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return i(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("./src/index.js"),o=r(i);t.exports=o["default"]},{"./src/index.js":641}],2:[function(e,t,n){"use strict";function r(e,t,n){return new i(e,t,n)}var i=e("./src/algoliasearch.helper"),o=e("./src/SearchParameters"),a=e("./src/SearchResults");r.version=e("./src/version.js"),r.AlgoliaSearchHelper=i,r.SearchParameters=o,r.SearchResults=a,r.url=e("./src/url"),t.exports=r},{"./src/SearchParameters":11,"./src/SearchResults":14,"./src/algoliasearch.helper":15,"./src/url":19,"./src/version.js":20}],3:[function(e,t,n){"use strict";var r=String.prototype.replace,i=/%20/g;t.exports={"default":"RFC3986",formatters:{RFC1738:function(e){return r.call(e,i,"+")},RFC3986:function(e){return e}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},{}],4:[function(e,t,n){"use strict";var r=e("./stringify"),i=e("./parse"),o=e("./formats");t.exports={formats:o,parse:i,stringify:r}},{"./formats":3,"./parse":5,"./stringify":6}],5:[function(e,t,n){"use strict";var r=e("./utils"),i=Object.prototype.hasOwnProperty,o={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:r.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},a=function(e,t){for(var n={},r=e.split(t.delimiter,t.parameterLimit===1/0?void 0:t.parameterLimit),o=0;o<r.length;++o){var a,s,u=r[o],c=u.indexOf("]=")===-1?u.indexOf("="):u.indexOf("]=")+1;c===-1?(a=t.decoder(u),s=t.strictNullHandling?null:""):(a=t.decoder(u.slice(0,c)),s=t.decoder(u.slice(c+1))),i.call(n,a)?n[a]=[].concat(n[a]).concat(s):n[a]=s}return n},s=function(e,t,n){if(!e.length)return t;var r,i=e.shift();if("[]"===i)r=[],r=r.concat(s(e,t,n));else{r=n.plainObjects?Object.create(null):{};var o="["===i.charAt(0)&&"]"===i.charAt(i.length-1)?i.slice(1,-1):i,a=parseInt(o,10);!isNaN(a)&&i!==o&&String(a)===o&&a>=0&&n.parseArrays&&a<=n.arrayLimit?(r=[],r[a]=s(e,t,n)):r[o]=s(e,t,n)}return r},u=function(e,t,n){if(e){var r=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/^([^[]*)/,a=/(\[[^[\]]*])/g,u=o.exec(r),c=[];if(u[1]){if(!n.plainObjects&&i.call(Object.prototype,u[1])&&!n.allowPrototypes)return;c.push(u[1])}for(var l=0;null!==(u=a.exec(r))&&l<n.depth;){if(l+=1,!n.plainObjects&&i.call(Object.prototype,u[1].slice(1,-1))&&!n.allowPrototypes)return;c.push(u[1])}return u&&c.push("["+r.slice(u.index)+"]"),s(c,t,n)}};t.exports=function(e,t){var n=t||{};if(null!==n.decoder&&void 0!==n.decoder&&"function"!=typeof n.decoder)throw new TypeError("Decoder has to be a function.");if(n.delimiter="string"==typeof n.delimiter||r.isRegExp(n.delimiter)?n.delimiter:o.delimiter,n.depth="number"==typeof n.depth?n.depth:o.depth,n.arrayLimit="number"==typeof n.arrayLimit?n.arrayLimit:o.arrayLimit,n.parseArrays=n.parseArrays!==!1,n.decoder="function"==typeof n.decoder?n.decoder:o.decoder,n.allowDots="boolean"==typeof n.allowDots?n.allowDots:o.allowDots,n.plainObjects="boolean"==typeof n.plainObjects?n.plainObjects:o.plainObjects,n.allowPrototypes="boolean"==typeof n.allowPrototypes?n.allowPrototypes:o.allowPrototypes,n.parameterLimit="number"==typeof n.parameterLimit?n.parameterLimit:o.parameterLimit,n.strictNullHandling="boolean"==typeof n.strictNullHandling?n.strictNullHandling:o.strictNullHandling,""===e||null===e||"undefined"==typeof e)return n.plainObjects?Object.create(null):{};for(var i="string"==typeof e?a(e,n):e,s=n.plainObjects?Object.create(null):{},c=Object.keys(i),l=0;l<c.length;++l){var f=c[l],p=u(f,i[f],n);s=r.merge(s,p,n)}return r.compact(s)}},{"./utils":7}],6:[function(e,t,n){"use strict";var r=e("./utils"),i=e("./formats"),o={brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},a=Date.prototype.toISOString,s={delimiter:"&",encode:!0,encoder:r.encode,serializeDate:function(e){return a.call(e)},skipNulls:!1,strictNullHandling:!1},u=function c(e,t,n,i,o,a,s,u,l,f,p){var d=e;if("function"==typeof s)d=s(t,d);else if(d instanceof Date)d=f(d);else if(null===d){if(i)return a?a(t):t;d=""}if("string"==typeof d||"number"==typeof d||"boolean"==typeof d||r.isBuffer(d))return a?[p(a(t))+"="+p(a(d))]:[p(t)+"="+p(String(d))];var h=[];if("undefined"==typeof d)return h;var m;if(Array.isArray(s))m=s;else{var v=Object.keys(d);m=u?v.sort(u):v}for(var y=0;y<m.length;++y){var g=m[y];o&&null===d[g]||(h=Array.isArray(d)?h.concat(c(d[g],n(t,g),n,i,o,a,s,u,l,f,p)):h.concat(c(d[g],t+(l?"."+g:"["+g+"]"),n,i,o,a,s,u,l,f,p)))}return h};t.exports=function(e,t){var n=e,r=t||{};if(null!==r.encoder&&void 0!==r.encoder&&"function"!=typeof r.encoder)throw new TypeError("Encoder has to be a function.");var a="undefined"==typeof r.delimiter?s.delimiter:r.delimiter,c="boolean"==typeof r.strictNullHandling?r.strictNullHandling:s.strictNullHandling,l="boolean"==typeof r.skipNulls?r.skipNulls:s.skipNulls,f="boolean"==typeof r.encode?r.encode:s.encode,p=f?"function"==typeof r.encoder?r.encoder:s.encoder:null,d="function"==typeof r.sort?r.sort:null,h="undefined"!=typeof r.allowDots&&r.allowDots,m="function"==typeof r.serializeDate?r.serializeDate:s.serializeDate;if("undefined"==typeof r.format)r.format=i["default"];else if(!Object.prototype.hasOwnProperty.call(i.formatters,r.format))throw new TypeError("Unknown format option provided.");var v,y,g=i.formatters[r.format];"function"==typeof r.filter?(y=r.filter,n=y("",n)):Array.isArray(r.filter)&&(y=r.filter,v=y);var b=[];if("object"!=typeof n||null===n)return"";var _;_=r.arrayFormat in o?r.arrayFormat:"indices"in r?r.indices?"indices":"repeat":"indices";var w=o[_];v||(v=Object.keys(n)),d&&v.sort(d);for(var C=0;C<v.length;++C){var j=v[C];l&&null===n[j]||(b=b.concat(u(n[j],j,w,c,l,p,y,d,h,m,g)))}return b.join(a)}},{"./formats":3,"./utils":7}],7:[function(e,t,n){"use strict";var r=Object.prototype.hasOwnProperty,i=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}();n.arrayToObject=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r<e.length;++r)"undefined"!=typeof e[r]&&(n[r]=e[r]);return n},n.merge=function(e,t,i){if(!t)return e;if("object"!=typeof t){if(Array.isArray(e))e.push(t);else{if("object"!=typeof e)return[e,t];e[t]=!0}return e}if("object"!=typeof e)return[e].concat(t);var o=e;return Array.isArray(e)&&!Array.isArray(t)&&(o=n.arrayToObject(e,i)),Array.isArray(e)&&Array.isArray(t)?(t.forEach(function(t,o){r.call(e,o)?e[o]&&"object"==typeof e[o]?e[o]=n.merge(e[o],t,i):e.push(t):e[o]=t}),e):Object.keys(t).reduce(function(e,r){var o=t[r];return Object.prototype.hasOwnProperty.call(e,r)?e[r]=n.merge(e[r],o,i):e[r]=o,e},o)},n.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},n.encode=function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),n="",r=0;r<t.length;++r){var o=t.charCodeAt(r);45===o||46===o||95===o||126===o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?n+=t.charAt(r):o<128?n+=i[o]:o<2048?n+=i[192|o>>6]+i[128|63&o]:o<55296||o>=57344?n+=i[224|o>>12]+i[128|o>>6&63]+i[128|63&o]:(r+=1,o=65536+((1023&o)<<10|1023&t.charCodeAt(r)),n+=i[240|o>>18]+i[128|o>>12&63]+i[128|o>>6&63]+i[128|63&o])}return n},n.compact=function(e,t){if("object"!=typeof e||null===e)return e;var r=t||[],i=r.indexOf(e);if(i!==-1)return r[i];if(r.push(e),Array.isArray(e)){for(var o=[],a=0;a<e.length;++a)e[a]&&"object"==typeof e[a]?o.push(n.compact(e[a],r)):"undefined"!=typeof e[a]&&o.push(e[a]);return o}var s=Object.keys(e);return s.forEach(function(t){e[t]=n.compact(e[t],r)}),e},n.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},n.isBuffer=function(e){return null!==e&&"undefined"!=typeof e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}},{}],8:[function(e,t,n){"use strict";function r(e,t){this.main=e,this.fn=t,this.lastResults=null}var i=e("util"),o=e("events");i.inherits(r,o.EventEmitter),r.prototype.detach=function(){this.removeAllListeners(),this.main.detachDerivedHelper(this)},r.prototype.getModifiedState=function(e){return this.fn(e)},t.exports=r},{events:64,util:637}],9:[function(e,t,n){"use strict";var r=e("lodash/isUndefined"),i=e("lodash/isString"),o=e("lodash/isFunction"),a=e("lodash/isEmpty"),s=e("lodash/defaults"),u=e("lodash/reduce"),c=e("lodash/filter"),l=e("lodash/omit"),f={addRefinement:function(e,t,n){if(f.isRefined(e,t,n))return e;var r=""+n,i=e[t]?e[t].concat(r):[r],o={};return o[t]=i,s({},o,e)},removeRefinement:function(e,t,n){if(r(n))return f.clearRefinement(e,t);var i=""+n;return f.clearRefinement(e,function(e,n){return t===n&&i===e})},toggleRefinement:function(e,t,n){if(r(n))throw new Error("toggleRefinement should be used with a value");return f.isRefined(e,t,n)?f.removeRefinement(e,t,n):f.addRefinement(e,t,n)},clearRefinement:function(e,t,n){return r(t)?{}:i(t)?l(e,t):o(t)?u(e,function(e,r,i){var o=c(r,function(e){return!t(e,i,n)});return a(o)||(e[i]=o),e},{}):void 0},isRefined:function(t,n,i){var o=e("lodash/indexOf"),a=!!t[n]&&t[n].length>0;if(r(i)||!a)return a;var s=""+i;return o(t[n],s)!==-1}};t.exports=f},{"lodash/defaults":402,"lodash/filter":405,"lodash/indexOf":416,"lodash/isEmpty":425,"lodash/isFunction":427,"lodash/isString":435,"lodash/isUndefined":438,"lodash/omit":449,"lodash/reduce":457}],10:[function(e,t,n){"use strict";function r(e,t){var n={},r=o(t,function(e){return e.indexOf("attribute:")!==-1}),c=a(r,function(e){return e.split(":")[1]});u(c,"*")===-1?i(c,function(t){e.isConjunctiveFacet(t)&&e.isFacetRefined(t)&&(n.facetsRefinements||(n.facetsRefinements={}),n.facetsRefinements[t]=e.facetsRefinements[t]),e.isDisjunctiveFacet(t)&&e.isDisjunctiveFacetRefined(t)&&(n.disjunctiveFacetsRefinements||(n.disjunctiveFacetsRefinements={}),n.disjunctiveFacetsRefinements[t]=e.disjunctiveFacetsRefinements[t]),e.isHierarchicalFacet(t)&&e.isHierarchicalFacetRefined(t)&&(n.hierarchicalFacetsRefinements||(n.hierarchicalFacetsRefinements={}),n.hierarchicalFacetsRefinements[t]=e.hierarchicalFacetsRefinements[t]);var r=e.getNumericRefinements(t);s(r)||(n.numericRefinements||(n.numericRefinements={}),n.numericRefinements[t]=e.numericRefinements[t])}):(s(e.numericRefinements)||(n.numericRefinements=e.numericRefinements),s(e.facetsRefinements)||(n.facetsRefinements=e.facetsRefinements),s(e.disjunctiveFacetsRefinements)||(n.disjunctiveFacetsRefinements=e.disjunctiveFacetsRefinements),s(e.hierarchicalFacetsRefinements)||(n.hierarchicalFacetsRefinements=e.hierarchicalFacetsRefinements));var l=o(t,function(e){return e.indexOf("attribute:")===-1});return i(l,function(t){n[t]=e[t]}),n}var i=e("lodash/forEach"),o=e("lodash/filter"),a=e("lodash/map"),s=e("lodash/isEmpty"),u=e("lodash/indexOf");t.exports=r},{"lodash/filter":405,"lodash/forEach":409,"lodash/indexOf":416,"lodash/isEmpty":425,"lodash/map":442}],11:[function(e,t,n){"use strict";function r(e,t){return w(e,function(e){return y(e,t)})}function i(e){var t=e?i._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.optionalTagFilters=t.optionalTagFilters,this.optionalFacetFilters=t.optionalFacetFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.minProximity=t.minProximity,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.snippetEllipsisText=t.snippetEllipsisText,this.disableExactOnAttributes=t.disableExactOnAttributes,this.enableExactOnSingleWordQuery=t.enableExactOnSingleWordQuery,this.offset=t.offset,this.length=t.length;var n=this;s(t,function(e,t){i.PARAMETERS.indexOf(t)===-1&&(n[t]=e)})}var o=e("lodash/keys"),a=e("lodash/intersection"),s=e("lodash/forOwn"),u=e("lodash/forEach"),c=e("lodash/filter"),l=e("lodash/map"),f=e("lodash/reduce"),p=e("lodash/omit"),d=e("lodash/indexOf"),h=e("lodash/isNaN"),m=e("lodash/isArray"),v=e("lodash/isEmpty"),y=e("lodash/isEqual"),g=e("lodash/isUndefined"),b=e("lodash/isString"),_=e("lodash/isFunction"),w=e("lodash/find"),C=e("lodash/trim"),j=e("lodash/defaults"),x=e("lodash/merge"),R=e("../functions/valToNumber"),P=e("./filterState"),E=e("./RefinementList");i.PARAMETERS=o(new i),i._parseNumbers=function(e){if(e instanceof i)return e;var t={},n=["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"];if(u(n,function(n){var r=e[n];if(b(r)){var i=parseFloat(r);t[n]=h(i)?r:i}}),e.numericRefinements){var r={};u(e.numericRefinements,function(e,t){r[t]={},u(e,function(e,n){var i=l(e,function(e){return m(e)?l(e,function(e){return b(e)?parseFloat(e):e}):b(e)?parseFloat(e):e});r[t][n]=i})}),t.numericRefinements=r}return x({},e,t)},i.make=function(e){var t=new i(e);return u(e.hierarchicalFacets,function(e){if(e.rootPath){var n=t.getHierarchicalRefinement(e.name);n.length>0&&0!==n[0].indexOf(e.rootPath)&&(t=t.clearRefinements(e.name)),n=t.getHierarchicalRefinement(e.name),0===n.length&&(t=t.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}}),t},i.validate=function(e,t){var n=t||{};return e.tagFilters&&n.tagRefinements&&n.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&n.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&n.numericRefinements&&!v(n.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):!v(e.numericRefinements)&&n.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},i.prototype={constructor:i,clearRefinements:function(e){var t=E.clearRefinement;return this.setQueryParameters({numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")})},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e})},addNumericRefinement:function(e,t,n){var r=R(n);if(this.isNumericRefined(e,t,r))return this;var i=x({},this.numericRefinements);return i[e]=x({},i[e]),i[e][t]?(i[e][t]=i[e][t].slice(),i[e][t].push(r)):i[e][t]=[r],this.setQueryParameters({numericRefinements:i})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,n){if(void 0!==n){var r=R(n);return this.isNumericRefined(e,t,r)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(n,i){return i===e&&n.op===t&&y(n.val,r)})}):this}return void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(n,r){return r===e&&n.op===t})}):this:this.isNumericRefined(e)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(t,n){return n===e})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){return g(e)?{}:b(e)?p(this.numericRefinements,e):_(e)?f(this.numericRefinements,function(t,n,r){var i={};return u(n,function(t,n){var o=[];u(t,function(t){var i=e({val:t,op:n},r,"numeric");i||o.push(t)}),v(o)||(i[n]=o)}),v(i)||(t[r]=i),t},{}):void 0},addFacet:function(e){return this.isConjunctiveFacet(e)?this:this.setQueryParameters({facets:this.facets.concat([e])})},addDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this:this.setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.concat([e])})},addHierarchicalFacet:function(e){if(this.isHierarchicalFacet(e.name))throw new Error("Cannot declare two hierarchical facets with the same name: `"+e.name+"`");return this.setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.concat([e])})},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({facetsRefinements:E.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({facetsExcludes:E.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({disjunctiveFacetsRefinements:E.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacet:function(e){return this.isConjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({facets:c(this.facets,function(t){return t!==e})}):this},removeDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({disjunctiveFacets:c(this.disjunctiveFacets,function(t){return t!==e})}):this},removeHierarchicalFacet:function(e){return this.isHierarchicalFacet(e)?this.clearRefinements(e).setQueryParameters({hierarchicalFacets:c(this.hierarchicalFacets,function(t){return t.name!==e})}):this},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({facetsRefinements:E.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({facetsExcludes:E.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({disjunctiveFacetsRefinements:E.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={tagRefinements:c(this.tagRefinements,function(t){return t!==e})};return this.setQueryParameters(t)},toggleRefinement:function(e,t){return this.toggleFacetRefinement(e,t)},toggleFacetRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleConjunctiveFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleConjunctiveFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsRefinements:E.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsExcludes:E.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({disjunctiveFacetsRefinements:E.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),r={},i=void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+n));return i?t.indexOf(n)===-1?r[e]=[]:r[e]=[t.slice(0,t.lastIndexOf(n))]:r[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:j({},r,this.hierarchicalFacetsRefinements)})},addHierarchicalFacetRefinement:function(e,t){if(this.isHierarchicalFacetRefined(e))throw new Error(e+" is already refined.");var n={};return n[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:j({},n,this.hierarchicalFacetsRefinements)})},removeHierarchicalFacetRefinement:function(e){if(!this.isHierarchicalFacetRefined(e))throw new Error(e+" is not refined.");var t={};return t[e]=[],this.setQueryParameters({hierarchicalFacetsRefinements:j({},t,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return d(this.disjunctiveFacets,e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return d(this.facets,e)>-1},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return E.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return E.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var n=this.getHierarchicalRefinement(e);return t?d(n,t)!==-1:n.length>0},isNumericRefined:function(e,t,n){if(g(n)&&g(t))return!!this.numericRefinements[e];var i=this.numericRefinements[e]&&!g(this.numericRefinements[e][t]);if(g(n)||!i)return i;var o=R(n),a=!g(r(this.numericRefinements[e][t],o));return i&&a},isTagRefined:function(e){return d(this.tagRefinements,e)!==-1},getRefinedDisjunctiveFacets:function(){var e=a(o(this.numericRefinements),this.disjunctiveFacets);return o(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return a(l(this.hierarchicalFacets,"name"),o(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return c(this.disjunctiveFacets,function(t){return d(e,t)===-1})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={};return s(this,function(n,r){d(e,r)===-1&&void 0!==n&&(t[r]=n)}),t},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var n={};return n[e]=t,this.setQueryParameters(n)},setQueryParameters:function(e){if(!e)return this;var t=i.validate(this,e);if(t)throw t;var n=i._parseNumbers(e);return this.mutateMe(function(t){var r=o(e);return u(r,function(e){t[e]=n[e]}),t})},filter:function(e){return P(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),t},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"!=typeof e.showParentLevel||e.showParentLevel},getHierarchicalFacetByName:function(e){return w(this.hierarchicalFacets,{name:e})},getHierarchicalFacetBreadcrumb:function(e){if(!this.isHierarchicalFacet(e))throw new Error("Cannot get the breadcrumb of an unknown hierarchical facet: `"+e+"`");var t=this.getHierarchicalRefinement(e)[0];if(!t)return[];var n=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),r=t.split(n);return l(r,C)}},t.exports=i},{"../functions/valToNumber":17,"./RefinementList":9,"./filterState":10,"lodash/defaults":402,"lodash/filter":405,"lodash/find":406,"lodash/forEach":409,"lodash/forOwn":410,"lodash/indexOf":416,"lodash/intersection":417,"lodash/isArray":420,"lodash/isEmpty":425,"lodash/isEqual":426,"lodash/isFunction":427,"lodash/isNaN":429,"lodash/isString":435,"lodash/isUndefined":438,"lodash/keys":439,"lodash/map":442,"lodash/merge":446,"lodash/omit":449,"lodash/reduce":457,"lodash/trim":468}],12:[function(e,t,n){"use strict";var r=e("lodash/invert"),i=e("lodash/keys"),o={advancedSyntax:"aS",allowTyposOnNumericTokens:"aTONT",analyticsTags:"aT",analytics:"a",aroundLatLngViaIP:"aLLVIP",aroundLatLng:"aLL",aroundPrecision:"aP",aroundRadius:"aR",attributesToHighlight:"aTH",attributesToRetrieve:"aTR",attributesToSnippet:"aTS",disjunctiveFacetsRefinements:"dFR",disjunctiveFacets:"dF",distinct:"d",facetsExcludes:"fE",facetsRefinements:"fR",facets:"f",getRankingInfo:"gRI",hierarchicalFacetsRefinements:"hFR",hierarchicalFacets:"hF",highlightPostTag:"hPoT",highlightPreTag:"hPrT",hitsPerPage:"hPP",ignorePlurals:"iP",index:"idx",insideBoundingBox:"iBB",insidePolygon:"iPg",length:"l",maxValuesPerFacet:"mVPF",minimumAroundRadius:"mAR",minProximity:"mP",minWordSizefor1Typo:"mWS1T",minWordSizefor2Typos:"mWS2T",numericFilters:"nF",numericRefinements:"nR",offset:"o",optionalWords:"oW",page:"p",queryType:"qT",query:"q",removeWordsIfNoResults:"rWINR",replaceSynonymsInHighlight:"rSIH",restrictSearchableAttributes:"rSA",synonyms:"s",tagFilters:"tF",tagRefinements:"tR",typoTolerance:"tT",optionalTagFilters:"oTF",optionalFacetFilters:"oFF",snippetEllipsisText:"sET",disableExactOnAttributes:"dEOA",enableExactOnSingleWordQuery:"eEOSWQ"},a=r(o);t.exports={ENCODED_PARAMETERS:i(a),decode:function(e){return a[e]},encode:function(e){return o[e]}}},{"lodash/invert":418,"lodash/keys":439}],13:[function(e,t,n){"use strict";function r(e){return function(t,n){var r=e.hierarchicalFacets[n],o=e.hierarchicalFacetsRefinements[r.name]&&e.hierarchicalFacetsRefinements[r.name][0]||"",a=e._getHierarchicalFacetSeparator(r),s=e._getHierarchicalRootPath(r),u=e._getHierarchicalShowParentLevel(r),l=h(e._getHierarchicalFacetSortBy(r)),f=i(l,a,s,u,o),p=t;return s&&(p=t.slice(s.split(a).length)),c(p,f,{name:e.hierarchicalFacets[n].name,count:null,isRefined:!0,path:null,data:null})}}function i(e,t,n,r,i){return function(s,c,f){var h=s;if(f>0){var m=0;for(h=s;m<f;)h=h&&p(h.data,{isRefined:!0}),m++}if(h){var v=o(h.path||n,i,t,n,r);h.data=l(u(d(c.data,v),a(t,i)),e[0],e[1])}return s}}function o(e,t,n,r,i){return function(o,a){return(!r||0===a.indexOf(r)&&r!==a)&&(!r&&a.indexOf(n)===-1||r&&a.split(n).length-r.split(n).length===1||a.indexOf(n)===-1&&t.indexOf(n)===-1||0===t.indexOf(a)||0===a.indexOf(e+n)&&(i||0===a.indexOf(t)))}}function a(e,t){return function(n,r){return{name:f(s(r.split(e))),path:r,count:n,isRefined:t===r||0===t.indexOf(r+e),data:null}}}t.exports=r;var s=e("lodash/last"),u=e("lodash/map"),c=e("lodash/reduce"),l=e("lodash/orderBy"),f=e("lodash/trim"),p=e("lodash/find"),d=e("lodash/pickBy"),h=e("../functions/formatSort"); },{"../functions/formatSort":16,"lodash/find":406,"lodash/last":441,"lodash/map":442,"lodash/orderBy":450,"lodash/pickBy":454,"lodash/reduce":457,"lodash/trim":468}],14:[function(e,t,n){"use strict";function r(e){var t={};return d(e,function(e,n){t[e]=n}),t}function i(e,t,n){t&&t[n]&&(e.stats=t[n])}function o(e,t){return b(e,function(e){return _(e.attributes,t)})}function a(e,t){var n=t[0];this.query=n.query,this.parsedQuery=n.parsedQuery,this.hits=n.hits,this.index=n.index,this.hitsPerPage=n.hitsPerPage,this.nbHits=n.nbHits,this.nbPages=n.nbPages,this.page=n.page,this.processingTimeMS=g(t,"processingTimeMS"),this.aroundLatLng=n.aroundLatLng,this.automaticRadius=n.automaticRadius,this.serverUsed=n.serverUsed,this.timeoutCounts=n.timeoutCounts,this.timeoutHits=n.timeoutHits,this.disjunctiveFacets=[],this.hierarchicalFacets=w(e.hierarchicalFacets,function(){return[]}),this.facets=[];var a=e.getRefinedDisjunctiveFacets(),s=r(e.facets),u=r(e.disjunctiveFacets),c=1,l=this;d(n.facets,function(t,r){var a=o(e.hierarchicalFacets,r);if(a){var c=a.attributes.indexOf(r),f=v(e.hierarchicalFacets,{name:a.name});l.hierarchicalFacets[f][c]={attribute:r,data:t,exhaustive:n.exhaustiveFacetsCount}}else{var p,d=m(e.disjunctiveFacets,r)!==-1,h=m(e.facets,r)!==-1;d&&(p=u[r],l.disjunctiveFacets[p]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},i(l.disjunctiveFacets[p],n.facets_stats,r)),h&&(p=s[r],l.facets[p]={name:r,data:t,exhaustive:n.exhaustiveFacetsCount},i(l.facets[p],n.facets_stats,r))}}),this.hierarchicalFacets=h(this.hierarchicalFacets),d(a,function(r){var o=t[c],a=e.getHierarchicalFacetByName(r);d(o.facets,function(t,r){var s;if(a){s=v(e.hierarchicalFacets,{name:a.name});var c=v(l.hierarchicalFacets[s],{attribute:r});if(c===-1)return;l.hierarchicalFacets[s][c].data=x({},l.hierarchicalFacets[s][c].data,t)}else{s=u[r];var f=n.facets&&n.facets[r]||{};l.disjunctiveFacets[s]={name:r,data:j({},t,f),exhaustive:o.exhaustiveFacetsCount},i(l.disjunctiveFacets[s],o.facets_stats,r),e.disjunctiveFacetsRefinements[r]&&d(e.disjunctiveFacetsRefinements[r],function(t){!l.disjunctiveFacets[s].data[t]&&m(e.disjunctiveFacetsRefinements[r],t)>-1&&(l.disjunctiveFacets[s].data[t]=0)})}}),c++}),d(e.getRefinedHierarchicalFacets(),function(n){var r=e.getHierarchicalFacetByName(n),i=e._getHierarchicalFacetSeparator(r),o=e.getHierarchicalRefinement(n);if(!(0===o.length||o[0].split(i).length<2)){var a=t[c];d(a.facets,function(t,n){var a=v(e.hierarchicalFacets,{name:r.name}),s=v(l.hierarchicalFacets[a],{attribute:n});if(s!==-1){var u={};if(o.length>0){var c=o[0].split(i)[0];u[c]=l.hierarchicalFacets[a][s].data[c]}l.hierarchicalFacets[a][s].data=j(u,t,l.hierarchicalFacets[a][s].data)}}),c++}}),d(e.facetsExcludes,function(e,t){var r=s[t];l.facets[r]={name:t,data:n.facets[t],exhaustive:n.exhaustiveFacetsCount},d(e,function(e){l.facets[r]=l.facets[r]||{name:t},l.facets[r].data=l.facets[r].data||{},l.facets[r].data[e]=0})}),this.hierarchicalFacets=w(this.hierarchicalFacets,T(e)),this.facets=h(this.facets),this.disjunctiveFacets=h(this.disjunctiveFacets),this._state=e}function s(e,t){var n={name:t};if(e._state.isConjunctiveFacet(t)){var r=b(e.facets,n);return r?w(r.data,function(n,r){return{name:r,count:n,isRefined:e._state.isFacetRefined(t,r),isExcluded:e._state.isExcludeRefined(t,r)}}):[]}if(e._state.isDisjunctiveFacet(t)){var i=b(e.disjunctiveFacets,n);return i?w(i.data,function(n,r){return{name:r,count:n,isRefined:e._state.isDisjunctiveFacetRefined(t,r)}}):[]}if(e._state.isHierarchicalFacet(t))return b(e.hierarchicalFacets,n)}function u(e,t){if(!t.data||0===t.data.length)return t;var n=w(t.data,E(u,e)),r=e(n),i=x({},t,{data:r});return i}function c(e,t){return t.sort(e)}function l(e,t){var n=b(e,{name:t});return n&&n.stats}function f(e,t,n,r,i){var o=b(i,{name:n}),a=y(o,"data["+r+"]"),s=y(o,"exhaustive");return{type:t,attributeName:n,name:r,count:a||0,exhaustive:s||!1}}function p(e,t,n,r){for(var i=b(r,{name:t}),o=e.getHierarchicalFacetByName(t),a=n.split(o.separator),s=a[a.length-1],u=0;void 0!==i&&u<a.length;++u)i=b(i.data,{name:a[u]});var c=y(i,"count"),l=y(i,"exhaustive");return{type:"hierarchical",attributeName:t,name:s,count:c||0,exhaustive:l||!1}}var d=e("lodash/forEach"),h=e("lodash/compact"),m=e("lodash/indexOf"),v=e("lodash/findIndex"),y=e("lodash/get"),g=e("lodash/sumBy"),b=e("lodash/find"),_=e("lodash/includes"),w=e("lodash/map"),C=e("lodash/orderBy"),j=e("lodash/defaults"),x=e("lodash/merge"),R=e("lodash/isArray"),P=e("lodash/isFunction"),E=e("lodash/partial"),O=e("lodash/partialRight"),S=e("../functions/formatSort"),T=e("./generate-hierarchical-tree");a.prototype.getFacetByName=function(e){var t={name:e};return b(this.facets,t)||b(this.disjunctiveFacets,t)||b(this.hierarchicalFacets,t)},a.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],a.prototype.getFacetValues=function(e,t){var n=s(this,e);if(!n)throw new Error(e+" is not a retrieved facet.");var r=j({},t,{sortBy:a.DEFAULT_SORT});if(R(r.sortBy)){var i=S(r.sortBy,a.DEFAULT_SORT);return R(n)?C(n,i[0],i[1]):u(O(C,i[0],i[1]),n)}if(P(r.sortBy))return R(n)?n.sort(r.sortBy):u(E(c,r.sortBy),n);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},a.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return l(this.facets,e);if(this._state.isDisjunctiveFacet(e))return l(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},a.prototype.getRefinements=function(){var e=this._state,t=this,n=[];return d(e.facetsRefinements,function(r,i){d(r,function(r){n.push(f(e,"facet",i,r,t.facets))})}),d(e.facetsExcludes,function(r,i){d(r,function(r){n.push(f(e,"exclude",i,r,t.facets))})}),d(e.disjunctiveFacetsRefinements,function(r,i){d(r,function(r){n.push(f(e,"disjunctive",i,r,t.disjunctiveFacets))})}),d(e.hierarchicalFacetsRefinements,function(r,i){d(r,function(r){n.push(p(e,i,r,t.hierarchicalFacets))})}),d(e.numericRefinements,function(e,t){d(e,function(e,r){d(e,function(e){n.push({type:"numeric",attributeName:t,name:e,numericValue:e,operator:r})})})}),d(e.tagRefinements,function(e){n.push({type:"tag",attributeName:"_tags",name:e})}),n},t.exports=a},{"../functions/formatSort":16,"./generate-hierarchical-tree":13,"lodash/compact":399,"lodash/defaults":402,"lodash/find":406,"lodash/findIndex":407,"lodash/forEach":409,"lodash/get":411,"lodash/includes":415,"lodash/indexOf":416,"lodash/isArray":420,"lodash/isFunction":427,"lodash/map":442,"lodash/merge":446,"lodash/orderBy":450,"lodash/partial":451,"lodash/partialRight":452,"lodash/sumBy":462}],15:[function(e,t,n){"use strict";function r(e,t,n){e.addAlgoliaAgent?a(e)||e.addAlgoliaAgent("JS Helper "+g):console.log("Please upgrade to the newest version of the JS Client."),this.setClient(e);var r=n||{};r.index=t,this.state=s.make(r),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1,this.derivedHelpers=[]}function i(e){if(e<0)throw new Error("Page requested below 0.");return this.state=this.state.setPage(e),this._change(),this}function o(){return this.state.page}function a(e){var t=e._ua;return!!t&&t.indexOf("JS Helper")!==-1}var s=e("./SearchParameters"),u=e("./SearchResults"),c=e("./DerivedHelper"),l=e("./requestBuilder"),f=e("util"),p=e("events"),d=e("lodash/flatten"),h=e("lodash/forEach"),m=e("lodash/isEmpty"),v=e("lodash/map"),y=e("./url"),g=e("./version");f.inherits(r,p.EventEmitter),r.prototype.search=function(){return this._search(),this},r.prototype.getQuery=function(){var e=this.state;return l._getHitsSearchParams(e)},r.prototype.searchOnce=function(e,t){var n=e?this.state.setQueryParameters(e):this.state,r=l._getQueries(n.index,n);return t?this.client.search(r,function(e,r){e?t(e,null,n):t(e,new u(n,r.results),n)}):this.client.search(r).then(function(e){return{content:new u(n,e.results),state:n,_originalResponse:e}})},r.prototype.searchForFacetValues=function(e,t){var n=this.state,r=this.client.initIndex(this.state.index),i=n.isDisjunctiveFacet(e),o=l.getSearchForFacetQuery(e,t,this.state);return r.searchForFacetValues(o).then(function(t){return t.facetHits=h(t.facetHits,function(t){t.isRefined=i?n.isDisjunctiveFacetRefined(e,t.value):n.isFacetRefined(e,t.value)}),t})},r.prototype.setQuery=function(e){return this.state=this.state.setPage(0).setQuery(e),this._change(),this},r.prototype.clearRefinements=function(e){return this.state=this.state.setPage(0).clearRefinements(e),this._change(),this},r.prototype.clearTags=function(){return this.state=this.state.setPage(0).clearTags(),this._change(),this},r.prototype.addDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.setPage(0).addDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.addHierarchicalFacetRefinement=function(e,t){return this.state=this.state.setPage(0).addHierarchicalFacetRefinement(e,t),this._change(),this},r.prototype.addNumericRefinement=function(e,t,n){return this.state=this.state.setPage(0).addNumericRefinement(e,t,n),this._change(),this},r.prototype.addFacetRefinement=function(e,t){return this.state=this.state.setPage(0).addFacetRefinement(e,t),this._change(),this},r.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},r.prototype.addFacetExclusion=function(e,t){return this.state=this.state.setPage(0).addExcludeRefinement(e,t),this._change(),this},r.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},r.prototype.addTag=function(e){return this.state=this.state.setPage(0).addTagRefinement(e),this._change(),this},r.prototype.removeNumericRefinement=function(e,t,n){return this.state=this.state.setPage(0).removeNumericRefinement(e,t,n),this._change(),this},r.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this.state=this.state.setPage(0).removeDisjunctiveFacetRefinement(e,t),this._change(),this},r.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},r.prototype.removeHierarchicalFacetRefinement=function(e){return this.state=this.state.setPage(0).removeHierarchicalFacetRefinement(e),this._change(),this},r.prototype.removeFacetRefinement=function(e,t){return this.state=this.state.setPage(0).removeFacetRefinement(e,t),this._change(),this},r.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},r.prototype.removeFacetExclusion=function(e,t){return this.state=this.state.setPage(0).removeExcludeRefinement(e,t),this._change(),this},r.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},r.prototype.removeTag=function(e){return this.state=this.state.setPage(0).removeTagRefinement(e),this._change(),this},r.prototype.toggleFacetExclusion=function(e,t){return this.state=this.state.setPage(0).toggleExcludeFacetRefinement(e,t),this._change(),this},r.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},r.prototype.toggleRefinement=function(e,t){return this.toggleFacetRefinement(e,t)},r.prototype.toggleFacetRefinement=function(e,t){return this.state=this.state.setPage(0).toggleFacetRefinement(e,t),this._change(),this},r.prototype.toggleRefine=function(){return this.toggleFacetRefinement.apply(this,arguments)},r.prototype.toggleTag=function(e){return this.state=this.state.setPage(0).toggleTagRefinement(e),this._change(),this},r.prototype.nextPage=function(){return this.setPage(this.state.page+1)},r.prototype.previousPage=function(){return this.setPage(this.state.page-1)},r.prototype.setCurrentPage=i,r.prototype.setPage=i,r.prototype.setIndex=function(e){return this.state=this.state.setPage(0).setIndex(e),this._change(),this},r.prototype.setQueryParameter=function(e,t){var n=this.state.setPage(0).setQueryParameter(e,t);return this.state===n?this:(this.state=n,this._change(),this)},r.prototype.setState=function(e){return this.state=new s(e),this._change(),this},r.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},r.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],n=this.getState(t);return y.getQueryStringFromState(n,e)},r.getConfigurationFromQueryString=y.getStateFromQueryString,r.getForeignConfigurationInQueryString=y.getUnrecognizedParametersInQueryString,r.prototype.setStateFromQueryString=function(e,t){var n=t&&t.triggerChange||!1,r=y.getStateFromQueryString(e,t),i=this.state.setQueryParameters(r);n?this.setState(i):this.overrideStateWithoutTriggeringChangeEvent(i)},r.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new s(e),this},r.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},r.prototype.hasRefinements=function(e){return!m(this.state.getNumericRefinements(e))||(this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):!!this.state.isHierarchicalFacet(e)&&this.state.isHierarchicalFacetRefined(e))},r.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},r.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},r.prototype.hasTag=function(e){return this.state.isTagRefined(e)},r.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},r.prototype.getIndex=function(){return this.state.index},r.prototype.getCurrentPage=o,r.prototype.getPage=o,r.prototype.getTags=function(){return this.state.tagRefinements},r.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},r.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e)){var n=this.state.getConjunctiveRefinements(e);h(n,function(e){t.push({value:e,type:"conjunctive"})});var r=this.state.getExcludeRefinements(e);h(r,function(e){t.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var i=this.state.getDisjunctiveRefinements(e);h(i,function(e){t.push({value:e,type:"disjunctive"})})}var o=this.state.getNumericRefinements(e);return h(o,function(e,n){t.push({value:e,operator:n,type:"numeric"})}),t},r.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},r.prototype.getHierarchicalFacetBreadcrumb=function(e){return this.state.getHierarchicalFacetBreadcrumb(e)},r.prototype._search=function(){var e=this.state,t=l._getQueries(e.index,e),n=[{state:e,queriesCount:t.length,helper:this}];this.emit("search",e,this.lastResults);var r=v(this.derivedHelpers,function(t){var r=t.getModifiedState(e),i=l._getQueries(r.index,r);return n.push({state:r,queriesCount:i.length,helper:t}),t.emit("search",r,t.lastResults),i}),i=t.concat(d(r)),o=this._queryId++;this.client.search(i,this._dispatchAlgoliaResponse.bind(this,n,o))},r.prototype._dispatchAlgoliaResponse=function(e,t,n,r){if(!(t<this._lastQueryIdReceived)){if(this._lastQueryIdReceived=t,n)return void this.emit("error",n);var i=r.results;h(e,function(e){var t=e.state,n=e.queriesCount,r=e.helper,o=i.splice(0,n),a=r.lastResults=new u(t,o);r.emit("result",a,t)})}},r.prototype.containsRefinement=function(e,t,n,r){return e||0!==t.length||0!==n.length||0!==r.length},r.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&this.state.disjunctiveRefinements[e].length>0},r.prototype._change=function(){this.emit("change",this.state,this.lastResults)},r.prototype.clearCache=function(){return this.client.clearCache(),this},r.prototype.setClient=function(e){return this.client===e?this:(e.addAlgoliaAgent&&!a(e)&&e.addAlgoliaAgent("JS Helper "+g),this.client=e,this)},r.prototype.getClient=function(){return this.client},r.prototype.derive=function(e){var t=new c(this,e);return this.derivedHelpers.push(t),t},r.prototype.detachDerivedHelper=function(e){var t=this.derivedHelpers.indexOf(e);if(t===-1)throw new Error("Derived helper already detached");this.derivedHelpers.splice(t,1)},t.exports=r},{"./DerivedHelper":8,"./SearchParameters":11,"./SearchResults":14,"./requestBuilder":18,"./url":19,"./version":20,events:64,"lodash/flatten":408,"lodash/forEach":409,"lodash/isEmpty":425,"lodash/map":442,util:637}],16:[function(e,t,n){"use strict";var r=e("lodash/reduce"),i=e("lodash/find"),o=e("lodash/startsWith");t.exports=function(e,t){return r(e,function(e,n){var r=n.split(":");if(t&&1===r.length){var a=i(t,function(e){return o(e,n[0])});a&&(r=a.split(":"))}return e[0].push(r[0]),e[1].push(r[1]),e},[[],[]])}},{"lodash/find":406,"lodash/reduce":457,"lodash/startsWith":459}],17:[function(e,t,n){"use strict";function r(e){if(a(e))return e;if(s(e))return parseFloat(e);if(o(e))return i(e,r);throw new Error("The value should be a number, a parseable string or an array of those.")}var i=e("lodash/map"),o=e("lodash/isArray"),a=e("lodash/isNumber"),s=e("lodash/isString");t.exports=r},{"lodash/isArray":420,"lodash/isNumber":431,"lodash/isString":435,"lodash/map":442}],18:[function(e,t,n){"use strict";var r=e("lodash/forEach"),i=e("lodash/map"),o=e("lodash/reduce"),a=e("lodash/merge"),s=e("lodash/isArray"),u={_getQueries:function(e,t){var n=[];return n.push({indexName:e,params:u._getHitsSearchParams(t)}),r(t.getRefinedDisjunctiveFacets(),function(r){n.push({indexName:e,params:u._getDisjunctiveFacetSearchParams(t,r)})}),r(t.getRefinedHierarchicalFacets(),function(r){var i=t.getHierarchicalFacetByName(r),o=t.getHierarchicalRefinement(r),a=t._getHierarchicalFacetSeparator(i);o.length>0&&o[0].split(a).length>1&&n.push({indexName:e,params:u._getDisjunctiveFacetSearchParams(t,r,!0)})}),n},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(u._getHitsHierarchicalFacetsAttributes(e)),n=u._getFacetFilters(e),r=u._getNumericFilters(e),i=u._getTagFilters(e),o={facets:t,tagFilters:i};return n.length>0&&(o.facetFilters=n),r.length>0&&(o.numericFilters=r),a(e.getQueryParams(),o)},_getDisjunctiveFacetSearchParams:function(e,t,n){var r=u._getFacetFilters(e,t,n),i=u._getNumericFilters(e,t),o=u._getTagFilters(e),s={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:o},c=e.getHierarchicalFacetByName(t);return c?s.facets=u._getDisjunctiveHierarchicalFacetAttribute(e,c,n):s.facets=t,i.length>0&&(s.numericFilters=i),r.length>0&&(s.facetFilters=r),a(e.getQueryParams(),s)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var n=[];return r(e.numericRefinements,function(e,o){r(e,function(e,a){t!==o&&r(e,function(e){if(s(e)){var t=i(e,function(e){return o+a+e});n.push(t)}else n.push(o+a+e)})})}),n},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,n){var i=[];return r(e.facetsRefinements,function(e,t){r(e,function(e){i.push(t+":"+e)})}),r(e.facetsExcludes,function(e,t){r(e,function(e){i.push(t+":-"+e)})}),r(e.disjunctiveFacetsRefinements,function(e,n){if(n!==t&&e&&0!==e.length){var o=[];r(e,function(e){o.push(n+":"+e)}),i.push(o)}}),r(e.hierarchicalFacetsRefinements,function(r,o){var a=r[0];if(void 0!==a){var s,u,c=e.getHierarchicalFacetByName(o),l=e._getHierarchicalFacetSeparator(c),f=e._getHierarchicalRootPath(c);if(t===o){if(a.indexOf(l)===-1||!f&&n===!0||f&&f.split(l).length===a.split(l).length)return;f?(u=f.split(l).length-1,a=f):(u=a.split(l).length-2,a=a.slice(0,a.lastIndexOf(l))),s=c.attributes[u]}else u=a.split(l).length-1,s=c.attributes[u];s&&i.push([s+":"+a])}}),i},_getHitsHierarchicalFacetsAttributes:function(e){var t=[];return o(e.hierarchicalFacets,function(t,n){var r=e.getHierarchicalRefinement(n.name)[0];if(!r)return t.push(n.attributes[0]),t;var i=e._getHierarchicalFacetSeparator(n),o=r.split(i).length,a=n.attributes.slice(0,o+1);return t.concat(a)},t)},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,n){var r=e._getHierarchicalFacetSeparator(t);if(n===!0){var i=e._getHierarchicalRootPath(t),o=0;return i&&(o=i.split(r).length),[t.attributes[o]]}var a=e.getHierarchicalRefinement(t.name)[0]||"",s=a.split(r).length-1;return t.attributes.slice(0,s+1)},getSearchForFacetQuery:function(e,t,n){var r=n.isDisjunctiveFacet(e)?n.clearRefinements(e):n,i=a(u._getHitsSearchParams(r),{facetQuery:t,facetName:e});return i}};t.exports=u},{"lodash/forEach":409,"lodash/isArray":420,"lodash/map":442,"lodash/merge":446,"lodash/reduce":457}],19:[function(e,t,n){"use strict";function r(e){return m(e)?d(e,r):v(e)?f(e,r):h(e)?g(e):e}function i(e,t,n,r){if(null!==e&&(n=n.replace(e,""),r=r.replace(e,"")),n=t[n]||n,r=t[r]||r,_.indexOf(n)!==-1||_.indexOf(r)!==-1){if("q"===n)return-1;if("q"===r)return 1;var i=b.indexOf(n)!==-1,o=b.indexOf(r)!==-1;if(i&&!o)return 1;if(o&&!i)return-1}return n.localeCompare(r)}var o=e("./SearchParameters/shortener"),a=e("./SearchParameters"),s=e("qs"),u=e("lodash/bind"),c=e("lodash/forEach"),l=e("lodash/pick"),f=e("lodash/map"),p=e("lodash/mapKeys"),d=e("lodash/mapValues"),h=e("lodash/isString"),m=e("lodash/isPlainObject"),v=e("lodash/isArray"),y=e("lodash/invert"),g=e("qs/lib/utils").encode,b=["dFR","fR","nR","hFR","tR"],_=o.ENCODED_PARAMETERS;n.getStateFromQueryString=function(e,t){var n=t&&t.prefix||"",r=t&&t.mapping||{},i=y(r),u=s.parse(e),c=new RegExp("^"+n),f=p(u,function(e,t){var r=n&&c.test(t),a=r?t.replace(c,""):t,s=o.decode(i[a]||a);return s||a}),d=a._parseNumbers(f);return l(d,a.PARAMETERS)},n.getUnrecognizedParametersInQueryString=function(e,t){var n=t&&t.prefix,r=t&&t.mapping||{},i=y(r),a={},u=s.parse(e);if(n){var l=new RegExp("^"+n);c(u,function(e,t){l.test(t)||(a[t]=e)})}else c(u,function(e,t){o.decode(i[t]||t)||(a[t]=e)});return a},n.getQueryStringFromState=function(e,t){var n=t&&t.moreAttributes,a=t&&t.prefix||"",c=t&&t.mapping||{},l=t&&t.safe||!1,f=y(c),d=l?e:r(e),h=p(d,function(e,t){var n=o.encode(t);return a+(c[n]||n)}),m=""===a?null:new RegExp("^"+a),v=u(i,null,m,f);if(n){var g=s.stringify(h,{encode:l,sort:v}),b=s.stringify(n,{encode:l});return g?g+"&"+b:b}return s.stringify(h,{encode:l,sort:v})}},{"./SearchParameters":11,"./SearchParameters/shortener":12,"lodash/bind":396,"lodash/forEach":409,"lodash/invert":418,"lodash/isArray":420,"lodash/isPlainObject":434,"lodash/isString":435,"lodash/map":442,"lodash/mapKeys":443,"lodash/mapValues":444,"lodash/pick":453,qs:4,"qs/lib/utils":7}],20:[function(e,t,n){"use strict";t.exports="2.18.1"},{}],21:[function(e,t,n){function r(){u.apply(this,arguments)}function i(){var e="Not implemented in this environment.\nIf you feel this is a mistake, write to [email protected]";throw new l.AlgoliaSearchError(e)}t.exports=r;var o=e("./Index.js"),a=e("./deprecate.js"),s=e("./deprecatedMessage.js"),u=e("./AlgoliaSearchCore.js"),c=e("inherits"),l=e("./errors");c(r,u),r.prototype.deleteIndex=function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(e),hostType:"write",callback:t})},r.prototype.moveIndex=function(e,t,n){var r={operation:"move",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},r.prototype.copyIndex=function(e,t,n){var r={operation:"copy",destination:t};return this._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(e)+"/operation",body:r,hostType:"write",callback:n})},r.prototype.getLogs=function(t,n,r){var i=e("./clone.js"),o={};return"object"==typeof t?(o=i(t),r=n):0===arguments.length||"function"==typeof t?r=t:1===arguments.length||"function"==typeof n?(r=n,o.offset=t):(o.offset=t,o.length=n),void 0===o.offset&&(o.offset=0),void 0===o.length&&(o.length=10),this._jsonRequest({method:"GET",url:"/1/logs?"+this._getSearchParams(o,""),hostType:"read",callback:r})},r.prototype.listIndexes=function(e,t){var n="";return void 0===e||"function"==typeof e?t=e:n="?page="+e,this._jsonRequest({method:"GET",url:"/1/indexes"+n,hostType:"read",callback:t})},r.prototype.initIndex=function(e){return new o(this,e)},r.prototype.listUserKeys=function(e){return this._jsonRequest({method:"GET",url:"/1/keys",hostType:"read",callback:e})},r.prototype.getUserKeyACL=function(e,t){return this._jsonRequest({method:"GET",url:"/1/keys/"+e,hostType:"read",callback:t})},r.prototype.deleteUserKey=function(e,t){return this._jsonRequest({method:"DELETE",url:"/1/keys/"+e,hostType:"write",callback:t})},r.prototype.addUserKey=function(t,n,r){var i=e("isarray"),o="Usage: client.addUserKey(arrayOfAcls[, params, callback])";if(!i(t))throw new Error(o);1!==arguments.length&&"function"!=typeof n||(r=n,n=null);var a={acl:t};return n&&(a.validity=n.validity,a.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,a.maxHitsPerQuery=n.maxHitsPerQuery,a.indexes=n.indexes,a.description=n.description,n.queryParameters&&(a.queryParameters=this._getSearchParams(n.queryParameters,"")),a.referers=n.referers),this._jsonRequest({method:"POST",url:"/1/keys",body:a,hostType:"write",callback:r})},r.prototype.addUserKeyWithValidity=a(function(e,t,n){return this.addUserKey(e,t,n)},s("client.addUserKeyWithValidity()","client.addUserKey()")),r.prototype.updateUserKey=function(t,n,r,i){var o=e("isarray"),a="Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])";if(!o(n))throw new Error(a);2!==arguments.length&&"function"!=typeof r||(i=r,r=null);var s={acl:n};return r&&(s.validity=r.validity,s.maxQueriesPerIPPerHour=r.maxQueriesPerIPPerHour,s.maxHitsPerQuery=r.maxHitsPerQuery,s.indexes=r.indexes,s.description=r.description,r.queryParameters&&(s.queryParameters=this._getSearchParams(r.queryParameters,"")),s.referers=r.referers),this._jsonRequest({method:"PUT",url:"/1/keys/"+t,body:s,hostType:"write",callback:i})},r.prototype.startQueriesBatch=a(function(){this._batch=[]},s("client.startQueriesBatch()","client.search()")),r.prototype.addQueryInBatch=a(function(e,t,n){this._batch.push({indexName:e,query:t,params:n})},s("client.addQueryInBatch()","client.search()")),r.prototype.sendQueriesBatch=a(function(e){return this.search(this._batch,e)},s("client.sendQueriesBatch()","client.search()")),r.prototype.batch=function(t,n){var r=e("isarray"),i="Usage: client.batch(operations[, callback])";if(!r(t))throw new Error(i);return this._jsonRequest({method:"POST",url:"/1/indexes/*/batch",body:{requests:t},hostType:"write",callback:n})},r.prototype.destroy=i,r.prototype.enableRateLimitForward=i,r.prototype.disableRateLimitForward=i,r.prototype.useSecuredAPIKey=i,r.prototype.disableSecuredAPIKey=i,r.prototype.generateSecuredApiKey=i},{"./AlgoliaSearchCore.js":22,"./Index.js":23,"./clone.js":33,"./deprecate.js":34,"./deprecatedMessage.js":35,"./errors":36,inherits:110,isarray:176}],22:[function(e,t,n){(function(n){function r(t,n,r){var o=e("debug")("algoliasearch"),a=e("./clone.js"),s=e("isarray"),c=e("./map.js"),l="Usage: algoliasearch(applicationID, apiKey, opts)";if(r._allowEmptyCredentials!==!0&&!t)throw new u.AlgoliaSearchError("Please provide an application ID. "+l);if(r._allowEmptyCredentials!==!0&&!n)throw new u.AlgoliaSearchError("Please provide an API key. "+l);this.applicationID=t,this.apiKey=n,this.hosts={read:[],write:[]},r=r||{};var f=r.protocol||"https:";if(this._timeouts=r.timeouts||{connect:1e3,read:2e3,write:3e4},r.timeout&&(this._timeouts.connect=this._timeouts.read=this._timeouts.write=r.timeout),/:$/.test(f)||(f+=":"),"http:"!==r.protocol&&"https:"!==r.protocol)throw new u.AlgoliaSearchError("protocol must be `http:` or `https:` (was `"+r.protocol+"`)");if(this._checkAppIdData(),r.hosts)s(r.hosts)?(this.hosts.read=a(r.hosts),this.hosts.write=a(r.hosts)):(this.hosts.read=a(r.hosts.read),this.hosts.write=a(r.hosts.write));else{var p=c(this._shuffleResult,function(e){return t+"-"+e+".algolianet.com"});this.hosts.read=[this.applicationID+"-dsn.algolia.net"].concat(p),this.hosts.write=[this.applicationID+".algolia.net"].concat(p)}this.hosts.read=c(this.hosts.read,i(f)),this.hosts.write=c(this.hosts.write,i(f)),this.extraHeaders=[],this.cache=r._cache||{},this._ua=r._ua,this._useCache=!(void 0!==r._useCache&&!r._cache)||r._useCache,this._useFallback=void 0===r.useFallback||r.useFallback,this._setTimeout=r._setTimeout,o("init done, %j",this)}function i(e){return function(t){return e+"//"+t.toLowerCase()}}function o(e){if(void 0===Array.prototype.toJSON)return JSON.stringify(e);var t=Array.prototype.toJSON;delete Array.prototype.toJSON;var n=JSON.stringify(e);return Array.prototype.toJSON=t,n}function a(e){for(var t,n,r=e.length;0!==r;)n=Math.floor(Math.random()*r),r-=1,t=e[r],e[r]=e[n],e[n]=t;return e}function s(e){var t={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r;r="x-algolia-api-key"===n||"x-algolia-application-id"===n?"**hidden for security purposes**":e[n],t[n]=r}return t}t.exports=r;var u=e("./errors"),c=e("./exitPromise.js"),l=e("./IndexCore.js"),f=e("./store.js"),p=500,d=n.env.RESET_APP_DATA_TIMER&&parseInt(n.env.RESET_APP_DATA_TIMER,10)||12e4;r.prototype.initIndex=function(e){return new l(this,e)},r.prototype.setExtraHeader=function(e,t){this.extraHeaders.push({name:e.toLowerCase(),value:t})},r.prototype.addAlgoliaAgent=function(e){this._ua.indexOf(";"+e)===-1&&(this._ua+=";"+e)},r.prototype._jsonRequest=function(t){function n(e,c){function p(e){var t=e&&e.body&&e.body.message&&e.body.status||e.statusCode||e&&e.body&&200;a("received response: statusCode: %s, computed statusCode: %d, headers: %j",e.statusCode,t,e.headers);var n=2===Math.floor(t/100),o=new Date;if(y.push({currentHost:j,headers:s(i),content:r||null,contentLength:void 0!==r?r.length:null,method:c.method,timeouts:c.timeouts,url:c.url,startTime:C,endTime:o,duration:o-C,statusCode:t}),n)return d._useCache&&f&&(f[w]=e.responseText),e.body;var l=4!==Math.floor(t/100);if(l)return h+=1,b();a("unrecoverable error");var p=new u.AlgoliaSearchError(e.body&&e.body.message,{debugData:y,statusCode:t});return d._promise.reject(p)}function g(e){a("error: %s, stack: %s",e.message,e.stack);var n=new Date;return y.push({currentHost:j,headers:s(i),content:r||null,contentLength:void 0!==r?r.length:null,method:c.method,timeouts:c.timeouts,url:c.url,startTime:C,endTime:n,duration:n-C}),e instanceof u.AlgoliaSearchError||(e=new u.Unknown(e&&e.message,e)),h+=1,e instanceof u.Unknown||e instanceof u.UnparsableJSON||h>=d.hosts[t.hostType].length&&(m||!v)?(e.debugData=y,d._promise.reject(e)):e instanceof u.RequestTimeout?_():b()}function b(){return a("retrying request"),d._incrementHostIndex(t.hostType),n(e,c)}function _(){return a("retrying request with higher timeout"),d._incrementHostIndex(t.hostType),d._incrementTimeoutMultipler(),c.timeouts=d._getTimeoutsForRequest(t.hostType),n(e,c)}d._checkAppIdData();var w,C=new Date;if(d._useCache&&(w=t.url),d._useCache&&r&&(w+="_body_"+c.body),d._useCache&&f&&void 0!==f[w])return a("serving response from cache"),d._promise.resolve(JSON.parse(f[w]));if(h>=d.hosts[t.hostType].length)return!v||m?(a("could not get any response"),d._promise.reject(new u.AlgoliaSearchError("Cannot connect to the AlgoliaSearch API. Send an email to [email protected] to report and resolve the issue. Application id was: "+d.applicationID,{debugData:y}))):(a("switching to fallback"),h=0,c.method=t.fallback.method,c.url=t.fallback.url,c.jsonBody=t.fallback.body,c.jsonBody&&(c.body=o(c.jsonBody)),i=d._computeRequestHeaders(l),c.timeouts=d._getTimeoutsForRequest(t.hostType),d._setHostIndexByType(0,t.hostType),m=!0,n(d._request.fallback,c));var j=d._getHostByType(t.hostType),x=j+c.url,R={body:c.body,jsonBody:c.jsonBody,method:c.method,headers:i,timeouts:c.timeouts,debug:a};return a("method: %s, url: %s, headers: %j, timeouts: %d",R.method,x,R.headers,R.timeouts),e===d._request.fallback&&a("using fallback"),e.call(d,x,R).then(p,g)}this._checkAppIdData();var r,i,a=e("debug")("algoliasearch:"+t.url),l=t.additionalUA||"",f=t.cache,d=this,h=0,m=!1,v=d._useFallback&&d._request.fallback&&t.fallback; this.apiKey.length>p&&void 0!==t.body&&(void 0!==t.body.params||void 0!==t.body.requests)?(t.body.apiKey=this.apiKey,i=this._computeRequestHeaders(l,!1)):i=this._computeRequestHeaders(l),void 0!==t.body&&(r=o(t.body)),a("request start");var y=[],g=n(d._request,{url:t.url,method:t.method,body:r,jsonBody:t.body,timeouts:d._getTimeoutsForRequest(t.hostType)});return t.callback?void g.then(function(e){c(function(){t.callback(null,e)},d._setTimeout||setTimeout)},function(e){c(function(){t.callback(e)},d._setTimeout||setTimeout)}):g},r.prototype._getSearchParams=function(e,t){if(void 0===e||null===e)return t;for(var n in e)null!==n&&void 0!==e[n]&&e.hasOwnProperty(n)&&(t+=""===t?"":"&",t+=n+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(e[n])?o(e[n]):e[n]));return t},r.prototype._computeRequestHeaders=function(t,n){var r=e("foreach"),i=t?this._ua+";"+t:this._ua,o={"x-algolia-agent":i,"x-algolia-application-id":this.applicationID};return n!==!1&&(o["x-algolia-api-key"]=this.apiKey),this.userToken&&(o["x-algolia-usertoken"]=this.userToken),this.securityTags&&(o["x-algolia-tagfilters"]=this.securityTags),this.extraHeaders&&r(this.extraHeaders,function(e){o[e.name]=e.value}),o},r.prototype.search=function(t,n,r){var i=e("isarray"),o=e("./map.js"),a="Usage: client.search(arrayOfQueries[, callback])";if(!i(t))throw new Error(a);"function"==typeof n?(r=n,n={}):void 0===n&&(n={});var s=this,u={requests:o(t,function(e){var t="";return void 0!==e.query&&(t+="query="+encodeURIComponent(e.query)),{indexName:e.indexName,params:s._getSearchParams(e.params,t)}})},c=o(u.requests,function(e,t){return t+"="+encodeURIComponent("/1/indexes/"+encodeURIComponent(e.indexName)+"?"+e.params)}).join("&"),l="/1/indexes/*/queries";return void 0!==n.strategy&&(l+="?strategy="+n.strategy),this._jsonRequest({cache:this.cache,method:"POST",url:l,body:u,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:c}},callback:r})},r.prototype.setSecurityTags=function(e){if("[object Array]"===Object.prototype.toString.call(e)){for(var t=[],n=0;n<e.length;++n)if("[object Array]"===Object.prototype.toString.call(e[n])){for(var r=[],i=0;i<e[n].length;++i)r.push(e[n][i]);t.push("("+r.join(",")+")")}else t.push(e[n]);e=t.join(",")}this.securityTags=e},r.prototype.setUserToken=function(e){this.userToken=e},r.prototype.clearCache=function(){this.cache={}},r.prototype.setRequestTimeout=function(e){e&&(this._timeouts.connect=this._timeouts.read=this._timeouts.write=e)},r.prototype.setTimeouts=function(e){this._timeouts=e},r.prototype.getTimeouts=function(){return this._timeouts},r.prototype._getAppIdData=function(){var e=f.get(this.applicationID);return null!==e&&this._cacheAppIdData(e),e},r.prototype._setAppIdData=function(e){return e.lastChange=(new Date).getTime(),this._cacheAppIdData(e),f.set(this.applicationID,e)},r.prototype._checkAppIdData=function(){var e=this._getAppIdData(),t=(new Date).getTime();return null===e||t-e.lastChange>d?this._resetInitialAppIdData(e):e},r.prototype._resetInitialAppIdData=function(e){var t=e||{};return t.hostIndexes={read:0,write:0},t.timeoutMultiplier=1,t.shuffleResult=t.shuffleResult||a([1,2,3]),this._setAppIdData(t)},r.prototype._cacheAppIdData=function(e){this._hostIndexes=e.hostIndexes,this._timeoutMultiplier=e.timeoutMultiplier,this._shuffleResult=e.shuffleResult},r.prototype._partialAppIdDataUpdate=function(t){var n=e("foreach"),r=this._getAppIdData();return n(t,function(e,t){r[t]=e}),this._setAppIdData(r)},r.prototype._getHostByType=function(e){return this.hosts[e][this._getHostIndexByType(e)]},r.prototype._getTimeoutMultiplier=function(){return this._timeoutMultiplier},r.prototype._getHostIndexByType=function(e){return this._hostIndexes[e]},r.prototype._setHostIndexByType=function(t,n){var r=e("./clone"),i=r(this._hostIndexes);return i[n]=t,this._partialAppIdDataUpdate({hostIndexes:i}),t},r.prototype._incrementHostIndex=function(e){return this._setHostIndexByType((this._getHostIndexByType(e)+1)%this.hosts[e].length,e)},r.prototype._incrementTimeoutMultipler=function(){var e=Math.max(this._timeoutMultiplier+1,4);return this._partialAppIdDataUpdate({timeoutMultiplier:e})},r.prototype._getTimeoutsForRequest=function(e){return{connect:this._timeouts.connect*this._timeoutMultiplier,complete:this._timeouts[e]*this._timeoutMultiplier}}}).call(this,e("_process"))},{"./IndexCore.js":25,"./clone":33,"./clone.js":33,"./errors":36,"./exitPromise.js":37,"./map.js":38,"./store.js":42,_process:477,debug:60,foreach:105,isarray:176}],23:[function(e,t,n){function r(){o.apply(this,arguments)}var i=e("inherits"),o=e("./IndexCore.js"),a=e("./deprecate.js"),s=e("./deprecatedMessage.js"),u=e("./exitPromise.js"),c=e("./errors"),l=a(function(){},s("forwardToSlaves","forwardToReplicas"));t.exports=r,i(r,o),r.prototype.addObject=function(e,t,n){var r=this;return 1!==arguments.length&&"function"!=typeof t||(n=t,t=void 0),this.as._jsonRequest({method:void 0!==t?"PUT":"POST",url:"/1/indexes/"+encodeURIComponent(r.indexName)+(void 0!==t?"/"+encodeURIComponent(t):""),body:e,hostType:"write",callback:n})},r.prototype.addObjects=function(t,n){var r=e("isarray"),i="Usage: index.addObjects(arrayOfObjects[, callback])";if(!r(t))throw new Error(i);for(var o=this,a={requests:[]},s=0;s<t.length;++s){var u={action:"addObject",body:t[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(o.indexName)+"/batch",body:a,hostType:"write",callback:n})},r.prototype.partialUpdateObject=function(e,t,n){1!==arguments.length&&"function"!=typeof t||(n=t,t=void 0);var r=this,i="/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e.objectID)+"/partial";return t===!1&&(i+="?createIfNotExists=false"),this.as._jsonRequest({method:"POST",url:i,body:e,hostType:"write",callback:n})},r.prototype.partialUpdateObjects=function(t,n){var r=e("isarray"),i="Usage: index.partialUpdateObjects(arrayOfObjects[, callback])";if(!r(t))throw new Error(i);for(var o=this,a={requests:[]},s=0;s<t.length;++s){var u={action:"partialUpdateObject",objectID:t[s].objectID,body:t[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(o.indexName)+"/batch",body:a,hostType:"write",callback:n})},r.prototype.saveObject=function(e,t){var n=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/"+encodeURIComponent(e.objectID),body:e,hostType:"write",callback:t})},r.prototype.saveObjects=function(t,n){var r=e("isarray"),i="Usage: index.saveObjects(arrayOfObjects[, callback])";if(!r(t))throw new Error(i);for(var o=this,a={requests:[]},s=0;s<t.length;++s){var u={action:"updateObject",objectID:t[s].objectID,body:t[s]};a.requests.push(u)}return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(o.indexName)+"/batch",body:a,hostType:"write",callback:n})},r.prototype.deleteObject=function(e,t){if("function"==typeof e||"string"!=typeof e&&"number"!=typeof e){var n=new c.AlgoliaSearchError("Cannot delete an object without an objectID");return t=e,"function"==typeof t?t(n):this.as._promise.reject(n)}var r=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e),hostType:"write",callback:t})},r.prototype.deleteObjects=function(t,n){var r=e("isarray"),i=e("./map.js"),o="Usage: index.deleteObjects(arrayOfObjectIDs[, callback])";if(!r(t))throw new Error(o);var a=this,s={requests:i(t,function(e){return{action:"deleteObject",objectID:e,body:{objectID:e}}})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(a.indexName)+"/batch",body:s,hostType:"write",callback:n})},r.prototype.deleteByQuery=function(t,n,r){function i(e){if(0===e.nbHits)return e;var t=f(e.hits,function(e){return e.objectID});return p.deleteObjects(t).then(o).then(a)}function o(e){return p.waitTask(e.taskID)}function a(){return p.deleteByQuery(t,n)}function s(){u(function(){r(null)},d._setTimeout||setTimeout)}function c(e){u(function(){r(e)},d._setTimeout||setTimeout)}var l=e("./clone.js"),f=e("./map.js"),p=this,d=p.as;1===arguments.length||"function"==typeof n?(r=n,n={}):n=l(n),n.attributesToRetrieve="objectID",n.hitsPerPage=1e3,n.distinct=!1,this.clearCache();var h=this.search(t,n).then(i);return r?void h.then(s,c):h},r.prototype.browseAll=function(t,n){function r(e){if(!s._stopped){var t;t=void 0!==e?{cursor:e}:{params:l},u._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/browse",hostType:"read",body:t,callback:i})}}function i(e,t){if(!s._stopped)return e?void s._error(e):(s._result(t),void 0===t.cursor?void s._end():void r(t.cursor))}"object"==typeof t&&(n=t,t=void 0);var o=e("./merge.js"),a=e("./IndexBrowser"),s=new a,u=this.as,c=this,l=u._getSearchParams(o({},n||{},{query:t}),"");return r(),s},r.prototype.ttAdapter=function(e){var t=this;return function(n,r,i){var o;o="function"==typeof i?i:r,t.search(n,e,function(e,t){return e?void o(e):void o(t.hits)})}},r.prototype.waitTask=function(e,t){function n(){return l._jsonRequest({method:"GET",hostType:"read",url:"/1/indexes/"+encodeURIComponent(c.indexName)+"/task/"+e}).then(function(e){s++;var t=o*s*s;return t>a&&(t=a),"published"!==e.status?l._promise.delay(t).then(n):e})}function r(e){u(function(){t(null,e)},l._setTimeout||setTimeout)}function i(e){u(function(){t(e)},l._setTimeout||setTimeout)}var o=100,a=5e3,s=0,c=this,l=c.as,f=n();return t?void f.then(r,i):f},r.prototype.clearIndex=function(e){var t=this;return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/clear",hostType:"write",callback:e})},r.prototype.getSettings=function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/settings?getVersion=2",hostType:"read",callback:e})},r.prototype.searchSynonyms=function(e,t){return"function"==typeof e?(t=e,e={}):void 0===e&&(e={}),this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/search",body:e,hostType:"read",callback:t})},r.prototype.saveSynonym=function(e,t,n){"function"==typeof t?(n=t,t={}):void 0===t&&(t={}),void 0!==t.forwardToSlaves&&l();var r=t.forwardToSlaves||t.forwardToReplicas?"true":"false";return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/"+encodeURIComponent(e.objectID)+"?forwardToReplicas="+r,body:e,hostType:"write",callback:n})},r.prototype.getSynonym=function(e,t){return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/"+encodeURIComponent(e),hostType:"read",callback:t})},r.prototype.deleteSynonym=function(e,t,n){"function"==typeof t?(n=t,t={}):void 0===t&&(t={}),void 0!==t.forwardToSlaves&&l();var r=t.forwardToSlaves||t.forwardToReplicas?"true":"false";return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/"+encodeURIComponent(e)+"?forwardToReplicas="+r,hostType:"write",callback:n})},r.prototype.clearSynonyms=function(e,t){"function"==typeof e?(t=e,e={}):void 0===e&&(e={}),void 0!==e.forwardToSlaves&&l();var n=e.forwardToSlaves||e.forwardToReplicas?"true":"false";return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/clear?forwardToReplicas="+n,hostType:"write",callback:t})},r.prototype.batchSynonyms=function(e,t,n){"function"==typeof t?(n=t,t={}):void 0===t&&(t={}),void 0!==t.forwardToSlaves&&l();var r=t.forwardToSlaves||t.forwardToReplicas?"true":"false";return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/synonyms/batch?forwardToReplicas="+r+"&replaceExistingSynonyms="+(t.replaceExistingSynonyms?"true":"false"),hostType:"write",body:e,callback:n})},r.prototype.setSettings=function(e,t,n){1!==arguments.length&&"function"!=typeof t||(n=t,t={}),void 0!==t.forwardToSlaves&&l();var r=t.forwardToSlaves||t.forwardToReplicas?"true":"false",i=this;return this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(i.indexName)+"/settings?forwardToReplicas="+r,hostType:"write",body:e,callback:n})},r.prototype.listUserKeys=function(e){var t=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(t.indexName)+"/keys",hostType:"read",callback:e})},r.prototype.getUserKeyACL=function(e,t){var n=this;return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"read",callback:t})},r.prototype.deleteUserKey=function(e,t){var n=this;return this.as._jsonRequest({method:"DELETE",url:"/1/indexes/"+encodeURIComponent(n.indexName)+"/keys/"+e,hostType:"write",callback:t})},r.prototype.addUserKey=function(t,n,r){var i=e("isarray"),o="Usage: index.addUserKey(arrayOfAcls[, params, callback])";if(!i(t))throw new Error(o);1!==arguments.length&&"function"!=typeof n||(r=n,n=null);var a={acl:t};return n&&(a.validity=n.validity,a.maxQueriesPerIPPerHour=n.maxQueriesPerIPPerHour,a.maxHitsPerQuery=n.maxHitsPerQuery,a.description=n.description,n.queryParameters&&(a.queryParameters=this.as._getSearchParams(n.queryParameters,"")),a.referers=n.referers),this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys",body:a,hostType:"write",callback:r})},r.prototype.addUserKeyWithValidity=a(function(e,t,n){return this.addUserKey(e,t,n)},s("index.addUserKeyWithValidity()","index.addUserKey()")),r.prototype.updateUserKey=function(t,n,r,i){var o=e("isarray"),a="Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])";if(!o(n))throw new Error(a);2!==arguments.length&&"function"!=typeof r||(i=r,r=null);var s={acl:n};return r&&(s.validity=r.validity,s.maxQueriesPerIPPerHour=r.maxQueriesPerIPPerHour,s.maxHitsPerQuery=r.maxHitsPerQuery,s.description=r.description,r.queryParameters&&(s.queryParameters=this.as._getSearchParams(r.queryParameters,"")),s.referers=r.referers),this.as._jsonRequest({method:"PUT",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/keys/"+t,body:s,hostType:"write",callback:i})}},{"./IndexBrowser":24,"./IndexCore.js":25,"./clone.js":33,"./deprecate.js":34,"./deprecatedMessage.js":35,"./errors":36,"./exitPromise.js":37,"./map.js":38,"./merge.js":39,inherits:110,isarray:176}],24:[function(e,t,n){"use strict";function r(){}t.exports=r;var i=e("inherits"),o=e("events").EventEmitter;i(r,o),r.prototype.stop=function(){this._stopped=!0,this._clean()},r.prototype._end=function(){this.emit("end"),this._clean()},r.prototype._error=function(e){this.emit("error",e),this._clean()},r.prototype._result=function(e){this.emit("result",e)},r.prototype._clean=function(){this.removeAllListeners("stop"),this.removeAllListeners("end"),this.removeAllListeners("error"),this.removeAllListeners("result")}},{events:64,inherits:110}],25:[function(e,t,n){function r(e,t){this.indexName=t,this.as=e,this.typeAheadArgs=null,this.typeAheadValueOption=null,this.cache={}}var i=e("./buildSearchMethod.js"),o=e("./deprecate.js"),a=e("./deprecatedMessage.js");t.exports=r,r.prototype.clearCache=function(){this.cache={}},r.prototype.search=i("query"),r.prototype.similarSearch=i("similarQuery"),r.prototype.browse=function(t,n,r){var i,o,a=e("./merge.js"),s=this;0===arguments.length||1===arguments.length&&"function"==typeof arguments[0]?(i=0,r=arguments[0],t=void 0):"number"==typeof arguments[0]?(i=arguments[0],"number"==typeof arguments[1]?o=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1],o=void 0),t=void 0,n=void 0):"object"==typeof arguments[0]?("function"==typeof arguments[1]&&(r=arguments[1]),n=arguments[0],t=void 0):"string"==typeof arguments[0]&&"function"==typeof arguments[1]&&(r=arguments[1],n=void 0),n=a({},n||{},{page:i,hitsPerPage:o,query:t});var u=this.as._getSearchParams(n,"");return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(s.indexName)+"/browse",body:{params:u},hostType:"read",callback:r})},r.prototype.browseFrom=function(e,t){return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse",body:{cursor:e},hostType:"read",callback:t})},r.prototype.searchForFacetValues=function(t,n){var r=e("./clone.js"),i=e("./omit.js"),o="Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])";if(void 0===t.facetName||void 0===t.facetQuery)throw new Error(o);var a=t.facetName,s=i(r(t),function(e){return"facetName"===e}),u=this.as._getSearchParams(s,"");return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/facets/"+encodeURIComponent(a)+"/query",hostType:"read",body:{params:u},callback:n})},r.prototype.searchFacet=o(function(e,t){return this.searchForFacetValues(e,t)},a("index.searchFacet(params[, callback])","index.searchForFacetValues(params[, callback])")),r.prototype._search=function(e,t,n,r){return this.as._jsonRequest({cache:this.cache,method:"POST",url:t||"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:e},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:e}},callback:n,additionalUA:r})},r.prototype.getObject=function(e,t,n){var r=this;1!==arguments.length&&"function"!=typeof t||(n=t,t=void 0);var i="";if(void 0!==t){i="?attributes=";for(var o=0;o<t.length;++o)0!==o&&(i+=","),i+=t[o]}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(r.indexName)+"/"+encodeURIComponent(e)+i,hostType:"read",callback:n})},r.prototype.getObjects=function(t,n,r){var i=e("isarray"),o=e("./map.js"),a="Usage: index.getObjects(arrayOfObjectIDs[, callback])";if(!i(t))throw new Error(a);var s=this;1!==arguments.length&&"function"!=typeof n||(r=n,n=void 0);var u={requests:o(t,function(e){var t={indexName:s.indexName,objectID:e};return n&&(t.attributesToRetrieve=n.join(",")),t})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects",hostType:"read",body:u,callback:r})},r.prototype.as=null,r.prototype.indexName=null,r.prototype.typeAheadArgs=null,r.prototype.typeAheadValueOption=null},{"./buildSearchMethod.js":32,"./clone.js":33,"./deprecate.js":34,"./deprecatedMessage.js":35,"./map.js":38,"./merge.js":39,"./omit.js":40,isarray:176}],26:[function(e,t,n){"use strict";var r=e("../../AlgoliaSearch.js"),i=e("../createAlgoliasearch.js");t.exports=i(r)},{"../../AlgoliaSearch.js":21,"../createAlgoliasearch.js":28}],27:[function(e,t,n){"use strict";var r=e("../../AlgoliaSearchCore.js"),i=e("../createAlgoliasearch.js");t.exports=i(r,"(lite) ")},{"../../AlgoliaSearchCore.js":22,"../createAlgoliasearch.js":28}],28:[function(e,t,n){"use strict";var r=e("global"),i=r.Promise||e("es6-promise").Promise;t.exports=function(t,n){function o(t,n,r){var i=e("../clone.js"),s=e("./get-document-protocol");return r=i(r||{}),void 0===r.protocol&&(r.protocol=s()),r._ua=r._ua||o.ua,new a(t,n,r)}function a(){t.apply(this,arguments)}var s=e("inherits"),u=e("../errors"),c=e("./inline-headers"),l=e("./jsonp-request"),f=e("../places.js");n=n||"",o.version=e("../version.js"),o.ua="Algolia for vanilla JavaScript "+n+o.version,o.initPlaces=f(o),r.__algolia={debug:e("debug"),algoliasearch:o};var p={hasXMLHttpRequest:"XMLHttpRequest"in r,hasXDomainRequest:"XDomainRequest"in r};return p.hasXMLHttpRequest&&(p.cors="withCredentials"in new XMLHttpRequest),s(a,t),a.prototype._request=function(e,t){return new i(function(n,r){function i(){if(!h){clearTimeout(d);var e;try{e={body:JSON.parse(v.responseText),responseText:v.responseText,statusCode:v.status,headers:v.getAllResponseHeaders&&v.getAllResponseHeaders()||{}}}catch(t){e=new u.UnparsableJSON({more:v.responseText})}e instanceof u.UnparsableJSON?r(e):n(e)}}function o(e){h||(clearTimeout(d),r(new u.Network({more:e})))}function a(){h=!0,v.abort(),r(new u.RequestTimeout)}function s(){y=!0,clearTimeout(d),d=setTimeout(a,t.timeouts.complete)}function l(){y||s()}function f(){!y&&v.readyState>1&&s()}if(!p.cors&&!p.hasXDomainRequest)return void r(new u.Network("CORS not supported"));e=c(e,t.headers);var d,h,m=t.body,v=p.cors?new XMLHttpRequest:new XDomainRequest,y=!1;d=setTimeout(a,t.timeouts.connect),v.onprogress=l,"onreadystatechange"in v&&(v.onreadystatechange=f),v.onload=i,v.onerror=o,v instanceof XMLHttpRequest?v.open(t.method,e,!0):v.open(t.method,e),p.cors&&(m&&("POST"===t.method?v.setRequestHeader("content-type","application/x-www-form-urlencoded"):v.setRequestHeader("content-type","application/json")),v.setRequestHeader("accept","application/json")),v.send(m)})},a.prototype._request.fallback=function(e,t){return e=c(e,t.headers),new i(function(n,r){l(e,t,function(e,t){return e?void r(e):void n(t)})})},a.prototype._promise={reject:function(e){return i.reject(e)},resolve:function(e){return i.resolve(e)},delay:function(e){return new i(function(t){setTimeout(t,e)})}},o}},{"../clone.js":33,"../errors":36,"../places.js":41,"../version.js":43,"./get-document-protocol":29,"./inline-headers":30,"./jsonp-request":31,debug:60,"es6-promise":63,global:106,inherits:110}],29:[function(e,t,n){"use strict";function r(){var e=window.document.location.protocol;return"http:"!==e&&"https:"!==e&&(e="http:"),e}t.exports=r},{}],30:[function(e,t,n){"use strict";function r(e,t){return e+=/\?/.test(e)?"&":"?",e+i(t)}t.exports=r;var i=e("querystring-es3/encode")},{"querystring-es3/encode":478}],31:[function(e,t,n){"use strict";function r(e,t,n){function r(){t.debug("JSONP: success"),v||p||(v=!0,f||(t.debug("JSONP: Fail. Script loaded but did not call the callback"),s(),n(new i.JSONPScriptFail)))}function a(){"loaded"!==this.readyState&&"complete"!==this.readyState||r()}function s(){clearTimeout(y),h.onload=null,h.onreadystatechange=null,h.onerror=null,d.removeChild(h)}function u(){try{delete window[m],delete window[m+"_loaded"]}catch(e){window[m]=window[m+"_loaded"]=void 0}}function c(){t.debug("JSONP: Script timeout"),p=!0,s(),n(new i.RequestTimeout)}function l(){t.debug("JSONP: Script error"),v||p||(s(),n(new i.JSONPScriptError))}if("GET"!==t.method)return void n(new Error("Method "+t.method+" "+e+" is not supported by JSONP."));t.debug("JSONP: start");var f=!1,p=!1;o+=1;var d=document.getElementsByTagName("head")[0],h=document.createElement("script"),m="algoliaJSONP_"+o,v=!1;window[m]=function(e){return u(),p?void t.debug("JSONP: Late answer, ignoring"):(f=!0,s(),void n(null,{body:e}))},e+="&callback="+m,t.jsonBody&&t.jsonBody.params&&(e+="&"+t.jsonBody.params);var y=setTimeout(c,t.timeouts.complete);h.onreadystatechange=a,h.onload=r,h.onerror=l,h.async=!0,h.defer=!0,h.src=e,d.appendChild(h)}t.exports=r;var i=e("../errors"),o=0},{"../errors":36}],32:[function(e,t,n){function r(e,t){return function(n,r,o){if("function"==typeof n&&"object"==typeof r||"object"==typeof o)throw new i.AlgoliaSearchError("index.search usage is index.search(query, params, cb)");0===arguments.length||"function"==typeof n?(o=n,n=""):1!==arguments.length&&"function"!=typeof r||(o=r,r=void 0),"object"==typeof n&&null!==n?(r=n,n=void 0):void 0!==n&&null!==n||(n="");var a="";void 0!==n&&(a+=e+"="+encodeURIComponent(n));var s;return void 0!==r&&(r.additionalUA&&(s=r.additionalUA,delete r.additionalUA),a=this.as._getSearchParams(r,a)),this._search(a,t,o,s)}}t.exports=r;var i=e("./errors.js")},{"./errors.js":36}],33:[function(e,t,n){t.exports=function(e){return JSON.parse(JSON.stringify(e))}},{}],34:[function(e,t,n){t.exports=function(e,t){function n(){return r||(console.log(t),r=!0),e.apply(this,arguments)}var r=!1;return n}},{}],35:[function(e,t,n){t.exports=function(e,t){var n=e.toLowerCase().replace(".","").replace("()","");return"algoliasearch: `"+e+"` was replaced by `"+t+"`. Please see https://github.com/algolia/algoliasearch-client-js/wiki/Deprecated#"+n}},{}],36:[function(e,t,n){"use strict";function r(t,n){var r=e("foreach"),i=this;"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):i.stack=(new Error).stack||"Cannot get a stacktrace, browser is too old",this.name="AlgoliaSearchError",this.message=t||"Unknown error",n&&r(n,function(e,t){i[t]=e})}function i(e,t){function n(){var n=Array.prototype.slice.call(arguments,0);"string"!=typeof n[0]&&n.unshift(t),r.apply(this,n),this.name="AlgoliaSearch"+e+"Error"}return o(n,r),n}var o=e("inherits");o(r,Error),t.exports={AlgoliaSearchError:r,UnparsableJSON:i("UnparsableJSON","Could not parse the incoming response as JSON, see err.more for details"),RequestTimeout:i("RequestTimeout","Request timedout before getting a response"),Network:i("Network","Network issue, see err.more for details"),JSONPScriptFail:i("JSONPScriptFail","<script> was loaded but did not call our provided callback"),JSONPScriptError:i("JSONPScriptError","<script> unable to load due to an `error` event on it"),Unknown:i("Unknown","Unknown error occured")}},{foreach:105,inherits:110}],37:[function(e,t,n){t.exports=function(e,t){t(e,0)}},{}],38:[function(e,t,n){var r=e("foreach");t.exports=function(e,t){var n=[];return r(e,function(r,i){n.push(t(r,i,e))}),n}},{foreach:105}],39:[function(e,t,n){var r=e("foreach");t.exports=function i(e){var t=Array.prototype.slice.call(arguments);return r(t,function(t){for(var n in t)t.hasOwnProperty(n)&&("object"==typeof e[n]&&"object"==typeof t[n]?e[n]=i({},e[n],t[n]):void 0!==t[n]&&(e[n]=t[n]))}),e}},{foreach:105}],40:[function(e,t,n){t.exports=function(t,n){var r=e("object-keys"),i=e("foreach"),o={};return i(r(t),function(e){n(e)!==!0&&(o[e]=t[e])}),o}},{foreach:105,"object-keys":475}],41:[function(e,t,n){function r(t){return function(n,r,o){var a=e("./clone.js");o=o&&a(o)||{},o.hosts=o.hosts||["places-dsn.algolia.net","places-1.algolianet.com","places-2.algolianet.com","places-3.algolianet.com"],0!==arguments.length&&"object"!=typeof n&&void 0!==n||(n="",r="",o._allowEmptyCredentials=!0);var s=t(n,r,o),u=s.initIndex("places");return u.search=i("query","/1/places/query"),u}}t.exports=r;var i=e("./buildSearchMethod.js")},{"./buildSearchMethod.js":32,"./clone.js":33}],42:[function(e,t,n){(function(n){function r(e,t){return u("localStorage failed with",t),a(),s=l,s.get(e)}function i(e,t){return 1===arguments.length?s.get(e):s.set(e,t)}function o(){try{return"localStorage"in n&&null!==n.localStorage&&(n.localStorage[c]||n.localStorage.setItem(c,JSON.stringify({})),!0)}catch(e){return!1}}function a(){try{n.localStorage.removeItem(c)}catch(e){}}var s,u=e("debug")("algoliasearch:src/hostIndexState.js"),c="algoliasearch-client-js",l={state:{},set:function(e,t){return this.state[e]=t,this.state[e]},get:function(e){return this.state[e]||null}},f={set:function(e,t){l.set(e,t);try{var i=JSON.parse(n.localStorage[c]);return i[e]=t,n.localStorage[c]=JSON.stringify(i),i[e]}catch(o){return r(e,o)}},get:function(e){try{return JSON.parse(n.localStorage[c])[e]||null}catch(t){return r(e,t)}}};s=o()?f:l,t.exports={get:i,set:i,supportsLocalStorage:o}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{debug:60}],43:[function(e,t,n){"use strict";t.exports="3.21.1"},{}],44:[function(e,t,n){"use strict";t.exports=e("./src/jquery/plugin.js")},{"./src/jquery/plugin.js":55}],45:[function(e,t,n){"use strict";var r=e("../common/utils.js"),i={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:"0"}};r.isMsie()&&r.mixin(i.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),r.isMsie()&&r.isMsie()<=7&&r.mixin(i.input,{marginTop:"-1px"}),t.exports=i},{"../common/utils.js":54}],46:[function(e,t,n){"use strict";function r(e){e=e||{},e.templates=e.templates||{},e.source||l.error("missing source"),e.name&&!a(e.name)&&l.error("invalid dataset name: "+e.name),this.query=null,this.highlight=!!e.highlight,this.name="undefined"==typeof e.name||null===e.name?l.getUniqueId():e.name,this.source=e.source,this.displayFn=i(e.display||e.displayKey),this.templates=o(e.templates,this.displayFn),this.$el=e.$menu&&e.$menu.find(".aa-dataset-"+this.name).length>0?f.element(e.$menu.find(".aa-dataset-"+this.name)[0]):f.element(p.dataset.replace("%CLASS%",this.name)),this.$menu=e.$menu}function i(e){function t(t){return t[e]}return e=e||"value",l.isFunction(e)?e:t}function o(e,t){function n(e){return"<p>"+t(e)+"</p>"}return{empty:e.empty&&l.templatify(e.empty),header:e.header&&l.templatify(e.header),footer:e.footer&&l.templatify(e.footer),suggestion:e.suggestion||n}}function a(e){return/^[_a-zA-Z0-9-]+$/.test(e)}var s="aaDataset",u="aaValue",c="aaDatum",l=e("../common/utils.js"),f=e("../common/dom.js"),p=e("./html.js"),d=e("./css.js"),h=e("./event_emitter.js");r.extractDatasetName=function(e){return f.element(e).data(s)},r.extractValue=function(e){return f.element(e).data(u)},r.extractDatum=function(e){var t=f.element(e).data(c);return"string"==typeof t&&(t=JSON.parse(t)),t},l.mixin(r.prototype,h,{_render:function(e,t){function n(){var t=[].slice.call(arguments,0);return t=[{query:e,isEmpty:!0}].concat(t),h.templates.empty.apply(this,t)}function r(){function e(e){var t;return t=f.element(p.suggestion).append(h.templates.suggestion.apply(this,[e].concat(i))),t.data(s,h.name),t.data(u,h.displayFn(e)||void 0),t.data(c,JSON.stringify(e)),t.children().each(function(){f.element(this).css(d.suggestionChild)}),t}var n,r,i=[].slice.call(arguments,0);return n=f.element(p.suggestions).css(d.suggestions),r=l.map(t,e),n.append.apply(n,r),n}function i(){var t=[].slice.call(arguments,0);return t=[{query:e,isEmpty:!a}].concat(t),h.templates.header.apply(this,t)}function o(){var t=[].slice.call(arguments,0);return t=[{query:e,isEmpty:!a}].concat(t),h.templates.footer.apply(this,t)}if(this.$el){var a,h=this,m=[].slice.call(arguments,2);this.$el.empty(),a=t&&t.length,!a&&this.templates.empty?this.$el.html(n.apply(this,m)).prepend(h.templates.header?i.apply(this,m):null).append(h.templates.footer?o.apply(this,m):null):a&&this.$el.html(r.apply(this,m)).prepend(h.templates.header?i.apply(this,m):null).append(h.templates.footer?o.apply(this,m):null),this.$menu&&this.$menu.addClass("aa-"+(a?"with":"without")+"-"+this.name).removeClass("aa-"+(a?"without":"with")+"-"+this.name),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(e){function t(t){if(!n.canceled&&e===n.query){var r=[].slice.call(arguments,1);r=[e,t].concat(r),n._render.apply(n,r)}}var n=this;this.query=e,this.canceled=!1,this.source(e,t)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),t.exports=r},{"../common/dom.js":53,"../common/utils.js":54,"./css.js":45,"./event_emitter.js":49,"./html.js":50}],47:[function(e,t,n){"use strict";function r(e){var t,n,r,s=this;e=e||{},e.menu||o.error("menu is required"),o.isArray(e.datasets)||o.isObject(e.datasets)||o.error("1 or more datasets required"),e.datasets||o.error("datasets is required"),this.isOpen=!1,this.isEmpty=!0,t=o.bind(this._onSuggestionClick,this),n=o.bind(this._onSuggestionMouseEnter,this),r=o.bind(this._onSuggestionMouseLeave,this),this.$menu=a.element(e.menu).on("click.aa",".aa-suggestion",t).on("mouseenter.aa",".aa-suggestion",n).on("mouseleave.aa",".aa-suggestion",r),e.templates&&e.templates.header&&this.$menu.prepend(o.templatify(e.templates.header)()),this.datasets=o.map(e.datasets,function(e){return i(s.$menu,e)}),o.each(this.datasets,function(e){var t=e.getRoot();t&&0===t.parent().length&&s.$menu.append(t),e.onSync("rendered",s._onRendered,s)}),e.templates&&e.templates.footer&&this.$menu.append(o.templatify(e.templates.footer)()); }function i(e,t){return new r.Dataset(o.mixin({$menu:e},t))}var o=e("../common/utils.js"),a=e("../common/dom.js"),s=e("./event_emitter.js"),u=e("./dataset.js"),c=e("./css.js");o.mixin(r.prototype,s,{_onSuggestionClick:function(e){this.trigger("suggestionClicked",a.element(e.currentTarget))},_onSuggestionMouseEnter:function(e){this._removeCursor(),this._setCursor(a.element(e.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function e(e){return e.isEmpty()}this.isEmpty=o.every(this.datasets,e),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".aa-suggestion")},_getCursor:function(){return this.$menu.find(".aa-cursor").first()},_setCursor:function(e,t){e.first().addClass("aa-cursor"),t||this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("aa-cursor")},_moveCursor:function(e){var t,n,r,i;if(this.isOpen){if(n=this._getCursor(),t=this._getSuggestions(),this._removeCursor(),r=t.index(n)+e,r=(r+1)%(t.length+1)-1,r===-1)return void this.trigger("cursorRemoved");r<-1&&(r=t.length-1),this._setCursor(i=t.eq(r)),this._ensureVisible(i)}},_ensureVisible:function(e){var t,n,r,i;t=e.position().top,n=t+e.height()+parseInt(e.css("margin-top"),10)+parseInt(e.css("margin-bottom"),10),r=this.$menu.scrollTop(),i=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),t<0?this.$menu.scrollTop(r+t):i<n&&this.$menu.scrollTop(r+(n-i))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,this.isEmpty||this._show(),this.trigger("opened"))},setLanguageDirection:function(e){this.$menu.css("ltr"===e?c.ltr:c.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(e){var t=null;return e.length&&(t={raw:u.extractDatum(e),value:u.extractValue(e),datasetName:u.extractDatasetName(e)}),t},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(e){function t(t){t.update(e)}o.each(this.datasets,t)},empty:function(){function e(e){e.clear()}o.each(this.datasets,e),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function e(e){e.destroy()}this.$menu.off(".aa"),this.$menu=null,o.each(this.datasets,e)}}),r.Dataset=u,t.exports=r},{"../common/dom.js":53,"../common/utils.js":54,"./css.js":45,"./dataset.js":46,"./event_emitter.js":49}],48:[function(e,t,n){"use strict";function r(e){e&&e.el||o.error("EventBus initialized without el"),this.$el=a.element(e.el)}var i="autocomplete:",o=e("../common/utils.js"),a=e("../common/dom.js");o.mixin(r.prototype,{trigger:function(e){var t=[].slice.call(arguments,1);this.$el.trigger(i+e,t)}}),t.exports=r},{"../common/dom.js":53,"../common/utils.js":54}],49:[function(e,t,n){"use strict";function r(e,t,n,r){var i;if(!n)return this;for(t=t.split(f),n=r?l(n,r):n,this._callbacks=this._callbacks||{};i=t.shift();)this._callbacks[i]=this._callbacks[i]||{sync:[],async:[]},this._callbacks[i][e].push(n);return this}function i(e,t,n){return r.call(this,"async",e,t,n)}function o(e,t,n){return r.call(this,"sync",e,t,n)}function a(e){var t;if(!this._callbacks)return this;for(e=e.split(f);t=e.shift();)delete this._callbacks[t];return this}function s(e){var t,n,r,i,o;if(!this._callbacks)return this;for(e=e.split(f),r=[].slice.call(arguments,1);(t=e.shift())&&(n=this._callbacks[t]);)i=u(n.sync,this,[t].concat(r)),o=u(n.async,this,[t].concat(r)),i()&&p(o);return this}function u(e,t,n){function r(){for(var r,i=0,o=e.length;!r&&i<o;i+=1)r=e[i].apply(t,n)===!1;return!r}return r}function c(){var e;return e=window.setImmediate?function(e){setImmediate(function(){e()})}:function(e){setTimeout(function(){e()},0)}}function l(e,t){return e.bind?e.bind(t):function(){e.apply(t,[].slice.call(arguments,0))}}var f=/\s+/,p=c();t.exports={onSync:o,onAsync:i,off:a,trigger:s}},{}],50:[function(e,t,n){"use strict";t.exports={wrapper:'<span class="algolia-autocomplete"></span>',dropdown:'<span class="aa-dropdown-menu"></span>',dataset:'<div class="aa-dataset-%CLASS%"></div>',suggestions:'<span class="aa-suggestions"></span>',suggestion:'<div class="aa-suggestion"></div>'}},{}],51:[function(e,t,n){"use strict";function r(e){var t,n,r,o,a=this;e=e||{},e.input||u.error("input is missing"),t=u.bind(this._onBlur,this),n=u.bind(this._onFocus,this),r=u.bind(this._onKeydown,this),o=u.bind(this._onInput,this),this.$hint=c.element(e.hint),this.$input=c.element(e.input).on("blur.aa",t).on("focus.aa",n).on("keydown.aa",r),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=u.noop),u.isMsie()?this.$input.on("keydown.aa keypress.aa cut.aa paste.aa",function(e){s[e.which||e.keyCode]||u.defer(u.bind(a._onInput,a,e))}):this.$input.on("input.aa",o),this.query=this.$input.val(),this.$overflowHelper=i(this.$input)}function i(e){return c.element('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:e.css("font-family"),fontSize:e.css("font-size"),fontStyle:e.css("font-style"),fontVariant:e.css("font-variant"),fontWeight:e.css("font-weight"),wordSpacing:e.css("word-spacing"),letterSpacing:e.css("letter-spacing"),textIndent:e.css("text-indent"),textRendering:e.css("text-rendering"),textTransform:e.css("text-transform")}).insertAfter(e)}function o(e,t){return r.normalizeQuery(e)===r.normalizeQuery(t)}function a(e){return e.altKey||e.ctrlKey||e.metaKey||e.shiftKey}var s;s={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"};var u=e("../common/utils.js"),c=e("../common/dom.js"),l=e("./event_emitter.js");r.normalizeQuery=function(e){return(e||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},u.mixin(r.prototype,l,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(e){var t=s[e.which||e.keyCode];this._managePreventDefault(t,e),t&&this._shouldTrigger(t,e)&&this.trigger(t+"Keyed",e)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(e,t){var n,r,i;switch(e){case"tab":r=this.getHint(),i=this.getInputValue(),n=r&&r!==i&&!a(t);break;case"up":case"down":n=!a(t);break;default:n=!1}n&&t.preventDefault()},_shouldTrigger:function(e,t){var n;switch(e){case"tab":n=!a(t);break;default:n=!0}return n},_checkInputValue:function(){var e,t,n;e=this.getInputValue(),t=o(e,this.query),n=!(!t||!this.query)&&this.query.length!==e.length,this.query=e,t?n&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(e){this.query=e},getInputValue:function(){return this.$input.val()},setInputValue:function(e,t){"undefined"==typeof e&&(e=this.query),this.$input.val(e),t?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(e){this.$hint.val(e)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var e,t,n,r;e=this.getInputValue(),t=this.getHint(),n=e!==t&&0===t.indexOf(e),r=""!==e&&n&&!this.hasOverflow(),r||this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var e=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=e},isCursorAtEnd:function(){var e,t,n;return e=this.$input.val().length,t=this.$input[0].selectionStart,u.isNumber(t)?t===e:!document.selection||(n=document.selection.createRange(),n.moveStart("character",-e),e===n.text.length)},destroy:function(){this.$hint.off(".aa"),this.$input.off(".aa"),this.$hint=this.$input=this.$overflowHelper=null}}),t.exports=r},{"../common/dom.js":53,"../common/utils.js":54,"./event_emitter.js":49}],52:[function(e,t,n){"use strict";function r(e){var t,n,o;e=e||{},e.input||u.error("missing input"),this.isActivated=!1,this.debug=!!e.debug,this.autoselect=!!e.autoselect,this.openOnFocus=!!e.openOnFocus,this.minLength=u.isNumber(e.minLength)?e.minLength:1,this.$node=i(e),t=this.$node.find(".aa-dropdown-menu"),n=this.$node.find(".aa-input"),o=this.$node.find(".aa-hint"),e.dropdownMenuContainer&&c.element(e.dropdownMenuContainer).css("position","relative").append(t.css("top","0")),n.on("blur.aa",function(e){var r=document.activeElement;u.isMsie()&&(t.is(r)||t.has(r).length>0)&&(e.preventDefault(),e.stopImmediatePropagation(),u.defer(function(){n.focus()}))}),t.on("mousedown.aa",function(e){e.preventDefault()}),this.eventBus=e.eventBus||new l({el:n}),this.dropdown=new r.Dropdown({menu:t,datasets:e.datasets,templates:e.templates}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new r.Input({input:n,hint:o}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function i(e){var t,n,r,i;t=c.element(e.input),n=c.element(d.wrapper).css(h.wrapper),"block"===t.css("display")&&"table"===t.parent().css("display")&&n.css("display","table-cell"),r=c.element(d.dropdown).css(h.dropdown),e.templates&&e.templates.dropdownMenu&&r.html(u.templatify(e.templates.dropdownMenu)()),i=t.clone().css(h.hint).css(o(t)),i.val("").addClass("aa-hint").removeAttr("id name placeholder required").prop("readonly",!0).attr({autocomplete:"off",spellcheck:"false",tabindex:-1}),i.removeData&&i.removeData(),t.data(s,{dir:t.attr("dir"),autocomplete:t.attr("autocomplete"),spellcheck:t.attr("spellcheck"),style:t.attr("style")}),t.addClass("aa-input").attr({autocomplete:"off",spellcheck:!1}).css(e.hint?h.input:h.inputWithNoHint);try{t.attr("dir")||t.attr("dir","auto")}catch(a){}return t.wrap(n).parent().prepend(e.hint?i:null).append(r)}function o(e){return{backgroundAttachment:e.css("background-attachment"),backgroundClip:e.css("background-clip"),backgroundColor:e.css("background-color"),backgroundImage:e.css("background-image"),backgroundOrigin:e.css("background-origin"),backgroundPosition:e.css("background-position"),backgroundRepeat:e.css("background-repeat"),backgroundSize:e.css("background-size")}}function a(e){var t=e.find(".aa-input");u.each(t.data(s),function(e,n){void 0===e?t.removeAttr(n):t.attr(n,e)}),t.detach().removeClass("aa-input").insertAfter(e),t.removeData&&t.removeData(s),e.remove()}var s="aaAttrs",u=e("../common/utils.js"),c=e("../common/dom.js"),l=e("./event_bus.js"),f=e("./input.js"),p=e("./dropdown.js"),d=e("./html.js"),h=e("./css.js");u.mixin(r.prototype,{_onSuggestionClicked:function(e,t){var n;(n=this.dropdown.getDatumForSuggestion(t))&&this._select(n)},_onCursorMoved:function(){var e=this.dropdown.getDatumForCursor();this.input.setInputValue(e.value,!0),this.eventBus.trigger("cursorchanged",e.raw,e.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint(),this.eventBus.trigger("updated")},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){if(this.isActivated=!0,this.openOnFocus){var e=this.input.getQuery();e.length>=this.minLength?this.dropdown.update(e):this.dropdown.empty(),this.dropdown.open()}},_onBlurred:function(){this.debug||(this.isActivated=!1,this.dropdown.empty(),this.dropdown.close())},_onEnterKeyed:function(e,t){var n,r;n=this.dropdown.getDatumForCursor(),r=this.dropdown.getDatumForTopSuggestion(),n?(this._select(n),t.preventDefault()):this.autoselect&&r&&(this._select(r),t.preventDefault())},_onTabKeyed:function(e,t){var n;(n=this.dropdown.getDatumForCursor())?(this._select(n),t.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var e=this.input.getQuery();this.dropdown.isEmpty&&e.length>=this.minLength?this.dropdown.update(e):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var e=this.input.getQuery();this.dropdown.isEmpty&&e.length>=this.minLength?this.dropdown.update(e):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(e,t){this.input.clearHintIfInvalid(),t.length>=this.minLength?this.dropdown.update(t):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var e=this.input.getLanguageDirection();this.dir!==e&&(this.dir=e,this.$node.css("direction",e),this.dropdown.setLanguageDirection(e))},_updateHint:function(){var e,t,n,r,i,o;e=this.dropdown.getDatumForTopSuggestion(),e&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(t=this.input.getInputValue(),n=f.normalizeQuery(t),r=u.escapeRegExChars(n),i=new RegExp("^(?:"+r+")(.+$)","i"),o=i.exec(e.value),o?this.input.setHint(t+o[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(e){var t,n,r,i;t=this.input.getHint(),n=this.input.getQuery(),r=e||this.input.isCursorAtEnd(),t&&n!==t&&r&&(i=this.dropdown.getDatumForTopSuggestion(),i&&this.input.setInputValue(i.value),this.eventBus.trigger("autocompleted",i.raw,i.datasetName))},_select:function(e){"undefined"!=typeof e.value&&this.input.setQuery(e.value),this.input.setInputValue(e.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",e.raw,e.datasetName),this.dropdown.close(),u.defer(u.bind(this.dropdown.empty,this.dropdown))},open:function(){if(!this.isActivated){var e=this.input.getInputValue();e.length>=this.minLength?this.dropdown.update(e):this.dropdown.empty()}this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(e){e=u.toStr(e),this.isActivated?this.input.setInputValue(e):(this.input.setQuery(e),this.input.setInputValue(e,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),a(this.$node),this.$node=null}}),r.Dropdown=p,r.Input=f,r.sources=e("../sources/index.js"),t.exports=r},{"../common/dom.js":53,"../common/utils.js":54,"../sources/index.js":57,"./css.js":45,"./dropdown.js":47,"./event_bus.js":48,"./html.js":50,"./input.js":51}],53:[function(e,t,n){"use strict";t.exports={element:null}},{}],54:[function(e,t,n){"use strict";var r=e("./dom.js");t.exports={isArray:null,isFunction:null,isObject:null,bind:null,each:null,map:null,mixin:null,isMsie:function(){return!!/(msie|trident)/i.test(navigator.userAgent)&&navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]},escapeRegExChars:function(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isNumber:function(e){return"number"==typeof e},toStr:function(e){return void 0===e||null===e?"":e+""},cloneDeep:function(e){var t=this.mixin({},e),n=this;return this.each(t,function(e,r){e&&(n.isArray(e)?t[r]=[].concat(e):n.isObject(e)&&(t[r]=n.cloneDeep(e)))}),t},error:function(e){throw new Error(e)},every:function(e,t){var n=!0;return e?(this.each(e,function(r,i){if(n=t.call(null,r,i,e),!n)return!1}),!!n):n},getUniqueId:function(){var e=0;return function(){return e++}}(),templatify:function(e){if(this.isFunction(e))return e;var t=r.element(e);return"SCRIPT"===t.prop("tagName")?function(){return t.text()}:function(){return String(e)}},defer:function(e){setTimeout(e,0)},noop:function(){}}},{"./dom.js":53}],55:[function(e,t,n){(function(n){"use strict";var r=e("../common/dom.js"),i="undefined"!=typeof window?window.$:"undefined"!=typeof n?n.$:null;r.element=i;var o=e("../common/utils.js");o.isArray=i.isArray,o.isFunction=i.isFunction,o.isObject=i.isPlainObject,o.bind=i.proxy,o.each=function(e,t){function n(e,n){return t(n,e)}i.each(e,n)},o.map=i.map,o.mixin=i.extend;var a,s,u,c=e("../autocomplete/typeahead.js"),l=e("../autocomplete/event_bus.js");a=i.fn.autocomplete,s="aaAutocomplete",u={initialize:function(e,t){function n(){var n,r=i(this),o=new l({el:r});n=new c({input:r,eventBus:o,dropdownMenuContainer:e.dropdownMenuContainer,hint:void 0===e.hint||!!e.hint,minLength:e.minLength,autoselect:e.autoselect,openOnFocus:e.openOnFocus,templates:e.templates,debug:e.debug,datasets:t}),r.data(s,n)}return t=o.isArray(t)?t:[].slice.call(arguments,1),e=e||{},this.each(n)},open:function(){function e(){var e,t=i(this);(e=t.data(s))&&e.open()}return this.each(e)},close:function(){function e(){var e,t=i(this);(e=t.data(s))&&e.close()}return this.each(e)},val:function(e){function t(){var t,n=i(this);(t=n.data(s))&&t.setVal(e)}function n(e){var t,n;return(t=e.data(s))&&(n=t.getVal()),n}return arguments.length?this.each(t):n(this.first())},destroy:function(){function e(){var e,t=i(this);(e=t.data(s))&&(e.destroy(),t.removeData(s))}return this.each(e)}},i.fn.autocomplete=function(e){var t;return u[e]&&"initialize"!==e?(t=this.filter(function(){return!!i(this).data(s)}),u[e].apply(t,[].slice.call(arguments,1))):u.initialize.apply(this,arguments)},i.fn.autocomplete.noConflict=function(){return i.fn.autocomplete=a,this},i.fn.autocomplete.sources=c.sources,t.exports=i.fn.autocomplete}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../autocomplete/event_bus.js":48,"../autocomplete/typeahead.js":52,"../common/dom.js":53,"../common/utils.js":54}],56:[function(e,t,n){"use strict";var r=e("../common/utils.js");t.exports=function(e,t){function n(n,i){e.search(n,t,function(e,t){return e?void r.error(e.message):void i(t.hits,t)})}return n}},{"../common/utils.js":54}],57:[function(e,t,n){"use strict";t.exports={hits:e("./hits.js"),popularIn:e("./popularIn.js")}},{"./hits.js":56,"./popularIn.js":58}],58:[function(e,t,n){"use strict";var r=e("../common/utils.js");t.exports=function(e,t,n,i){function o(o,u){e.search(o,t,function(e,t){if(e)return void r.error(e.message);if(t.hits.length>0){var o=t.hits[0],c=r.mixin({hitsPerPage:0},n);return delete c.source,delete c.index,void s.search(a(o),c,function(e,n){if(e)return void r.error(e.message);var a=[];if(i.includeAll){var s=i.allTitle||"All departments";a.push(r.mixin({facet:{value:s,count:n.nbHits}},r.cloneDeep(o)))}r.each(n.facets,function(e,t){r.each(e,function(e,n){a.push(r.mixin({facet:{facet:t,value:n,count:e}},r.cloneDeep(o)))})});for(var c=1;c<t.hits.length;++c)a.push(t.hits[c]);u(a,t)})}u([])})}if(!n.source)return r.error("Missing 'source' key");var a=r.isFunction(n.source)?n.source:function(e){return e[n.source]};if(!n.index)return r.error("Missing 'index' key");var s=n.index;return i=i||{},o}},{"../common/utils.js":54}],59:[function(t,n,r){!function(){"use strict";function t(){for(var e=[],n=0;n<arguments.length;n++){var i=arguments[n];if(i){var o=typeof i;if("string"===o||"number"===o)e.push(i);else if(Array.isArray(i))e.push(t.apply(null,i));else if("object"===o)for(var a in i)r.call(i,a)&&i[a]&&e.push(a)}}return e.join(" ")}var r={}.hasOwnProperty;"undefined"!=typeof n&&n.exports?n.exports=t:"function"==typeof e&&"object"==typeof e.amd&&e.amd?e("classnames",[],function(){return t}):window.classNames=t}()},{}],60:[function(e,t,n){(function(r){function i(){return"undefined"!=typeof document&&"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function o(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var i=0,o=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(i++,"%c"===e&&(o=i))}),e.splice(o,0,r),e}function a(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function s(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(t){}}function u(){try{return n.storage.debug}catch(e){}if("undefined"!=typeof r&&"env"in r)return r.env.DEBUG}function c(){try{return window.localStorage}catch(e){}}n=t.exports=e("./debug"),n.log=a,n.formatArgs=o,n.save=s,n.load=u,n.useColors=i,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:c(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},n.enable(u())}).call(this,e("_process"))},{"./debug":61,_process:477}],61:[function(e,t,n){function r(){return n.colors[l++%n.colors.length]}function i(e){function t(){}function i(){var e=i,t=+new Date,o=t-(c||t);e.diff=o,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());for(var a=new Array(arguments.length),s=0;s<a.length;s++)a[s]=arguments[s];a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var u=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;u++;var i=n.formatters[r];if("function"==typeof i){var o=a[u];t=i.call(e,o),a.splice(u,1),u--}return t}),a=n.formatArgs.apply(e,a);var l=i.log||n.log||console.log.bind(console);l.apply(e,a)}t.enabled=!1,i.enabled=!0;var o=n.enabled(e)?i:t;return o.namespace=e,o}function o(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,i=0;i<r;i++)t[i]&&(e=t[i].replace(/[\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,".*?"),"-"===e[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function a(){n.enable("")}function s(e){var t,r;for(t=0,r=n.skips.length;t<r;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;t<r;t++)if(n.names[t].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}n=t.exports=i.debug=i,n.coerce=u,n.disable=a,n.enable=o,n.enabled=s,n.humanize=e("ms"),n.names=[],n.skips=[],n.formatters={};var c,l=0},{ms:473}],62:[function(e,t,n){(function(e){!function(e){"use strict";function t(e,t){function r(e){return this&&this.constructor===r?(this._keys=[],this._values=[],this._itp=[],this.objectOnly=t,void(e&&n.call(this,e))):new r(e)}return t||b(e,"size",{get:v}),e.constructor=r,r.prototype=e,r}function n(e){this.add?e.forEach(this.add,this):e.forEach(function(e){this.set(e[0],e[1])},this)}function r(e){return this.has(e)&&(this._keys.splice(g,1),this._values.splice(g,1),this._itp.forEach(function(e){g<e[0]&&e[0]--})),-1<g}function i(e){return this.has(e)?this._values[g]:void 0}function o(e,t){if(this.objectOnly&&t!==Object(t))throw new TypeError("Invalid value used as weak collection key");if(t!=t||0===t)for(g=e.length;g--&&!_(e[g],t););else g=e.indexOf(t);return-1<g}function a(e){return o.call(this,this._values,e)}function s(e){return o.call(this,this._keys,e)}function u(e,t){return this.has(e)?this._values[g]=t:this._values[this._keys.push(e)-1]=t,this}function c(e){return this.has(e)||this._values.push(e),this}function l(){(this._keys||0).length=this._values.length=0}function f(){return m(this._itp,this._keys)}function p(){return m(this._itp,this._values)}function d(){return m(this._itp,this._keys,this._values)}function h(){return m(this._itp,this._values,this._values)}function m(e,t,n){var r=[0],i=!1;return e.push(r),{next:function(){var o,a=r[0];return!i&&a<t.length?(o=n?[t[a],n[a]]:t[a],r[0]++):(i=!0,e.splice(e.indexOf(r),1)),{done:i,value:o}}}}function v(){return this._values.length}function y(e,t){for(var n=this.entries();;){var r=n.next();if(r.done)break;e.call(t,r.value[1],r.value[0],this)}}var g,b=Object.defineProperty,_=function(e,t){return e===t||e!==e&&t!==t};"undefined"==typeof WeakMap&&(e.WeakMap=t({"delete":r,clear:l,get:i,has:s,set:u},!0)),"undefined"!=typeof Map&&"function"==typeof(new Map).values&&(new Map).values().next||(e.Map=t({"delete":r,has:s,get:i,set:u,keys:f,values:p,entries:d,forEach:y,clear:l})),"undefined"!=typeof Set&&"function"==typeof(new Set).values&&(new Set).values().next||(e.Set=t({has:a,add:c,"delete":r,clear:l,keys:p,values:p,entries:h,forEach:y})),"undefined"==typeof WeakSet&&(e.WeakSet=t({"delete":r,add:c,clear:l,has:a},!0))}("undefined"!=typeof n&&"undefined"!=typeof e?e:window)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],63:[function(t,n,r){(function(i,o){!function(t,i){"object"==typeof r&&"undefined"!=typeof n?n.exports=i():"function"==typeof e&&e.amd?e(i):t.ES6Promise=i()}(this,function(){"use strict";function e(e){return"function"==typeof e||"object"==typeof e&&null!==e}function n(e){return"function"==typeof e}function r(e){G=e}function a(e){Y=e}function s(){return function(){return i.nextTick(p)}}function u(){return"undefined"!=typeof $?function(){$(p)}:f()}function c(){var e=0,t=new Z(p),n=document.createTextNode("");return t.observe(n,{characterData:!0}),function(){n.data=e=++e%2}}function l(){var e=new MessageChannel;return e.port1.onmessage=p,function(){return e.port2.postMessage(0)}}function f(){var e=setTimeout;return function(){return e(p,1)}}function p(){for(var e=0;e<Q;e+=2){var t=ne[e],n=ne[e+1];t(n),ne[e]=void 0,ne[e+1]=void 0}Q=0}function d(){try{var e=t,n=e("vertx");return $=n.runOnLoop||n.runOnContext,u()}catch(r){return f()}}function h(e,t){var n=arguments,r=this,i=new this.constructor(v);void 0===i[ie]&&F(i);var o=r._state;return o?!function(){var e=n[o-1];Y(function(){return M(o,i,e,r._result)})}():O(r,i,e,t),i}function m(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var n=new t(v);return x(n,e),n}function v(){}function y(){return new TypeError("You cannot resolve a promise with itself")}function g(){return new TypeError("A promises callback cannot return that same promise.")}function b(e){try{return e.then}catch(t){return ue.error=t,ue}}function _(e,t,n,r){try{e.call(t,n,r)}catch(i){return i}}function w(e,t,n){Y(function(e){var r=!1,i=_(n,t,function(n){r||(r=!0,t!==n?x(e,n):P(e,n))},function(t){r||(r=!0,E(e,t))},"Settle: "+(e._label||" unknown promise"));!r&&i&&(r=!0,E(e,i))},e)}function C(e,t){t._state===ae?P(e,t._result):t._state===se?E(e,t._result):O(t,void 0,function(t){return x(e,t)},function(t){return E(e,t)})}function j(e,t,r){t.constructor===e.constructor&&r===h&&t.constructor.resolve===m?C(e,t):r===ue?E(e,ue.error):void 0===r?P(e,t):n(r)?w(e,t,r):P(e,t)}function x(t,n){t===n?E(t,y()):e(n)?j(t,n,b(n)):P(t,n)}function R(e){e._onerror&&e._onerror(e._result),S(e)}function P(e,t){e._state===oe&&(e._result=t,e._state=ae,0!==e._subscribers.length&&Y(S,e))}function E(e,t){e._state===oe&&(e._state=se,e._result=t,Y(R,e))}function O(e,t,n,r){var i=e._subscribers,o=i.length;e._onerror=null,i[o]=t,i[o+ae]=n,i[o+se]=r,0===o&&e._state&&Y(S,e)}function S(e){var t=e._subscribers,n=e._state;if(0!==t.length){for(var r=void 0,i=void 0,o=e._result,a=0;a<t.length;a+=3)r=t[a],i=t[a+n],r?M(n,r,i,o):i(o);e._subscribers.length=0}}function T(){this.error=null}function k(e,t){try{return e(t)}catch(n){return ce.error=n,ce}}function M(e,t,r,i){var o=n(r),a=void 0,s=void 0,u=void 0,c=void 0;if(o){if(a=k(r,i),a===ce?(c=!0,s=a.error,a=null):u=!0,t===a)return void E(t,g())}else a=i,u=!0;t._state!==oe||(o&&u?x(t,a):c?E(t,s):e===ae?P(t,a):e===se&&E(t,a))}function A(e,t){try{t(function(t){x(e,t)},function(t){E(e,t)})}catch(n){E(e,n)}}function I(){return le++}function F(e){e[ie]=le++,e._state=void 0,e._result=void 0,e._subscribers=[]}function N(e,t){this._instanceConstructor=e,this.promise=new e(v),this.promise[ie]||F(this.promise),z(t)?(this._input=t,this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?P(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&P(this.promise,this._result))):E(this.promise,D())}function D(){return new Error("Array Methods must be provided an Array")}function L(e){return new N(this,e).promise}function U(e){var t=this;return new t(z(e)?function(n,r){for(var i=e.length,o=0;o<i;o++)t.resolve(e[o]).then(n,r)}:function(e,t){return t(new TypeError("You must pass an array to race."))})}function H(e){var t=this,n=new t(v);return E(n,e),n}function V(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function q(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function B(e){this[ie]=I(),this._result=this._state=void 0,this._subscribers=[],v!==e&&("function"!=typeof e&&V(),this instanceof B?A(this,e):q())}function W(){var e=void 0;if("undefined"!=typeof o)e=o;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=e.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(t){}if("[object Promise]"===r&&!n.cast)return}e.Promise=B}var K=void 0;K=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var z=K,Q=0,$=void 0,G=void 0,Y=function(e,t){ne[Q]=e,ne[Q+1]=t,Q+=2,2===Q&&(G?G(p):re())},J="undefined"!=typeof window?window:void 0,X=J||{},Z=X.MutationObserver||X.WebKitMutationObserver,ee="undefined"==typeof self&&"undefined"!=typeof i&&"[object process]"==={}.toString.call(i),te="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,ne=new Array(1e3),re=void 0;re=ee?s():Z?c():te?l():void 0===J&&"function"==typeof t?d():f();var ie=Math.random().toString(36).substring(16),oe=void 0,ae=1,se=2,ue=new T,ce=new T,le=0;return N.prototype._enumerate=function(){for(var e=this.length,t=this._input,n=0;this._state===oe&&n<e;n++)this._eachEntry(t[n],n)},N.prototype._eachEntry=function(e,t){var n=this._instanceConstructor,r=n.resolve;if(r===m){var i=b(e);if(i===h&&e._state!==oe)this._settledAt(e._state,t,e._result);else if("function"!=typeof i)this._remaining--,this._result[t]=e;else if(n===B){var o=new n(v);j(o,e,i),this._willSettleAt(o,t)}else this._willSettleAt(new n(function(t){return t(e)}),t)}else this._willSettleAt(r(e),t)},N.prototype._settledAt=function(e,t,n){var r=this.promise;r._state===oe&&(this._remaining--,e===se?E(r,n):this._result[t]=n),0===this._remaining&&P(r,this._result)},N.prototype._willSettleAt=function(e,t){var n=this;O(e,void 0,function(e){return n._settledAt(ae,t,e)},function(e){return n._settledAt(se,t,e)})},B.all=L,B.race=U,B.resolve=m,B.reject=H,B._setScheduler=r,B._setAsap=a,B._asap=Y,B.prototype={constructor:B,then:h,"catch":function(e){return this.then(null,e)}},B.polyfill=W,B.Promise=B,B})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:477}],64:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e; }function o(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!o(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,o,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(n=this._events[e],s(n))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),n.apply(this,o)}else if(a(n))for(o=Array.prototype.slice.call(arguments,1),c=n.slice(),r=c.length,u=0;u<r;u++)c[u].apply(this,o);return!0},r.prototype.addListener=function(e,t){var n;if(!i(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,i(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned&&(n=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,n&&n>0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,o,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],o=n.length,r=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(r<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],i(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],65:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("./src/types/undefined.js"),o=r(i),a=e("./src/types/null.js"),s=r(a),u=e("./src/types/boolean.js"),c=r(u),l=e("./src/types/number.js"),f=r(l),p=e("./src/types/string.js"),d=r(p),h=e("./src/types/function.js"),m=r(h),v=e("./src/types/Array.js"),y=r(v),g=e("./src/types/Object.js"),b=r(g),_=e("./src/OptionsManager.js"),w=r(_);t.exports=function(){return(new w["default"]).registerTypes([o["default"],s["default"],c["default"],f["default"],d["default"],m["default"],y["default"],b["default"]])}},{"./src/OptionsManager.js":68,"./src/types/Array.js":74,"./src/types/Object.js":75,"./src/types/boolean.js":76,"./src/types/function.js":77,"./src/types/null.js":78,"./src/types/number.js":79,"./src/types/string.js":80,"./src/types/undefined.js":81}],66:[function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(n,"__esModule",{value:!0});var i=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}}(),o=function(){function e(t){var n=arguments.length<=1||void 0===arguments[1]?"":arguments[1];r(this,e),this.path=n+"["+t+"]"}return i(e,[{key:"nest",value:function(t){return new e(t,this.path)}},{key:"throw",value:function(e){throw new Error(this.path+" "+e)}}]),e}();n["default"]=o},{}],67:[function(e,t,n){"use strict";function r(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")}Object.defineProperty(n,"__esModule",{value:!0});var o=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=e("lodash/forEach"),s=r(a),u=e("lodash/isNull"),c=r(u),l=e("lodash/isUndefined"),f=r(l),p=e("./Structure.js"),d=r(p),h=function(){function e(t,n){i(this,e),this.name=t,this.options=[],this.errors=[],this.shared=n}return o(e,[{key:"arg",value:function(e,t){if((0,f["default"])(t)&&(t=e,e=null),!(t instanceof d["default"])){var n=(0,c["default"])(e)?"arguments["+this.options.length+"]":e;t=new d["default"](t,this.shared,n)}return this.options.push({name:e,structure:t}),this}},{key:"_legend",value:function(){var e=["<...> Type","* Required"];return this.errors.length>0&&e.push("X Error"),e}},{key:"usage",value:function(){var e=this,t=[];(0,s["default"])(this.options,function(n){var r=n.structure,i=n.name;t.push(r.usage(i,e.errors))});var n=[];if(n.push("Usage:\n "+this.name+"(\n"+t.join(",\n")+"\n )"),this.errors.length>0){var r=this.errors.map(function(e){var t=e.actualPath,n=e.message;return" - `"+t+"` "+n}).join("\n");n.push("Errors:\n"+r)}return n.push("Legend:\n "+this._legend().join("\n ")),"\n"+n.join("\n----------------\n")}},{key:"check",value:function(){var e=this;if(this.errors=[],(0,s["default"])(this.options,function(t){var n=t.structure,r=t.value;n.check(r,e.errors)}),this.errors.length>0)throw new Error(this.usage())}},{key:"values",value:function(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=[];return(0,s["default"])(this.options,function(n,r){n.value=e[r],t.push(n.structure.buildValue(n.value))}),this.check(),t}}]),e}();n["default"]=h},{"./Structure.js":70,"lodash/forEach":409,"lodash/isNull":430,"lodash/isUndefined":438}],68:[function(e,t,n){"use strict";function r(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")}function o(e){return e.toString()}Object.defineProperty(n,"__esModule",{value:!0});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},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}}(),u=e("lodash/isUndefined"),c=r(u),l=e("./ExceptionThrower.js"),f=r(l),p=e("./FunctionChecker.js"),d=r(p),h=e("./Structure.js"),m=r(h),v=e("./TypeCheckerStore.js"),y=r(v),g=e("./TypePrinterStore.js"),b=r(g),_=e("./ValidatorStore.js"),w=r(_),C=function(){function e(){i(this,e),this.thrower=new f["default"]("OptionsManager"),this.typeCheckers=new y["default"](this.thrower),this.typePrinters=new b["default"](this.thrower),this.validators=new w["default"](this.thrower),this._shared={thrower:this.thrower,typeCheckers:this.typeCheckers,typePrinters:this.typePrinters}}return s(e,[{key:"registerType",value:function(e){var t=e.name,n=e.checker,r=e.printer,i=void 0===r?o:r;return this.typeCheckers.add(t,n),this.typePrinters.add(t,i),this}},{key:"registerTypes",value:function(e){return e.forEach(this.registerType,this),this}},{key:"registerValidator",value:function(e){var t=e.name,n=e.validator;return this.validators.add(t,n),this}},{key:"registerValidators",value:function(e){return e.forEach(this.registerValidator,this),this}},{key:"validator",value: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 this.validators.get(e).apply(void 0,n)}},{key:"structure",value:function(e,t){return(0,c["default"])(t)&&(t=e,e=""),new m["default"](t,this._shared,e)}},{key:"check",value:function(e){var t=a({},this._shared,{thrower:this.thrower.nest(".check")});return new d["default"](e,t)}}]),e}();n["default"]=C},{"./ExceptionThrower.js":66,"./FunctionChecker.js":67,"./Structure.js":70,"./TypeCheckerStore.js":71,"./TypePrinterStore.js":72,"./ValidatorStore.js":73,"lodash/isUndefined":438}],69:[function(e,t,n){"use strict";function r(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")}Object.defineProperty(n,"__esModule",{value:!0});var o=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=e("lodash/isFunction"),s=r(a),u=e("lodash/isNull"),c=r(u),l=e("lodash/isString"),f=r(l),p=e("lodash/isUndefined"),d=r(p),h=e("./ExceptionThrower.js"),m=r(h),v=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]?null:arguments[0],n=arguments.length<=1||void 0===arguments[1]?"Store":arguments[1];i(this,e),this.thrower=(0,c["default"])(t)?new m["default"](n):t.nest(n),this.store={}}return o(e,[{key:"get",value:function(e){var t=this.thrower.nest(".get");(0,f["default"])(e)||t["throw"]("Name `"+e+"` should be a string");var n=this.store[e];return(0,d["default"])(n)&&t["throw"]("Name `"+e+"` has no associated function"),n}},{key:"set",value:function(e,t){var n=arguments.length<=2||void 0===arguments[2]?"set":arguments[2],r=this.thrower.nest("."+n);(0,f["default"])(e)||r["throw"]("Name `"+e+"` should be a string"),(0,s["default"])(t)||r["throw"]("Function `"+t+"` should be a function"),this.store[e]=t}},{key:"add",value:function(e,t){this.set(e,t,"add")}}]),e}();n["default"]=v},{"./ExceptionThrower.js":66,"lodash/isFunction":427,"lodash/isNull":430,"lodash/isString":435,"lodash/isUndefined":438}],70:[function(e,t,n){"use strict";function r(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")}Object.defineProperty(n,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},a=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}}(),s=e("lodash/clone"),u=r(s),c=e("lodash/find"),l=r(c),f=e("lodash/forEach"),p=r(f),d=e("lodash/isArray"),h=r(d),m=e("lodash/isFunction"),v=r(m),y=e("lodash/isNumber"),g=r(y),b=e("lodash/isNull"),_=r(b),w=e("lodash/isPlainObject"),C=r(w),j=e("lodash/isString"),x=r(j),R=e("lodash/isUndefined"),P=r(R),E=function(){function e(t,n,r){var o=this,a=arguments.length<=3||void 0===arguments[3]?null:arguments[3],s=!(arguments.length<=4||void 0===arguments[4])&&arguments[4];i(this,e);var u=n.thrower,c=n.typeCheckers,l=n.typePrinters;this.path=r,this.fullPath=""+((0,_["default"])(a)?"":a)+r,(0,P["default"])(t)&&u["throw"]("`"+this.fullPath+"`'s `structure` must be defined"),(0,x["default"])(t.type)||u["throw"]("`"+this.fullPath+"` must have a `type`"),this.types=t.type.split("|"),this.typeCheck=c.check.bind(c,this.types),this.typesStr=this.types.join("|"),this.required=t.required===!0,this.hasValue=t.hasOwnProperty("value")||t.hasOwnProperty("computeValue"),this.value=(t.computeValue||function(){return t.value})(),this.computeValue=t.computeValue,this.hasValue&&(this.valueStr=l.get(this.types[0])(this.value)),this.hasValue&&this.required&&u["throw"]("`"+this.fullPath+"` can't be `required` and have a `value`"),this.validators=t.validators||[],this.isElement=s,this.isElement&&(this.hasValue&&u["throw"]("`"+this.fullPath+"` is an `element`, it can't have a `value`"),this.required&&u["throw"]("`"+this.fullPath+"` is an `element`, it can't be `required`")),this.hasElement=!(0,P["default"])(t.element),this.hasChildren=!(0,P["default"])(t.children),this.hasElement&&this.hasChildren&&u["throw"]("`"+this.fullPath+"`'s structure can't have both `element` and `children`"),this.children=null,this.hasChildren&&(this.children=(0,h["default"])(t.children)?[]:{},(0,p["default"])(t.children,function(r,i){var a=(0,h["default"])(t.children)?"["+i+"]":"."+i;o.children[i]=new e(r,n,a,o.fullPath)})),this.element=null,this.hasElement&&(this.element=new e(t.element,n,"[]",this.fullPath,(!0)))}return a(e,[{key:"buildValue",value:function(e){var t=this;if((0,P["default"])(e)&&this.hasValue)if((0,v["default"])(this.computeValue))e=this.computeValue();else{var n=(0,u["default"])(this.value);e=(0,C["default"])(n)&&!(0,C["default"])(this.value)?this.value:n}return(0,_["default"])(this.children)||(0,p["default"])(this.children,function(t,n){var r=t.buildValue(e[n]);(0,P["default"])(r)||(e[n]=r)}),(0,_["default"])(this.element)||(0,p["default"])(e,function(n,r){e[r]=t.element.buildValue(n)}),e}},{key:"_addError",value:function(e,t,n,r){(0,_["default"])(n)&&(n=""),e.push({actualPath:""+n+(this.isElement?"["+r+"]":this.path),message:t,structurePath:this.isElement?n:this.fullPath})}},{key:"check",value:function(e,t){var n=this,r=arguments.length<=2||void 0===arguments[2]?null:arguments[2],i=arguments.length<=3||void 0===arguments[3]?null:arguments[3],a="undefined"==typeof e?"undefined":o(e);if(this.isElement){var s=this.types.indexOf("undefined")===-1&&this.types.indexOf("any")===-1;if((0,P["default"])(e)&&s)return void this._addError(t,"should be defined",r,i)}if(this.required&&(0,P["default"])(e))return void this._addError(t,"is required",r,i);if(!(0,P["default"])(e)||this.isElement||this.required){if(!this.typeCheck(e)){var u="should be <"+this.typesStr+">, received "+a;return void this._addError(t,u,r,i)}for(var c=0;c<this.validators.length;++c){var l=this.validators[c](e);if(l!==!0)return void this._addError(t,l,r,i)}this.hasChildren&&(0,p["default"])(this.children,function(r,i){r.check(e[i],t,n.fullPath)}),this.hasElement&&(0,p["default"])(e,function(e,r){n.element.check(e,t,n.fullPath,r)})}}},{key:"usage",value:function(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=this,n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],r=arguments.length<=2||void 0===arguments[2]?4:arguments[2],i=new Array(r+1).join(" "),o=this.required?"*":" ",a=(0,l["default"])(n,{structurePath:this.fullPath})?"X":" ",s=o+a+i.substring(0,i.length-2),u=!(0,P["default"])(e)&&!(0,_["default"])(e)&&!(0,g["default"])(e);u||(e="");var c=""+s+e+"<"+this.typesStr+">";return(0,_["default"])(this.children)&&(0,_["default"])(this.element)||!u||(c+=": "),(0,_["default"])(this.children)||!function(){var e=(0,h["default"])(t.children);c+=e?"[":"{",c+="\n";var o=[];(0,p["default"])(t.children,function(e,t){o.push(e.usage(t,n,r+2))}),c+=o.join(",\n"),c+="\n"+i,c+=e?"]":"}"}(),(0,_["default"])(this.element)||(c+="["+this.element.usage(null,n,r).substr(r)+"]"),this.hasValue&&(c+=" = "+this.valueStr),c}}]),e}();n["default"]=E},{"lodash/clone":397,"lodash/find":406,"lodash/forEach":409,"lodash/isArray":420,"lodash/isFunction":427,"lodash/isNull":430,"lodash/isNumber":431,"lodash/isPlainObject":434,"lodash/isString":435,"lodash/isUndefined":438}],71:[function(e,t,n){"use strict";function r(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")}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 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(n,"__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}}(),u=e("lodash/isArray"),c=r(u),l=e("./Store.js"),f=r(l),p=function(e){function t(e){return i(this,t),o(this,Object.getPrototypeOf(t).call(this,e,"TypeCheckerStore"))}return a(t,e),s(t,[{key:"check",value:function(e,t){var n=this,r=this.thrower.nest(".check");(0,c["default"])(e)||r["throw"]("Types `"+e+"` should be an array"),0===e.length&&r["throw"]("Types `[]` must have at least one element");var i=!1;return e.forEach(function(e){n.get(e)(t)&&(i=!0)}),i}}]),t}(f["default"]);n["default"]=p},{"./Store.js":69,"lodash/isArray":420}],72:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!0});var s=e("./Store.js"),u=r(s),c=function(e){function t(e){return i(this,t),o(this,Object.getPrototypeOf(t).call(this,e,"TypePrinterStore"))}return a(t,e),t}(u["default"]);n["default"]=c},{"./Store.js":69}],73:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!0});var s=e("./Store.js"),u=r(s),c=function(e){function t(e){return i(this,t),o(this,Object.getPrototypeOf(t).call(this,e,"ValidatorStore"))}return a(t,e),t}(u["default"]);n["default"]=c},{"./Store.js":69}],74:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isArray"),o=r(i);t.exports={name:"Array",checker:o["default"],printer:JSON.stringify}},{"lodash/isArray":420}],75:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isPlainObject"),o=r(i);t.exports={name:"Object",checker:o["default"],printer:JSON.stringify}},{"lodash/isPlainObject":434}],76:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isBoolean"),o=r(i);t.exports={name:"boolean",checker:o["default"],printer:JSON.stringify}},{"lodash/isBoolean":423}],77:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isFunction"),o=r(i);t.exports={name:"function",checker:o["default"],printer:function(e){var t=e.name||"anonymous",n=e.length?e.length+" argument"+(e.length>1?"s":""):"";return t+"("+n+")"}}},{"lodash/isFunction":427}],78:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isNull"),o=r(i);t.exports={name:"null",checker:o["default"],printer:function(){return"null"}}},{"lodash/isNull":430}],79:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isNumber"),o=r(i);t.exports={name:"number",checker:o["default"],printer:JSON.stringify}},{"lodash/isNumber":431}],80:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isString"),o=r(i);t.exports={name:"string",checker:o["default"],printer:JSON.stringify}},{"lodash/isString":435}],81:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("lodash/isUndefined"),o=r(i);t.exports={name:"undefined",checker:o["default"],printer:function(){return"undefined"}}},{"lodash/isUndefined":438}],82:[function(e,t,n){"use strict";var r=e("./emptyFunction"),i={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=i},{"./emptyFunction":89}],83:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),i={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=i},{}],84:[function(e,t,n){"use strict";function r(e){return e.replace(i,function(e,t){return t.toUpperCase()})}var i=/-(.)/g;t.exports=r},{}],85:[function(e,t,n){"use strict";function r(e){return i(e.replace(o,"ms-"))}var i=e("./camelize"),o=/^-ms-/;t.exports=r},{"./camelize":84}],86:[function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!i(e)&&(i(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var i=e("./isTextNode");t.exports=r},{"./isTextNode":99}],87:[function(e,t,n){"use strict";function r(e){var t=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?a(!1):void 0,"number"!=typeof t?a(!1):void 0,0===t||t-1 in e?void 0:a(!1),"function"==typeof e.callee?a(!1):void 0,e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;i<t;i++)r[i]=e[i];return r}function i(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function o(e){return i(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=e("./invariant");t.exports=o},{"./invariant":97}],88:[function(e,t,n){"use strict";function r(e){var t=e.match(l);return t&&t[1].toLowerCase()}function i(e,t){var n=c;c?void 0:u(!1);var i=r(e),o=i&&s(i);if(o){n.innerHTML=o[1]+e+o[2];for(var l=o[0];l--;)n=n.lastChild}else n.innerHTML=e;var f=n.getElementsByTagName("script");f.length&&(t?void 0:u(!1),a(f).forEach(t));for(var p=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return p}var o=e("./ExecutionEnvironment"),a=e("./createArrayFromMixed"),s=e("./getMarkupWrap"),u=e("./invariant"),c=o.canUseDOM?document.createElement("div"):null,l=/^\s*<(\w+)/;t.exports=i},{"./ExecutionEnvironment":83,"./createArrayFromMixed":87,"./getMarkupWrap":93,"./invariant":97}],89:[function(e,t,n){"use strict";function r(e){return function(){return e}}var i=function(){};i.thatReturns=r,i.thatReturnsFalse=r(!1),i.thatReturnsTrue=r(!0),i.thatReturnsNull=r(null),i.thatReturnsThis=function(){return this},i.thatReturnsArgument=function(e){return e},t.exports=i},{}],90:[function(e,t,n){"use strict";var r={};t.exports=r},{}],91:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],92:[function(e,t,n){"use strict";function r(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],93:[function(e,t,n){"use strict";function r(e){return a?void 0:o(!1),p.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?p[e]:null}var i=e("./ExecutionEnvironment"),o=e("./invariant"),a=i.canUseDOM?document.createElement("div"):null,s={},u=[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:u,option:u,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:l,th:l},d=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];d.forEach(function(e){p[e]=f,s[e]=!0}),t.exports=r},{"./ExecutionEnvironment":83,"./invariant":97}],94:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],95:[function(e,t,n){"use strict";function r(e){return e.replace(i,"-$1").toLowerCase()}var i=/([A-Z])/g;t.exports=r},{}],96:[function(e,t,n){"use strict";function r(e){return i(e).replace(o,"-ms-")}var i=e("./hyphenate"),o=/^ms-/;t.exports=r},{"./hyphenate":95}],97:[function(e,t,n){"use strict";function r(e,t,n,r,o,a,s,u){if(i(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,o,a,s,u],f=0;c=new Error(t.replace(/%s/g,function(){return l[f++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var i=function(e){};t.exports=r},{}],98:[function(e,t,n){"use strict";function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],99:[function(e,t,n){"use strict";function r(e){return i(e)&&3==e.nodeType}var i=e("./isNode");t.exports=r},{"./isNode":98}],100:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],101:[function(e,t,n){"use strict";var r,i=e("./ExecutionEnvironment");i.canUseDOM&&(r=window.performance||window.msPerformance||window.webkitPerformance),t.exports=r||{}},{"./ExecutionEnvironment":83}],102:[function(e,t,n){"use strict";var r,i=e("./performance");r=i.now?function(){return i.now()}:function(){return Date.now()},t.exports=r},{"./performance":101}],103:[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 i(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),i=Object.keys(t);if(n.length!==i.length)return!1;for(var a=0;a<n.length;a++)if(!o.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;t.exports=i},{}],104:[function(e,t,n){"use strict";var r=e("./emptyFunction"),i=r;t.exports=i},{"./emptyFunction":89}],105:[function(e,t,n){var r=Object.prototype.hasOwnProperty,i=Object.prototype.toString;t.exports=function(e,t,n){if("[object Function]"!==i.call(t))throw new TypeError("iterator must be a function");var o=e.length;if(o===+o)for(var a=0;a<o;a++)t.call(n,e[a],a,e);else for(var s in e)r.call(e,s)&&t.call(n,e[s],s,e)}},{}],106:[function(e,t,n){(function(e){"undefined"!=typeof window?t.exports=window:"undefined"!=typeof e?t.exports=e:"undefined"!=typeof self?t.exports=self:t.exports={}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],107:[function(e,t,n){!function(e){function t(e){"}"===e.n.substr(e.n.length-1)&&(e.n=e.n.substring(0,e.n.length-1))}function n(e){return e.trim?e.trim():e.replace(/^\s*|\s*$/g,"")}function r(e,t,n){if(t.charAt(n)!=e.charAt(0))return!1;for(var r=1,i=e.length;r<i;r++)if(t.charAt(n+r)!=e.charAt(r))return!1;return!0}function i(t,n,r,s){var u=[],c=null,l=null,f=null;for(l=r[r.length-1];t.length>0;){if(f=t.shift(),l&&"<"==l.tag&&!(f.tag in w))throw new Error("Illegal content in < super tag.");if(e.tags[f.tag]<=e.tags.$||o(f,s))r.push(f),f.nodes=i(t,f.tag,r,s);else{if("/"==f.tag){if(0===r.length)throw new Error("Closing tag without opener: /"+f.n);if(c=r.pop(),f.n!=c.n&&!a(f.n,c.n,s))throw new Error("Nesting error: "+c.n+" vs. "+f.n);return c.end=f.i,u}"\n"==f.tag&&(f.last=0==t.length||"\n"==t[0].tag)}u.push(f)}if(r.length>0)throw new Error("missing closing tag: "+r.pop().n);return u}function o(e,t){for(var n=0,r=t.length;n<r;n++)if(t[n].o==e.n)return e.tag="#",!0}function a(e,t,n){for(var r=0,i=n.length;r<i;r++)if(n[r].c==e&&n[r].o==t)return!0}function s(e){var t=[];for(var n in e)t.push('"'+c(n)+'": function(c,p,t,i) {'+e[n]+"}");return"{ "+t.join(",")+" }"}function u(e){var t=[];for(var n in e.partials)t.push('"'+c(n)+'":{name:"'+c(e.partials[n].name)+'", '+u(e.partials[n])+"}");return"partials: {"+t.join(",")+"}, subs: "+s(e.subs)}function c(e){return e.replace(g,"\\\\").replace(m,'\\"').replace(v,"\\n").replace(y,"\\r").replace(b,"\\u2028").replace(_,"\\u2029")}function l(e){return~e.indexOf(".")?"d":"f"}function f(e,t){var n="<"+(t.prefix||""),r=n+e.n+C++;return t.partials[r]={name:e.n,partials:{}},t.code+='t.b(t.rp("'+c(r)+'",c,p,"'+(e.indent||"")+'"));',r}function p(e,t){t.code+="t.b(t.t(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'}function d(e){return"t.b("+e+");"}var h=/\S/,m=/\"/g,v=/\n/g,y=/\r/g,g=/\\/g,b=/\u2028/,_=/\u2029/;e.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},e.scan=function(i,o){function a(){g.length>0&&(b.push({tag:"_t",text:new String(g)}),g="")}function s(){for(var t=!0,n=C;n<b.length;n++)if(t=e.tags[b[n].tag]<e.tags._v||"_t"==b[n].tag&&null===b[n].text.match(h),!t)return!1;return t}function u(e,t){if(a(),e&&s())for(var n,r=C;r<b.length;r++)b[r].text&&((n=b[r+1])&&">"==n.tag&&(n.indent=b[r].text.toString()),b.splice(r,1));else t||b.push({tag:"\n"});_=!1,C=b.length}function c(e,t){var r="="+x,i=e.indexOf(r,t),o=n(e.substring(e.indexOf("=",t)+1,i)).split(" ");return j=o[0],x=o[o.length-1],i+r.length-1}var l=i.length,f=0,p=1,d=2,m=f,v=null,y=null,g="",b=[],_=!1,w=0,C=0,j="{{",x="}}";for(o&&(o=o.split(" "),j=o[0],x=o[1]),w=0;w<l;w++)m==f?r(j,i,w)?(--w,a(),m=p):"\n"==i.charAt(w)?u(_):g+=i.charAt(w):m==p?(w+=j.length-1,y=e.tags[i.charAt(w+1)],v=y?i.charAt(w+1):"_v","="==v?(w=c(i,w),m=f):(y&&w++,m=d),_=w):r(x,i,w)?(b.push({tag:v,n:n(g),otag:j,ctag:x,i:"/"==v?_-j.length:w+x.length}),g="",w+=x.length-1,m=f,"{"==v&&("}}"==x?w++:t(b[b.length-1]))):g+=i.charAt(w);return u(_,!0),b};var w={_t:!0,"\n":!0,$:!0,"/":!0};e.stringify=function(t,n,r){return"{code: function (c,p,i) { "+e.wrapMain(t.code)+" },"+u(t)+"}"};var C=0;e.generate=function(t,n,r){C=0;var i={code:"",subs:{}, partials:{}};return e.walk(t,i),r.asString?this.stringify(i,n,r):this.makeTemplate(i,n,r)},e.wrapMain=function(e){return'var t=this;t.b(i=i||"");'+e+"return t.fl();"},e.template=e.Template,e.makeTemplate=function(e,t,n){var r=this.makePartials(e);return r.code=new Function("c","p","i",this.wrapMain(e.code)),new this.template(r,t,this,n)},e.makePartials=function(e){var t,n={subs:{},partials:e.partials,name:e.name};for(t in n.partials)n.partials[t]=this.makePartials(n.partials[t]);for(t in e.subs)n.subs[t]=new Function("c","p","t","i",e.subs[t]);return n},e.codegen={"#":function(t,n){n.code+="if(t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,0,'+t.i+","+t.end+',"'+t.otag+" "+t.ctag+'")){t.rs(c,p,function(c,p,t){',e.walk(t.nodes,n),n.code+="});c.pop();}"},"^":function(t,n){n.code+="if(!t.s(t."+l(t.n)+'("'+c(t.n)+'",c,p,1),c,p,1,0,0,"")){',e.walk(t.nodes,n),n.code+="};"},">":f,"<":function(t,n){var r={partials:{},code:"",subs:{},inPartial:!0};e.walk(t.nodes,r);var i=n.partials[f(t,n)];i.subs=r.subs,i.partials=r.partials},$:function(t,n){var r={subs:{},code:"",partials:n.partials,prefix:t.n};e.walk(t.nodes,r),n.subs[t.n]=r.code,n.inPartial||(n.code+='t.sub("'+c(t.n)+'",c,p,i);')},"\n":function(e,t){t.code+=d('"\\n"'+(e.last?"":" + i"))},_v:function(e,t){t.code+="t.b(t.v(t."+l(e.n)+'("'+c(e.n)+'",c,p,0)));'},_t:function(e,t){t.code+=d('"'+c(e.text)+'"')},"{":p,"&":p},e.walk=function(t,n){for(var r,i=0,o=t.length;i<o;i++)r=e.codegen[t[i].tag],r&&r(t[i],n);return n},e.parse=function(e,t,n){return n=n||{},i(e,"",[],n.sectionTags||[])},e.cache={},e.cacheKey=function(e,t){return[e,!!t.asString,!!t.disableLambda,t.delimiters,!!t.modelGet].join("||")},e.compile=function(t,n){n=n||{};var r=e.cacheKey(t,n),i=this.cache[r];if(i){var o=i.partials;for(var a in o)delete o[a].instance;return i}return i=this.generate(this.parse(this.scan(t,n.delimiters),t,n),t,n),this.cache[r]=i}}("undefined"!=typeof n?n:Hogan)},{}],108:[function(e,t,n){var r=e("./compiler");r.Template=e("./template").Template,r.template=r.Template,t.exports=r},{"./compiler":107,"./template":109}],109:[function(e,t,n){var r={};!function(e){function t(e,t,n){var r;return t&&"object"==typeof t&&(void 0!==t[e]?r=t[e]:n&&t.get&&"function"==typeof t.get&&(r=t.get(e))),r}function n(e,t,n,r,i,o){function a(){}function s(){}a.prototype=e,s.prototype=e.subs;var u,c=new a;c.subs=new s,c.subsText={},c.buf="",r=r||{},c.stackSubs=r,c.subsText=o;for(u in t)r[u]||(r[u]=t[u]);for(u in r)c.subs[u]=r[u];i=i||{},c.stackPartials=i;for(u in n)i[u]||(i[u]=n[u]);for(u in i)c.partials[u]=i[u];return c}function r(e){return String(null===e||void 0===e?"":e)}function i(e){return e=r(e),l.test(e)?e.replace(o,"&amp;").replace(a,"&lt;").replace(s,"&gt;").replace(u,"&#39;").replace(c,"&quot;"):e}e.Template=function(e,t,n,r){e=e||{},this.r=e.code||this.r,this.c=n,this.options=r||{},this.text=t||"",this.partials=e.partials||{},this.subs=e.subs||{},this.buf=""},e.Template.prototype={r:function(e,t,n){return""},v:i,t:r,render:function(e,t,n){return this.ri([e],t||{},n)},ri:function(e,t,n){return this.r(e,t,n)},ep:function(e,t){var r=this.partials[e],i=t[r.name];if(r.instance&&r.base==i)return r.instance;if("string"==typeof i){if(!this.c)throw new Error("No compiler available.");i=this.c.compile(i,this.options)}if(!i)return null;if(this.partials[e].base=i,r.subs){t.stackText||(t.stackText={});for(key in r.subs)t.stackText[key]||(t.stackText[key]=void 0!==this.activeSub&&t.stackText[this.activeSub]?t.stackText[this.activeSub]:this.text);i=n(i,r.subs,r.partials,this.stackSubs,this.stackPartials,t.stackText)}return this.partials[e].instance=i,i},rp:function(e,t,n,r){var i=this.ep(e,n);return i?i.ri(t,n,r):""},rs:function(e,t,n){var r=e[e.length-1];if(!f(r))return void n(e,t,this);for(var i=0;i<r.length;i++)e.push(r[i]),n(e,t,this),e.pop()},s:function(e,t,n,r,i,o,a){var s;return(!f(e)||0!==e.length)&&("function"==typeof e&&(e=this.ms(e,t,n,r,i,o,a)),s=!!e,!r&&s&&t&&t.push("object"==typeof e?e:t[t.length-1]),s)},d:function(e,n,r,i){var o,a=e.split("."),s=this.f(a[0],n,r,i),u=this.options.modelGet,c=null;if("."===e&&f(n[n.length-2]))s=n[n.length-1];else for(var l=1;l<a.length;l++)o=t(a[l],s,u),void 0!==o?(c=s,s=o):s="";return!(i&&!s)&&(i||"function"!=typeof s||(n.push(c),s=this.mv(s,n,r),n.pop()),s)},f:function(e,n,r,i){for(var o=!1,a=null,s=!1,u=this.options.modelGet,c=n.length-1;c>=0;c--)if(a=n[c],o=t(e,a,u),void 0!==o){s=!0;break}return s?(i||"function"!=typeof o||(o=this.mv(o,n,r)),o):!i&&""},ls:function(e,t,n,i,o){var a=this.options.delimiters;return this.options.delimiters=o,this.b(this.ct(r(e.call(t,i)),t,n)),this.options.delimiters=a,!1},ct:function(e,t,n){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(e,this.options).render(t,n)},b:function(e){this.buf+=e},fl:function(){var e=this.buf;return this.buf="",e},ms:function(e,t,n,r,i,o,a){var s,u=t[t.length-1],c=e.call(u);return"function"==typeof c?!!r||(s=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(c,u,n,s.substring(i,o),a)):c},mv:function(e,t,n){var i=t[t.length-1],o=e.call(i);return"function"==typeof o?this.ct(r(o.call(i)),i,n):o},sub:function(e,t,n,r){var i=this.subs[e];i&&(this.activeSub=e,i(t,n,this,r),this.activeSub=!1)}};var o=/&/g,a=/</g,s=/>/g,u=/\'/g,c=/\"/g,l=/[&<>\"\']/,f=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}}("undefined"!=typeof n?n:r)},{}],110:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],111:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var i=e("./src/lib/main.js"),o=r(i);t.exports=o["default"]},{"./src/lib/main.js":132}],112:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("../Template.js"),p=r(f),d=e("../../lib/utils.js"),h=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"componentWillMount",value:function(){this.handleClick=this.handleClick.bind(this)}},{key:"shouldComponentUpdate",value:function(e){return this.props.url!==e.url||this.props.hasRefinements!==e.hasRefinements}},{key:"handleClick",value:function(e){(0,d.isSpecialClick)(e)||(e.preventDefault(),this.props.clearAll())}},{key:"render",value:function(){var e={hasRefinements:this.props.hasRefinements};return l["default"].createElement("a",{className:this.props.cssClasses.link,href:this.props.url,onClick:this.handleClick},l["default"].createElement(p["default"],s({data:e,templateKey:"link"},this.props.templateProps)))}}]),t}(l["default"].Component);n["default"]=h},{"../../lib/utils.js":136,"../Template.js":127,react:633}],113:[function(e,t,n){"use strict";function r(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")}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 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 s(e){var t={};return void 0!==e.template&&(t.templates={item:e.template}),void 0!==e.transformData&&(t.transformData=e.transformData),t}function u(e,t,n){var r=(0,_["default"])(t);return r.cssClasses=n,void 0!==e.label&&(r.label=e.label),void 0!==r.operator&&(r.displayOperator=r.operator,">="===r.operator&&(r.displayOperator="&ge;"),"<="===r.operator&&(r.displayOperator="&le;")),r}function c(e){return function(t){(0,v.isSpecialClick)(t)||(t.preventDefault(),e())}}Object.defineProperty(n,"__esModule",{value:!0});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},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=e("react"),d=r(p),h=e("../Template.js"),m=r(h),v=e("../../lib/utils.js"),y=e("lodash/map"),g=r(y),b=e("lodash/cloneDeep"),_=r(b),w=e("lodash/isEqual"),C=r(w),j=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),f(t,[{key:"shouldComponentUpdate",value:function(e){return!(0,C["default"])(this.props.refinements,e.refinements)}},{key:"_clearAllElement",value:function(e,t){if(t===e)return d["default"].createElement("a",{className:this.props.cssClasses.clearAll,href:this.props.clearAllURL,onClick:c(this.props.clearAllClick)},d["default"].createElement(m["default"],l({templateKey:"clearAll"},this.props.templateProps)))}},{key:"_refinementElement",value:function(e,t){var n=this.props.attributes[e.attributeName]||{},r=u(n,e,this.props.cssClasses),i=s(n),o=e.attributeName+(e.operator?e.operator:":")+(e.exclude?e.exclude:"")+e.name;return d["default"].createElement("div",{className:this.props.cssClasses.item,key:o},d["default"].createElement("a",{className:this.props.cssClasses.link,href:this.props.clearRefinementURLs[t],onClick:c(this.props.clearRefinementClicks[t])},d["default"].createElement(m["default"],l({data:r,templateKey:"item"},this.props.templateProps,i))))}},{key:"render",value:function(){return d["default"].createElement("div",null,this._clearAllElement("before",this.props.clearAllPosition),d["default"].createElement("div",{className:this.props.cssClasses.list},(0,g["default"])(this.props.refinements,this._refinementElement.bind(this))),this._clearAllElement("after",this.props.clearAllPosition))}}]),t}(d["default"].Component);n["default"]=j},{"../../lib/utils.js":136,"../Template.js":127,"lodash/cloneDeep":398,"lodash/isEqual":426,"lodash/map":442,react:633}],114:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("lodash/map"),p=r(f),d=e("./Template.js"),h=r(d),m=e("lodash/has"),v=r(m),y=e("classnames"),g=r(y),b=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"renderWithResults",value:function(){var e=this,t=(0,p["default"])(this.props.hits,function(t,n){var r=s({},t,{__hitIndex:n});return l["default"].createElement(h["default"],s({data:r,key:r.objectID,rootProps:{className:e.props.cssClasses.item},templateKey:"item"},e.props.templateProps))});return l["default"].createElement("div",{className:this.props.cssClasses.root},t)}},{key:"renderAllResults",value:function(){var e=(0,g["default"])(this.props.cssClasses.root,this.props.cssClasses.allItems);return l["default"].createElement(h["default"],s({data:this.props.results,rootProps:{className:e},templateKey:"allItems"},this.props.templateProps))}},{key:"renderNoResults",value:function(){var e=(0,g["default"])(this.props.cssClasses.root,this.props.cssClasses.empty);return l["default"].createElement(h["default"],s({data:this.props.results,rootProps:{className:e},templateKey:"empty"},this.props.templateProps))}},{key:"render",value:function(){var e=this.props.results.hits.length>0,t=(0,v["default"])(this.props,"templateProps.templates.allItems");return e?t?this.renderAllResults():this.renderWithResults():this.renderNoResults()}}]),t}(l["default"].Component);b.defaultProps={results:{hits:[]}},n["default"]=b},{"./Template.js":127,classnames:59,"lodash/has":412,"lodash/map":442,react:633}],115:[function(e,t,n){"use strict";function r(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")}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 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(n,"__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}}(),u=e("react"),c=r(u),l=e("./Hits.js"),f=r(l),p=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.cssClasses,n=e.hits,r=e.results,i=e.showMore,o=e.showMoreLabel,a=e.templateProps,s=this.props.isLastPage?c["default"].createElement("button",{disabled:!0},o):c["default"].createElement("button",{onClick:i},o);return c["default"].createElement("div",null,c["default"].createElement(f["default"],{cssClasses:t,hits:n,results:r,templateProps:a}),c["default"].createElement("div",{className:t.showmore},s))}}]),t}(c["default"].Component);n["default"]=p},{"./Hits.js":114,react:633}],116:[function(e,t,n){"use strict";function r(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")}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 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(n,"__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}}(),u=e("react"),c=r(u),l=e("lodash/forEach"),f=r(l),p=e("lodash/defaultsDeep"),d=r(p),h=e("../../lib/utils.js"),m=e("./Paginator.js"),v=r(m),y=e("./PaginationLink.js"),g=r(y),b=e("classnames"),_=r(b),w=function(e){function t(e){i(this,t);var n=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,(0,d["default"])(e,t.defaultProps)));return n.handleClick=n.handleClick.bind(n),n}return a(t,e),s(t,[{key:"pageLink",value:function(e){var t=e.label,n=e.ariaLabel,r=e.pageNumber,i=e.additionalClassName,o=void 0===i?null:i,a=e.isDisabled,s=void 0!==a&&a,u=e.isActive,l=void 0!==u&&u,f=e.createURL,p={item:(0,_["default"])(this.props.cssClasses.item,o),link:(0,_["default"])(this.props.cssClasses.link)};s?p.item=(0,_["default"])(p.item,this.props.cssClasses.disabled):l&&(p.item=(0,_["default"])(p.item,this.props.cssClasses.active));var d=f&&!s?f(r):"#";return c["default"].createElement(g["default"],{ariaLabel:n,cssClasses:p,handleClick:this.handleClick,isDisabled:s,key:t+r,label:t,pageNumber:r,url:d})}},{key:"previousPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Previous",additionalClassName:this.props.cssClasses.previous,isDisabled:e.isFirstPage(),label:this.props.labels.previous,pageNumber:e.currentPage-1,createURL:t})}},{key:"nextPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Next",additionalClassName:this.props.cssClasses.next,isDisabled:e.isLastPage(),label:this.props.labels.next,pageNumber:e.currentPage+1,createURL:t})}},{key:"firstPageLink",value:function(e,t){return this.pageLink({ariaLabel:"First",additionalClassName:this.props.cssClasses.first,isDisabled:e.isFirstPage(),label:this.props.labels.first,pageNumber:0,createURL:t})}},{key:"lastPageLink",value:function(e,t){return this.pageLink({ariaLabel:"Last",additionalClassName:this.props.cssClasses.last,isDisabled:e.isLastPage(),label:this.props.labels.last,pageNumber:e.total-1,createURL:t})}},{key:"pages",value:function n(e,t){var r=this,n=[];return(0,f["default"])(e.pages(),function(i){var o=i===e.currentPage;n.push(r.pageLink({ariaLabel:i+1,additionalClassName:r.props.cssClasses.page,isActive:o,label:i+1,pageNumber:i,createURL:t}))}),n}},{key:"handleClick",value:function(e,t){(0,h.isSpecialClick)(t)||(t.preventDefault(),this.props.setCurrentPage(e))}},{key:"render",value:function(){var e=new v["default"]({currentPage:this.props.currentPage,total:this.props.nbPages,padding:this.props.padding}),t=this.props.createURL;return c["default"].createElement("ul",{className:this.props.cssClasses.root},this.props.showFirstLast?this.firstPageLink(e,t):null,this.previousPageLink(e,t),this.pages(e,t),this.nextPageLink(e,t),this.props.showFirstLast?this.lastPageLink(e,t):null)}}]),t}(c["default"].Component);w.defaultProps={nbHits:0,currentPage:0,nbPages:0},n["default"]=w},{"../../lib/utils.js":136,"./PaginationLink.js":117,"./Paginator.js":118,classnames:59,"lodash/defaultsDeep":403,"lodash/forEach":409,react:633}],117:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("lodash/isEqual"),p=r(f),d=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"componentWillMount",value:function(){this.handleClick=this.handleClick.bind(this)}},{key:"shouldComponentUpdate",value:function(e){return!(0,p["default"])(this.props,e)}},{key:"handleClick",value:function(e){this.props.handleClick(this.props.pageNumber,e)}},{key:"render",value:function(){var e=this.props,t=e.cssClasses,n=e.label,r=e.ariaLabel,i=e.url,o=e.isDisabled,a="span",u={className:t.link,dangerouslySetInnerHTML:{__html:n}};o||(a="a",u=s({},u,{"aria-label":r,href:i,onClick:this.handleClick}));var c=l["default"].createElement(a,u);return l["default"].createElement("li",{className:t.item},c)}}]),t}(l["default"].Component);n["default"]=d},{"lodash/isEqual":426,react:633}],118:[function(e,t,n){"use strict";function r(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")}Object.defineProperty(n,"__esModule",{value:!0});var o=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=e("lodash/range"),s=r(a),u=function(){function e(t){i(this,e),this.currentPage=t.currentPage,this.total=t.total,this.padding=t.padding}return o(e,[{key:"pages",value:function(){var e=this.total,t=this.currentPage,n=this.padding,r=this.nbPagesDisplayed(n,e);if(r===e)return(0,s["default"])(0,e);var i=this.calculatePaddingLeft(t,n,e,r),o=r-i,a=t-i,u=t+o;return(0,s["default"])(a,u)}},{key:"nbPagesDisplayed",value:function(e,t){return Math.min(2*e+1,t)}},{key:"calculatePaddingLeft",value:function(e,t,n,r){return e<=t?e:e>=n-t?r-(n-e):t}},{key:"isLastPage",value:function(){return this.currentPage===this.total-1}},{key:"isFirstPage",value:function(){return 0===this.currentPage}}]),e}();n["default"]=u},{"lodash/range":456}],119:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(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 s(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(n,"__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},c=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}}(),l=e("react"),f=r(l),p=e("../Template.js"),d=r(p),h=e("./PriceRangesForm.js"),m=r(h),v=e("classnames"),y=r(v),g=e("lodash/isEqual"),b=r(g),_=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),c(t,[{key:"componentWillMount",value:function(){this.refine=this.refine.bind(this)}},{key:"shouldComponentUpdate",value:function(e){return!(0,b["default"])(this.props.facetValues,e.facetValues)}},{key:"getForm",value:function(){var e=u({currency:this.props.currency},this.props.labels),t=void 0;return t=1===this.props.facetValues.length?{from:void 0!==this.props.facetValues[0].from?this.props.facetValues[0].from:"",to:void 0!==this.props.facetValues[0].to?this.props.facetValues[0].to:""}:{from:"",to:""},f["default"].createElement(m["default"],{cssClasses:this.props.cssClasses,currentRefinement:t,labels:e,refine:this.refine})}},{key:"getItemFromFacetValue",value:function(e){var t=(0,y["default"])(this.props.cssClasses.item,i({},this.props.cssClasses.active,e.isRefined)),n=e.from+"_"+e.to,r=this.refine.bind(this,e.from,e.to),o=u({currency:this.props.currency},e);return f["default"].createElement("div",{className:t,key:n},f["default"].createElement("a",{className:this.props.cssClasses.link,href:e.url,onClick:r},f["default"].createElement(d["default"],u({data:o,templateKey:"item"},this.props.templateProps))))}},{key:"refine",value:function(e,t,n){n.preventDefault(),this.props.refine(e,t)}},{key:"render",value:function(){var e=this;return f["default"].createElement("div",null,f["default"].createElement("div",{className:this.props.cssClasses.list},this.props.facetValues.map(function(t){return e.getItemFromFacetValue(t)})),this.getForm())}}]),t}(f["default"].Component);_.defaultProps={cssClasses:{}},n["default"]=_},{"../Template.js":127,"./PriceRangesForm.js":120,classnames:59,"lodash/isEqual":426,react:633}],120:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(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 s(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(n,"__esModule",{value:!0});var u=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=e("react"),l=r(c),f=function(e){function t(e){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={from:e.currentRefinement.from,to:e.currentRefinement.to},n}return s(t,e),u(t,[{key:"componentWillMount",value:function(){this.handleSubmit=this.handleSubmit.bind(this)}},{key:"componentWillReceiveProps",value:function(e){this.setState({from:e.currentRefinement.from,to:e.currentRefinement.to})}},{key:"getInput",value:function(e){var t=this;return l["default"].createElement("label",{className:this.props.cssClasses.label},l["default"].createElement("span",{className:this.props.cssClasses.currency},this.props.labels.currency," "),l["default"].createElement("input",{className:this.props.cssClasses.input,onChange:function(n){return t.setState(i({},e,n.target.value))},ref:e,type:"number",value:this.state[e]}))}},{key:"handleSubmit",value:function(e){var t=""!==this.refs.from.value?parseInt(this.refs.from.value,10):void 0,n=""!==this.refs.to.value?parseInt(this.refs.to.value,10):void 0;this.props.refine(t,n,e)}},{key:"render",value:function(){var e=this.getInput("from"),t=this.getInput("to"),n=this.handleSubmit;return l["default"].createElement("form",{className:this.props.cssClasses.form,onSubmit:n,ref:"form"},e,l["default"].createElement("span",{className:this.props.cssClasses.separator}," ",this.props.labels.separator," "),t,l["default"].createElement("button",{className:this.props.cssClasses.button,type:"submit"},this.props.labels.button))}}]),t}(l["default"].Component);f.defaultProps={cssClasses:{},labels:{}},n["default"]=f},{react:633}],121:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(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 s(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(n,"__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},c=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}}(),l=e("react"),f=r(l),p=e("classnames"),d=r(p),h=e("../../lib/utils.js"),m=e("../Template.js"),v=r(m),y=e("./RefinementListItem.js"),g=r(y),b=e("lodash/isEqual"),_=r(b),w=e("../SearchBox"),C=r(w),j=function(e){function t(e){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={isShowMoreOpen:!1},n.handleItemClick=n.handleItemClick.bind(n),n.handleClickShowMore=n.handleClickShowMore.bind(n),n}return s(t,e),c(t,[{key:"shouldComponentUpdate",value:function(e,t){var n=t!==this.state,r=!(0,_["default"])(this.props.facetValues,e.facetValues),i=n||r;return i}},{key:"refine",value:function(e,t){this.props.toggleRefinement(e,t)}},{key:"_generateFacetItem",value:function(e){var n=void 0,r=e.data&&e.data.length>0;r&&(n=f["default"].createElement(t,u({},this.props,{depth:this.props.depth+1,facetValues:e.data})));var o=this.props.createURL(e[this.props.attributeNameKey]),a=u({},e,{url:o,cssClasses:this.props.cssClasses}),s=(0,d["default"])(this.props.cssClasses.item,i({},this.props.cssClasses.active,e.isRefined)),c=e[this.props.attributeNameKey];return void 0!==e.isRefined&&(c+="/"+e.isRefined),void 0!==e.count&&(c+="/"+e.count),f["default"].createElement(g["default"],{facetValueToRefine:e[this.props.attributeNameKey],handleClick:this.handleItemClick,isRefined:e.isRefined,itemClassName:s,key:c,subItems:n,templateData:a,templateKey:"item",templateProps:this.props.templateProps})}},{key:"handleItemClick",value:function(e){var t=e.facetValueToRefine,n=e.originalEvent,r=e.isRefined;if(!(0,h.isSpecialClick)(n)){if("INPUT"===n.target.tagName)return void this.refine(t,r);for(var i=n.target;i!==n.currentTarget;){if("LABEL"===i.tagName&&(i.querySelector('input[type="checkbox"]')||i.querySelector('input[type="radio"]')))return;"A"===i.tagName&&i.href&&n.preventDefault(),i=i.parentNode}n.stopPropagation(),this.refine(t,r)}}},{key:"handleClickShowMore",value:function(){var e=!this.state.isShowMoreOpen;this.setState({isShowMoreOpen:e})}},{key:"componentWillReceiveProps",value:function(e){this.searchbox&&!e.isFromSearch&&this.searchbox.clearInput()}},{key:"refineFirstValue",value:function(){ var e=this.props.facetValues[0];if(e){var t=e[this.props.attributeNameKey];this.props.toggleRefinement(t)}}},{key:"render",value:function(){var e=this,t=[this.props.cssClasses.list];this.props.cssClasses.depth&&t.push(""+this.props.cssClasses.depth+this.props.depth);var n=this.state.isShowMoreOpen?this.props.limitMax:this.props.limitMin,r=this.props.facetValues.slice(0,n),i=this.props.showMore===!0&&this.props.facetValues.length>r.length||this.state.isShowMoreOpen&&r.length>this.props.limitMin,o=i?f["default"].createElement(v["default"],u({rootProps:{onClick:this.handleClickShowMore},templateKey:"show-more-"+(this.state.isShowMoreOpen?"active":"inactive")},this.props.templateProps)):void 0,a=this.props.searchFacetValues?f["default"].createElement(C["default"],{ref:function(t){e.searchbox=t},placeholder:this.props.searchPlaceholder,onChange:this.props.searchFacetValues,onValidate:function(){return e.refineFirstValue()}}):null,s=this.props.searchFacetValues&&this.props.isFromSearch&&0===this.props.facetValues.length?f["default"].createElement(v["default"],u({templateKey:"noResults"},this.props.templateProps)):null;return f["default"].createElement("div",{className:(0,d["default"])(t)},a,r.map(this._generateFacetItem,this),s,o)}}]),t}(f["default"].Component);j.defaultProps={cssClasses:{},depth:0,attributeNameKey:"name"},n["default"]=j},{"../../lib/utils.js":136,"../SearchBox":123,"../Template.js":127,"./RefinementListItem.js":122,classnames:59,"lodash/isEqual":426,react:633}],122:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("../Template.js"),p=r(f),d=e("lodash/isEqual"),h=r(d),m=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"componentWillMount",value:function(){this.handleClick=this.handleClick.bind(this)}},{key:"shouldComponentUpdate",value:function(e){return!(0,h["default"])(this.props,e)}},{key:"handleClick",value:function(e){this.props.handleClick({facetValueToRefine:this.props.facetValueToRefine,isRefined:this.props.isRefined,originalEvent:e})}},{key:"render",value:function(){return l["default"].createElement("div",{className:this.props.itemClassName,onClick:this.handleClick},l["default"].createElement(p["default"],s({data:this.props.templateData,templateKey:this.props.templateKey},this.props.templateProps)),this.props.subItems)}}]),t}(l["default"].Component);n["default"]=m},{"../Template.js":127,"lodash/isEqual":426,react:633}],123:[function(e,t,n){"use strict";function r(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")}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 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(n,"__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}}(),u=e("react"),c=r(u),l=c["default"].createElement("symbol",{xmlns:"http://www.w3.org/2000/svg",id:"sbx-icon-search-12",viewBox:"0 0 40 41"},c["default"].createElement("path",{d:"M30.967 27.727l-.03-.03c-.778-.777-2.038-.777-2.815 0l-1.21 1.21c-.78.78-.778 2.04 0 2.817l.03.03 4.025-4.027zm1.083 1.084L39.24 36c.778.778.78 2.037 0 2.816l-1.21 1.21c-.777.778-2.038.78-2.816 0l-7.19-7.19 4.026-4.025zM15.724 31.45c8.684 0 15.724-7.04 15.724-15.724C31.448 7.04 24.408 0 15.724 0 7.04 0 0 7.04 0 15.724c0 8.684 7.04 15.724 15.724 15.724zm0-3.93c6.513 0 11.793-5.28 11.793-11.794 0-6.513-5.28-11.793-11.793-11.793C9.21 3.93 3.93 9.21 3.93 15.725c0 6.513 5.28 11.793 11.794 11.793z",fillRule:"evenodd"})),f=c["default"].createElement("symbol",{xmlns:"http://www.w3.org/2000/svg",id:"sbx-icon-clear-2",viewBox:"0 0 20 20"},c["default"].createElement("path",{d:"M8.96 10L.52 1.562 0 1.042 1.04 0l.522.52L10 8.96 18.438.52l.52-.52L20 1.04l-.52.522L11.04 10l8.44 8.438.52.52L18.96 20l-.522-.52L10 11.04l-8.438 8.44-.52.52L0 18.96l.52-.522L8.96 10z",fillRule:"evenodd"})),p=c["default"].createElement("button",{type:"submit",title:"Submit your search query.",className:"sbx-sffv__submit"},c["default"].createElement("svg",{role:"img","aria-label":"Search"},c["default"].createElement("use",{xlinkHref:"#sbx-icon-search-12"}))),d=c["default"].createElement("button",{type:"reset",title:"Clear the search query.",className:"sbx-sffv__reset"},c["default"].createElement("svg",{role:"img","aria-label":"Reset"},c["default"].createElement("use",{xlinkHref:"#sbx-icon-clear-2"}))),h=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"clearInput",value:function(){this.input&&(this.input.value="")}},{key:"validateSearch",value:function(e){if(e.preventDefault(),this.input){var t=this.input.value;t&&this.props.onValidate()}}},{key:"render",value:function(){var e=this,t=this.props,n=t.placeholder,r=t.onChange;return c["default"].createElement("form",{noValidate:"novalidate",className:"searchbox sbx-sffv",onReset:function(){r("")},onSubmit:function(t){return e.validateSearch(t)}},c["default"].createElement("svg",{xmlns:"http://www.w3.org/2000/svg",style:{display:"none"}},l,f),c["default"].createElement("div",{role:"search",className:"sbx-sffv__wrapper"},c["default"].createElement("input",{type:"search",name:"search",placeholder:n,autoComplete:"off",required:"required",className:"sbx-sffv__input",onChange:function(e){return r(e.target.value)},ref:function(t){e.input=t}}),p,d))}}]),t}(c["default"].Component);n["default"]=h},{react:633}],124:[function(e,t,n){"use strict";function r(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")}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 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(n,"__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}}(),u=e("react"),c=r(u),l=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),s(t,[{key:"componentWillMount",value:function(){this.handleChange=this.handleChange.bind(this)}},{key:"handleChange",value:function(e){this.props.setValue(e.target.value)}},{key:"render",value:function(){var e=this,t=this.props,n=t.currentValue,r=t.options;return c["default"].createElement("select",{className:this.props.cssClasses.root,onChange:this.handleChange,value:n},r.map(function(t){return c["default"].createElement("option",{className:e.props.cssClasses.item,key:t.value,value:t.value},t.label)}))}}]),t}(c["default"].Component);n["default"]=l},{react:633}],125:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("lodash/omit"),p=r(f),d=e("react-nouislider"),h=r(d),m=e("lodash/isEqual"),v=r(m),y="ais-range-slider--",g=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"componentWillMount",value:function(){this.handleChange=this.handleChange.bind(this)}},{key:"shouldComponentUpdate",value:function(e){return!(0,v["default"])(this.props.range,e.range)||!(0,v["default"])(this.props.start,e.start)}},{key:"handleChange",value:function(e,t,n){this.props.onChange(n)}},{key:"render",value:function(){if(this.props.range.min===this.props.range.max)return null;var e=void 0;return e=this.props.pips===!1?void 0:this.props.pips===!0||"undefined"==typeof this.props.pips?{mode:"positions",density:3,values:[0,50,100],stepped:!0}:this.props.pips,l["default"].createElement(h["default"],s({},(0,p["default"])(this.props,["cssClasses"]),{animate:!1,behaviour:"snap",connect:!0,cssPrefix:y,onChange:this.handleChange,pips:e}))}}]),t}(l["default"].Component);n["default"]=g},{"lodash/isEqual":426,"lodash/omit":449,react:633,"react-nouislider":607}],126:[function(e,t,n){"use strict";function r(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")}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 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(n,"__esModule",{value:!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},u=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=e("react"),l=r(c),f=e("../Template.js"),p=r(f),d=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),u(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.nbHits!==e.hits||this.props.processingTimeMS!==e.processingTimeMS}},{key:"render",value:function(){var e={hasManyResults:this.props.nbHits>1,hasNoResults:0===this.props.nbHits,hasOneResult:1===this.props.nbHits,hitsPerPage:this.props.hitsPerPage,nbHits:this.props.nbHits,nbPages:this.props.nbPages,page:this.props.page,processingTimeMS:this.props.processingTimeMS,query:this.props.query,cssClasses:this.props.cssClasses};return l["default"].createElement(p["default"],s({data:e,templateKey:"body"},this.props.templateProps))}}]),t}(l["default"].Component);n["default"]=d},{"../Template.js":127,react:633}],127:[function(e,t,n){"use strict";function r(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")}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 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 s(e,t,n){if(!e)return n;var r=(0,g["default"])(n),i=void 0,o="undefined"==typeof e?"undefined":l(e);if("function"===o)i=e(r);else{if("object"!==o)throw new Error("transformData must be a function or an object, was "+o+" (key : "+t+")");i=e[t]?e[t](r):n}var a="undefined"==typeof i?"undefined":l(i),s="undefined"==typeof n?"undefined":l(n);if(a!==s)throw new Error("`transformData` must return a `"+s+"`, got `"+a+"`.");return i}function u(e){var t=e.templates,n=e.templateKey,r=e.compileOptions,i=e.helpers,o=e.data,a=t[n],s="undefined"==typeof a?"undefined":l(a),u="string"===s,p="function"===s;if(u||p){if(p)return a(o);var d=c(i,r,o),h=f({},o,{helpers:d});return C["default"].compile(a,r).render(h)}throw new Error("Template must be 'string' or 'function', was '"+s+"' (key: "+n+")")}function c(e,t,n){return(0,_["default"])(e,function(e){return(0,v["default"])(function(r){var i=this,o=function(e){return C["default"].compile(e,t).render(i)};return e.call(n,r,o)})})}Object.defineProperty(n,"__esModule",{value:!0}),n.PureTemplate=void 0;var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f=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},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=e("react"),h=r(d),m=e("lodash/curry"),v=r(m),y=e("lodash/cloneDeep"),g=r(y),b=e("lodash/mapValues"),_=r(b),w=e("hogan.js"),C=r(w),j=e("lodash/isEqual"),x=r(j),R=n.PureTemplate=function(e){function t(){return i(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),p(t,[{key:"shouldComponentUpdate",value:function(e){return!(0,x["default"])(this.props.data,e.data)||this.props.templateKey!==e.templateKey}},{key:"render",value:function(){var e=this.props.useCustomCompileOptions[this.props.templateKey],t=e?this.props.templatesConfig.compileOptions:{},n=u({templates:this.props.templates,templateKey:this.props.templateKey,compileOptions:t,helpers:this.props.templatesConfig.helpers,data:this.props.data});return null===n?null:h["default"].isValidElement(n)?h["default"].createElement("div",this.props.rootProps,n):h["default"].createElement("div",f({},this.props.rootProps,{dangerouslySetInnerHTML:{__html:n}}))}}]),t}(h["default"].Component);R.defaultProps={data:{},useCustomCompileOptions:{},templates:{},templatesConfig:{}};var P=function(e){return function(t){var n=void 0===t.data?{}:t.data;return h["default"].createElement(e,f({},t,{data:s(t.transformData,t.templateKey,n)}))}};n["default"]=P(R)},{"hogan.js":108,"lodash/cloneDeep":398,"lodash/curry":401,"lodash/isEqual":426,"lodash/mapValues":444,react:633}],128:[function(e,t,n){"use strict";function r(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")}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 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 s(e){var t=function(t){function n(){return i(this,n),o(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return a(n,t),u(n,[{key:"componentDidMount",value:function(){this._hideOrShowContainer(this.props)}},{key:"componentWillReceiveProps",value:function(e){this.props.shouldAutoHideContainer!==e.shouldAutoHideContainer&&this._hideOrShowContainer(e)}},{key:"shouldComponentUpdate",value:function(e){return e.shouldAutoHideContainer===!1}},{key:"_hideOrShowContainer",value:function(e){var t=p["default"].findDOMNode(this).parentNode;t.style.display=e.shouldAutoHideContainer===!0?"none":""}},{key:"render",value:function(){return l["default"].createElement(e,this.props)}}]),n}(l["default"].Component);return t.displayName=e.name+"-AutoHide",t}Object.defineProperty(n,"__esModule",{value:!0});var u=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=e("react"),l=r(c),f=e("react-dom"),p=r(f);n["default"]=s},{react:633,"react-dom":479}],129:[function(e,t,n){"use strict";function r(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")}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 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 s(e){var t=function(t){function n(e){i(this,n);var t=o(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t.handleHeaderClick=t.handleHeaderClick.bind(t),t.state={collapsed:e.collapsible&&e.collapsible.collapsed},t._cssClasses={root:(0,d["default"])("ais-root",t.props.cssClasses.root),body:(0,d["default"])("ais-body",t.props.cssClasses.body)},t._footerElement=t._getElement({type:"footer"}),t}return a(n,t),c(n,[{key:"_getElement",value:function(e){var t=e.type,n=e.handleClick,r=void 0===n?null:n,i=this.props.templateProps.templates;if(!i||!i[t])return null;var o=(0,d["default"])(this.props.cssClasses[t],"ais-"+t),a=(0,m["default"])(this.props,"headerFooterData."+t);return f["default"].createElement(y["default"],u({},this.props.templateProps,{data:a,rootProps:{className:o,onClick:r},templateKey:t,transformData:null}))}},{key:"handleHeaderClick",value:function(){this.setState({collapsed:!this.state.collapsed})}},{key:"render",value:function(){var t=[this._cssClasses.root];this.props.collapsible&&t.push("ais-root__collapsible"),this.state.collapsed&&t.push("ais-root__collapsed");var n=u({},this._cssClasses,{root:(0,d["default"])(t)}),r=this._getElement({type:"header",handleClick:this.props.collapsible?this.handleHeaderClick:null});return f["default"].createElement("div",{className:n.root},r,f["default"].createElement("div",{className:n.body},f["default"].createElement(e,this.props)),this._footerElement)}}]),n}(f["default"].Component);return t.defaultProps={cssClasses:{},collapsible:!1},t.displayName=e.name+"-HeaderFooter",t}Object.defineProperty(n,"__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},c=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}}(),l=e("react"),f=r(l),p=e("classnames"),d=r(p),h=e("lodash/get"),m=r(h),v=e("../components/Template.js"),y=r(v);n["default"]=s},{"../components/Template.js":127,classnames:59,"lodash/get":411,react:633}],130:[function(e,t,n){"use strict";function r(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")}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 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 s(){return"#"}function u(e){return function(t,n){if(!n.getConfiguration)return t;var r=n.getConfiguration(t,e),i=function o(e,t){return Array.isArray(e)?(0,_["default"])(e,t):(0,x["default"])(e)?(0,g["default"])({},e,t,o):void 0};return(0,g["default"])({},t,r,i)}}Object.defineProperty(n,"__esModule",{value:!0});var 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=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}}(),f=e("algoliasearch/src/browser/builds/algoliasearchLite.js"),p=r(f),d=e("algoliasearch-helper"),h=r(d),m=e("lodash/forEach"),v=r(m),y=e("lodash/mergeWith"),g=r(y),b=e("lodash/union"),_=r(b),w=e("lodash/clone"),C=r(w),j=e("lodash/isPlainObject"),x=r(j),R=e("events"),P=e("./url-sync.js"),E=r(P),O=e("./version.js"),S=r(O),T=e("./createHelpers.js"),k=r(T),M=function(e,t,n){return e(t,n)},A=function(e){function t(e){var n=e.appId,r=void 0===n?null:n,a=e.apiKey,s=void 0===a?null:a,u=e.indexName,l=void 0===u?null:u,f=e.numberLocale,d=e.searchParameters,h=void 0===d?{}:d,m=e.urlSync,v=void 0===m?null:m,y=e.searchFunction,g=e.createAlgoliaClient,b=void 0===g?M:g;i(this,t);var _=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));if(null===r||null===s||null===l){var w="\nUsage: instantsearch({\n appId: 'my_application_id',\n apiKey: 'my_search_api_key',\n indexName: 'my_index_name'\n});";throw new Error(w)}var C=b(p["default"],r,s);return C.addAlgoliaAgent("instantsearch.js "+S["default"]),_.client=C,_.helper=null,_.indexName=l,_.searchParameters=c({},h,{index:l}),_.widgets=[],_.templatesConfig={helpers:(0,k["default"])({numberLocale:f}),compileOptions:{}},y&&(_._searchFunction=y),_.urlSync=v===!0?{}:v,_}return a(t,e),l(t,[{key:"addWidget",value:function(e){if(void 0===e.render&&void 0===e.init)throw new Error("Widget definition missing render or init method");this.widgets.push(e)}},{key:"start",value:function(){var e=this;if(!this.widgets)throw new Error("No widgets were added to instantsearch.js");var t=void 0;if(this.urlSync){var n=(0,E["default"])(this.urlSync);this._createURL=n.createURL.bind(n),this._createAbsoluteURL=function(t){return e._createURL(t,{absolute:!0})},this._onHistoryChange=n.onHistoryChange.bind(n),this.widgets.push(n),t=n.searchParametersFromUrl}else this._createURL=s,this._createAbsoluteURL=s,this._onHistoryChange=function(){};this.searchParameters=this.widgets.reduce(u(t),this.searchParameters);var r=(0,h["default"])(this.client,this.searchParameters.index||this.indexName,this.searchParameters);this._searchFunction&&(this._originalHelperSearch=r.search.bind(r),r.search=this._wrappedSearch.bind(this)),this.helper=r,this._init(r.state,r),r.on("result",this._render.bind(this,r)),r.search()}},{key:"_wrappedSearch",value:function(){var e=(0,C["default"])(this.helper);e.search=this._originalHelperSearch,this._searchFunction(e)}},{key:"createURL",value:function(e){if(!this._createURL)throw new Error("You need to call start() before calling createURL()");return this._createURL(this.helper.state.setQueryParameters(e))}},{key:"_render",value:function(e,t,n){var r=this;(0,v["default"])(this.widgets,function(i){i.render&&i.render({templatesConfig:r.templatesConfig,results:t,state:n,helper:e,createURL:r._createAbsoluteURL})}),this.emit("render")}},{key:"_init",value:function(e,t){var n=this;(0,v["default"])(this.widgets,function(r){r.init&&r.init({state:e,helper:t,templatesConfig:n.templatesConfig,createURL:n._createAbsoluteURL,onHistoryChange:n._onHistoryChange})})}}]),t}(R.EventEmitter);n["default"]=A},{"./createHelpers.js":131,"./url-sync.js":135,"./version.js":137,"algoliasearch-helper":2,"algoliasearch/src/browser/builds/algoliasearchLite.js":27,events:64,"lodash/clone":397,"lodash/forEach":409,"lodash/isPlainObject":434,"lodash/mergeWith":447,"lodash/union":469}],131:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t=e.numberLocale;return{formatNumber:function(e,n){return Number(n(e)).toLocaleString(t)}}}},{}],132:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0}),e("../shams/Object.freeze.js"),e("../shims/Object.getPrototypeOf.js");var i=e("to-factory"),o=r(i),a=e("./InstantSearch.js"),s=r(a),u=e("algoliasearch-helper"),c=r(u),l=e("../widgets/clear-all/clear-all.js"),f=r(l),p=e("../widgets/current-refined-values/current-refined-values.js"),d=r(p),h=e("../widgets/hierarchical-menu/hierarchical-menu.js"),m=r(h),v=e("../widgets/hits/hits.js"),y=r(v),g=e("../widgets/hits-per-page-selector/hits-per-page-selector.js"),b=r(g),_=e("../widgets/infinite-hits/infinite-hits.js"),w=r(_),C=e("../widgets/menu/menu.js"),j=r(C),x=e("../widgets/refinement-list/refinement-list.js"),R=r(x),P=e("../widgets/numeric-refinement-list/numeric-refinement-list.js"),E=r(P),O=e("../widgets/numeric-selector/numeric-selector.js"),S=r(O),T=e("../widgets/pagination/pagination.js"),k=r(T),M=e("../widgets/price-ranges/price-ranges.js"),A=r(M),I=e("../widgets/search-box/search-box.js"),F=r(I),N=e("../widgets/range-slider/range-slider.js"),D=r(N),L=e("../widgets/sort-by-selector/sort-by-selector.js"),U=r(L),H=e("../widgets/star-rating/star-rating.js"),V=r(H),q=e("../widgets/stats/stats.js"),B=r(q),W=e("../widgets/toggle/toggle.js"),K=r(W),z=e("../widgets/analytics/analytics.js"),Q=r(z),$=e("./version.js"),G=r($),Y=(0,o["default"])(s["default"]);Y.widgets={analytics:Q["default"],clearAll:f["default"],currentRefinedValues:d["default"],hierarchicalMenu:m["default"],hits:y["default"],hitsPerPageSelector:b["default"],infiniteHits:w["default"],menu:j["default"],refinementList:R["default"],numericRefinementList:E["default"],numericSelector:S["default"],pagination:k["default"],priceRanges:A["default"],searchBox:F["default"],rangeSlider:D["default"],sortBySelector:U["default"],starRating:V["default"],stats:B["default"],toggle:K["default"]},Y.version=G["default"],Y.createQueryString=c["default"].url.getQueryStringFromState,n["default"]=Y},{"../shams/Object.freeze.js":138,"../shims/Object.getPrototypeOf.js":139,"../widgets/analytics/analytics.js":140,"../widgets/clear-all/clear-all.js":141,"../widgets/current-refined-values/current-refined-values.js":143,"../widgets/hierarchical-menu/hierarchical-menu.js":146,"../widgets/hits-per-page-selector/hits-per-page-selector.js":147,"../widgets/hits/hits.js":149,"../widgets/infinite-hits/infinite-hits.js":151,"../widgets/menu/menu.js":153,"../widgets/numeric-refinement-list/numeric-refinement-list.js":155,"../widgets/numeric-selector/numeric-selector.js":156,"../widgets/pagination/pagination.js":157,"../widgets/price-ranges/price-ranges.js":160,"../widgets/range-slider/range-slider.js":161,"../widgets/refinement-list/refinement-list.js":163,"../widgets/search-box/search-box.js":165,"../widgets/sort-by-selector/sort-by-selector.js":166,"../widgets/star-rating/star-rating.js":169,"../widgets/stats/stats.js":171,"../widgets/toggle/toggle.js":175,"./InstantSearch.js":130,"./version.js":137,"algoliasearch-helper":2,"to-factory":634}],133:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={active:'<a class="ais-show-more ais-show-more__active">Show less</a>',inactive:'<a class="ais-show-more ais-show-more__inactive">Show more</a>'}},{}],134:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e){if(!e)return null;if(e===!0)return u;var t=o({},e);return e.templates||(t.templates=u.templates),e.limit||(t.limit=u.limit),t}Object.defineProperty(n,"__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};n["default"]=i;var a=e("./defaultShowMoreTemplates.js"),s=r(a),u={templates:s["default"],limit:100}},{"./defaultShowMoreTemplates.js":133}],135:[function(e,t,n){"use strict";function r(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")}function o(e){var t=e;return function(){var e=Date.now(),n=e-t;return t=e,n}}function a(e){return s()+window.location.pathname+e}function s(){return window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"")}function u(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.useHash||!1,n=t?j:x;return new R(n,e)}Object.defineProperty(n,"__esModule",{value:!0});var c=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}}(),l=e("algoliasearch-helper"),f=r(l),p=e("../lib/version.js"),d=r(p),h=e("algoliasearch-helper/src/url"),m=r(h),v=e("lodash/isEqual"),y=r(v),g=e("lodash/assign"),b=r(g),_=f["default"].AlgoliaSearchHelper,w=d["default"].split(".")[0],C=!0,j={character:"#",onpopstate:function(e){window.addEventListener("hashchange",e)},pushState:function(e){window.location.assign(a(this.createURL(e)))},createURL:function(e){return window.location.search+this.character+e},readUrl:function(){return window.location.hash.slice(1)}},x={character:"?",onpopstate:function(e){window.addEventListener("popstate",e)},pushState:function(e,t){var n=t.getHistoryState;window.history.pushState(n(),"",a(this.createURL(e)))},createURL:function(e){return this.character+e+document.location.hash},readUrl:function(){return window.location.search.slice(1)}},R=function(){function e(t,n){i(this,e),this.urlUtils=t,this.originalConfig=null, this.timer=o(Date.now()),this.mapping=n.mapping||{},this.getHistoryState=n.getHistoryState||function(){return null},this.threshold=n.threshold||700,this.trackedParameters=n.trackedParameters||["query","attribute:*","index","page","hitsPerPage"],this.searchParametersFromUrl=_.getConfigurationFromQueryString(this.urlUtils.readUrl(),{mapping:this.mapping})}return c(e,[{key:"getConfiguration",value:function(e){return this.originalConfig=(0,f["default"])({addAlgoliaAgent:function(){}},e.index,e).state,this.searchParametersFromUrl}},{key:"render",value:function(e){var t=this,n=e.helper;C&&(C=!1,this.onHistoryChange(this.onPopState.bind(this,n)),n.on("change",function(e){return t.renderURLFromState(e)}))}},{key:"onPopState",value:function(e,t){clearTimeout(this.urlUpdateTimeout);var n=e.getState(this.trackedParameters),r=(0,b["default"])({},this.originalConfig,n);(0,y["default"])(r,t)||e.overrideStateWithoutTriggeringChangeEvent(t).search()}},{key:"renderURLFromState",value:function(e){var t=this,n=this.urlUtils.readUrl(),r=_.getForeignConfigurationInQueryString(n,{mapping:this.mapping});r.is_v=w;var i=m["default"].getQueryStringFromState(e.filter(this.trackedParameters),{moreAttributes:r,mapping:this.mapping,safe:!0});clearTimeout(this.urlUpdateTimeout),this.urlUpdateTimeout=setTimeout(function(){t.urlUtils.pushState(i,{getHistoryState:t.getHistoryState})},this.threshold)}},{key:"createURL",value:function(e,t){var n=t.absolute,r=this.urlUtils.readUrl(),i=e.filter(this.trackedParameters),o=f["default"].url.getUnrecognizedParametersInQueryString(r,{mapping:this.mapping});o.is_v=w;var s=this.urlUtils.createURL(f["default"].url.getQueryStringFromState(i,{mapping:this.mapping}));return n?a(s):s}},{key:"onHistoryChange",value:function(e){var t=this;this.urlUtils.onpopstate(function(){var n=t.urlUtils.readUrl(),r=_.getConfigurationFromQueryString(n,{mapping:t.mapping}),i=(0,b["default"])({},t.originalConfig,r);e(i)})}}]),e}();n["default"]=u},{"../lib/version.js":137,"algoliasearch-helper":2,"algoliasearch-helper/src/url":19,"lodash/assign":394,"lodash/isEqual":426}],136:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(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 o(e){var t="string"==typeof e,n=void 0;if(n=t?document.querySelector(e):e,!a(n)){var r="Container must be `string` or `HTMLElement`.";throw t&&(r+=" Unable to find "+e),new Error(r)}return n}function a(e){return e instanceof window.HTMLElement||Boolean(e)&&e.nodeType>0}function s(e){var t=1===e.button;return t||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey}function u(e){return function(t,n){return t&&!n?e+"--"+t:t&&n?e+"--"+t+"__"+n:!t&&n?e+"__"+n:e}}function c(e){var t=e.transformData,n=e.defaultTemplates,r=e.templates,i=e.templatesConfig,o=l(n,r);return g({transformData:t,templatesConfig:i},o)}function l(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,M["default"])([].concat(i((0,T["default"])(e)),i((0,T["default"])(t))));return(0,_["default"])(n,function(n,r){var i=e[r],o=t[r],a=void 0!==o&&o!==i;return n.templates[r]=a?o:i,n.useCustomCompileOptions[r]=a,n},{templates:{},useCustomCompileOptions:{}})}function f(e,t,n,r,i){var o={type:t,attributeName:n,name:r},a=(0,x["default"])(i,{name:n}),s=void 0;if("hierarchical"===t){var u=e.getHierarchicalFacetByName(n),c=r.split(u.separator);o.name=c[c.length-1];for(var l=0;void 0!==a&&l<c.length;++l)a=(0,x["default"])(a.data,{name:c[l]});s=(0,P["default"])(a,"count")}else s=(0,P["default"])(a,'data["'+o.name+'"]');var f=(0,P["default"])(a,"exhaustive");return void 0!==s&&(o.count=s),void 0!==f&&(o.exhaustive=f),o}function p(e,t){var n=[];return(0,C["default"])(t.facetsRefinements,function(r,i){(0,C["default"])(r,function(r){n.push(f(t,"facet",i,r,e.facets))})}),(0,C["default"])(t.facetsExcludes,function(e,t){(0,C["default"])(e,function(e){n.push({type:"exclude",attributeName:t,name:e,exclude:!0})})}),(0,C["default"])(t.disjunctiveFacetsRefinements,function(r,i){(0,C["default"])(r,function(r){n.push(f(t,"disjunctive",i,y(r),e.disjunctiveFacets))})}),(0,C["default"])(t.hierarchicalFacetsRefinements,function(r,i){(0,C["default"])(r,function(r){n.push(f(t,"hierarchical",i,r,e.hierarchicalFacets))})}),(0,C["default"])(t.numericRefinements,function(e,t){(0,C["default"])(e,function(e,r){(0,C["default"])(e,function(e){n.push({type:"numeric",attributeName:t,name:""+e,numericValue:e,operator:r})})})}),(0,C["default"])(t.tagRefinements,function(e){n.push({type:"tag",attributeName:"_tags",name:e})}),n}function d(e,t){var n=e;return(0,O["default"])(t)?(n=n.clearTags(),n=n.clearRefinements()):((0,C["default"])(t,function(e){n="_tags"===e?n.clearTags():n.clearRefinements(e)}),n)}function h(e,t){e.setState(d(e.state,t)).search()}function m(e,t){if(t)return(0,I["default"])(t,function(t,n){return e+n})}function v(e){return"number"==typeof e&&e<0&&(e=String(e).replace(/^-/,"\\-")),e}function y(e){return String(e).replace(/^\\-/,"-")}Object.defineProperty(n,"__esModule",{value:!0}),n.unescapeRefinement=n.escapeRefinement=n.prefixKeys=n.clearRefinementsAndSearch=n.clearRefinementsFromState=n.getRefinements=n.isDomElement=n.isSpecialClick=n.prepareTemplateProps=n.bemHelper=n.getContainerNode=void 0;var g=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},b=e("lodash/reduce"),_=r(b),w=e("lodash/forEach"),C=r(w),j=e("lodash/find"),x=r(j),R=e("lodash/get"),P=r(R),E=e("lodash/isEmpty"),O=r(E),S=e("lodash/keys"),T=r(S),k=e("lodash/uniq"),M=r(k),A=e("lodash/mapKeys"),I=r(A);n.getContainerNode=o,n.bemHelper=u,n.prepareTemplateProps=c,n.isSpecialClick=s,n.isDomElement=a,n.getRefinements=p,n.clearRefinementsFromState=d,n.clearRefinementsAndSearch=h,n.prefixKeys=m,n.escapeRefinement=v,n.unescapeRefinement=y},{"lodash/find":406,"lodash/forEach":409,"lodash/get":411,"lodash/isEmpty":425,"lodash/keys":439,"lodash/mapKeys":443,"lodash/reduce":457,"lodash/uniq":470}],137:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]="1.11.1"},{}],138:[function(e,t,n){"use strict";Object.freeze||(Object.freeze=function(e){if(Object(e)!==e)throw new TypeError("Object.freeze can only be called on Objects.");return e})},{}],139:[function(e,t,n){"use strict";var r={};Object.setPrototypeOf||r.__proto__||!function(){var e=Object.getPrototypeOf;Object.getPrototypeOf=function(t){return t.__proto__?t.__proto__:e.call(Object,t)}}()},{}],140:[function(e,t,n){"use strict";function r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.pushFunction,n=e.delay,r=void 0===n?3e3:n,o=e.triggerOnUIInteraction,a=void 0!==o&&o,s=e.pushInitialSearch,u=void 0===s||s;if(!t)throw new Error(i);var c=null,l=function(e){var t=[];for(var n in e)if(e.hasOwnProperty(n)){var r=e[n].join("+");t.push(encodeURIComponent(n)+"="+encodeURIComponent(n)+"_"+encodeURIComponent(r))}return t.join("&")},f=function(e){var t=[];for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];if(r.hasOwnProperty(">=")&&r.hasOwnProperty("<="))r[">="][0]===r["<="][0]?t.push(n+"="+n+"_"+r[">="]):t.push(n+"="+n+"_"+r[">="]+"to"+r["<="]);else if(r.hasOwnProperty(">="))t.push(n+"="+n+"_from"+r[">="]);else if(r.hasOwnProperty("<="))t.push(n+"="+n+"_to"+r["<="]);else if(r.hasOwnProperty("=")){var i=[];for(var o in r["="])r["="].hasOwnProperty(o)&&i.push(r["="][o]);t.push(n+"="+n+"_"+i.join("-"))}}return t.join("&")},p="",d=function(e){if(null!==e){var n=[],r=l(Object.assign({},e.state.disjunctiveFacetsRefinements,e.state.facetsRefinements,e.state.hierarchicalFacetsRefinements)),i=f(e.state.numericRefinements);""!==r&&n.push(r),""!==i&&n.push(i),n=n.join("&");var o="Query: "+e.state.query+", "+n;p!==o&&(t(n,e.state,e.results),p=o)}},h=void 0,m=!0;return u===!0&&(m=!1),{init:function(){a===!0&&(document.addEventListener("click",function(){d(c)}),window.addEventListener("beforeunload",function(){d(c)}))},render:function(e){var t=e.results,n=e.state;return m===!0?void(m=!1):(c={results:t,state:n},h&&clearTimeout(h),void(h=setTimeout(function(){return d(c)},r)))}}}Object.defineProperty(n,"__esModule",{value:!0});var i="Usage:\nanalytics({\n pushFunction,\n [ delay=3000 ],\n [ triggerOnUIInteraction=false ],\n [ pushInitialSearch=true ]\n})";n["default"]=r},{}],141:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.templates,r=void 0===n?y["default"]:n,i=e.cssClasses,o=void 0===i?{}:i,s=e.collapsible,l=void 0!==s&&s,p=e.autoHideContainer,h=void 0===p||p,v=e.excludeAttributes,g=void 0===v?[]:v;if(!t)throw new Error(w);var C=(0,c.getContainerNode)(t),j=(0,m["default"])(b["default"]);h===!0&&(j=(0,d["default"])(j));var x={root:(0,f["default"])(_(null),o.root),header:(0,f["default"])(_("header"),o.header),body:(0,f["default"])(_("body"),o.body),footer:(0,f["default"])(_("footer"),o.footer),link:(0,f["default"])(_("link"),o.link)};return{init:function(e){var t=e.helper,n=e.templatesConfig;this.clearAll=this.clearAll.bind(this,t),this._templateProps=(0,c.prepareTemplateProps)({defaultTemplates:y["default"],templatesConfig:n,templates:r})},render:function(e){var t=e.results,n=e.state,r=e.createURL;this.clearAttributes=(0,c.getRefinements)(t,n).map(function(e){return e.attributeName}).filter(function(e){return g.indexOf(e)===-1});var i=0!==this.clearAttributes.length,o=r((0,c.clearRefinementsFromState)(n));u["default"].render(a["default"].createElement(j,{clearAll:this.clearAll,collapsible:l,cssClasses:x,hasRefinements:i,shouldAutoHideContainer:!i,templateProps:this._templateProps,url:o}),C)},clearAll:function(e){this.clearAttributes.length>0&&(0,c.clearRefinementsAndSearch)(e,this.clearAttributes)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("classnames"),f=r(l),p=e("../../decorators/autoHideContainer.js"),d=r(p),h=e("../../decorators/headerFooter.js"),m=r(h),v=e("./defaultTemplates.js"),y=r(v),g=e("../../components/ClearAll/ClearAll.js"),b=r(g),_=(0,c.bemHelper)("ais-clear-all"),w="Usage:\nclearAll({\n container,\n [ cssClasses.{root,header,body,footer,link}={} ],\n [ templates.{header,link,footer}={link: 'Clear all'} ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ excludeAttributes=[] ]\n})";n["default"]=i},{"../../components/ClearAll/ClearAll.js":112,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":142,classnames:59,react:633,"react-dom":479}],142:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",link:"Clear all",footer:""}},{}],143:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e){var t=e.container,n=e.attributes,r=void 0===n?[]:n,i=e.onlyListedAttributes,o=void 0!==i&&i,a=e.clearAll,l=void 0===a?"before":a,p=e.templates,m=void 0===p?q["default"]:p,y=e.collapsible,b=void 0!==y&&y,w=e.transformData,j=e.autoHideContainer,R=void 0===j||j,E=e.cssClasses,S=void 0===E?{}:E,T=(0,x["default"])(r)&&(0,I["default"])(r,function(e,t){return e&&(0,P["default"])(t)&&(0,C["default"])(t.name)&&((0,g["default"])(t.label)||(0,C["default"])(t.label))&&((0,g["default"])(t.template)||(0,C["default"])(t.template)||(0,O["default"])(t.template))&&((0,g["default"])(t.transformData)||(0,O["default"])(t.transformData))},!0),k=["header","item","clearAll","footer"],A=(0,P["default"])(m)&&(0,I["default"])(m,function(e,t,n){return e&&k.indexOf(n)!==-1&&((0,C["default"])(t)||(0,O["default"])(t))},!0),F=["root","header","body","clearAll","list","item","link","count","footer"],N=(0,P["default"])(S)&&(0,I["default"])(S,function(e,t,n){return e&&F.indexOf(n)!==-1&&(0,C["default"])(t)||(0,x["default"])(t)},!0),D=(0,g["default"])(w)||(0,O["default"])(w)||(0,P["default"])(w)&&(0,O["default"])(w.item),U=!(((0,C["default"])(t)||(0,h.isDomElement)(t))&&(0,x["default"])(r)&&T&&(0,_["default"])(o)&&[!1,"before","after"].indexOf(l)!==-1&&(0,P["default"])(m)&&A&&D&&(0,_["default"])(R)&&N);if(U)throw new Error(z);var V=(0,h.getContainerNode)(t),B=(0,L["default"])(W["default"]);R===!0&&(B=(0,H["default"])(B));var Q=(0,M["default"])(r,function(e){return e.name}),$=o?Q:[],G=(0,I["default"])(r,function(e,t){return e[t.name]=t,e},{});return{init:function(e){var t=e.helper;this._clearRefinementsAndSearch=h.clearRefinementsAndSearch.bind(null,t,$)},render:function(e){var t=e.results,n=e.helper,r=e.state,i=e.templatesConfig,a=e.createURL,p={root:(0,v["default"])(K(null),S.root),header:(0,v["default"])(K("header"),S.header),body:(0,v["default"])(K("body"),S.body),clearAll:(0,v["default"])(K("clear-all"),S.clearAll),list:(0,v["default"])(K("list"),S.list),item:(0,v["default"])(K("item"),S.item),link:(0,v["default"])(K("link"),S.link),count:(0,v["default"])(K("count"),S.count),footer:(0,v["default"])(K("footer"),S.footer)},y=(0,h.prepareTemplateProps)({transformData:w,defaultTemplates:q["default"],templatesConfig:i,templates:m}),g=a((0,h.clearRefinementsFromState)(r,$)),_=s(t,r,Q,o),C=_.map(function(e){return a(u(r,e))}),j=_.map(function(e){return c.bind(null,n,e)}),x=0===_.length;d["default"].render(f["default"].createElement(B,{attributes:G,clearAllClick:this._clearRefinementsAndSearch,clearAllPosition:l,clearAllURL:g,clearRefinementClicks:j,clearRefinementURLs:C,collapsible:b,cssClasses:p,refinements:_,shouldAutoHideContainer:x,templateProps:y}),V)}}}function o(e,t,n){var r=e.indexOf(n);return r!==-1?r:e.length+t.indexOf(n)}function a(e,t,n,r){var i=o(e,t,n.attributeName),a=o(e,t,r.attributeName);return i===a?n.name===r.name?0:n.name<r.name?-1:1:i<a?-1:1}function s(e,t,n,r){var i=(0,h.getRefinements)(e,t),o=(0,I["default"])(i,function(e,t){return n.indexOf(t.attributeName)===-1&&e.indexOf(t.attributeName===-1)&&e.push(t.attributeName),e},[]);return i=i.sort(a.bind(null,n,o)),r&&!(0,T["default"])(n)&&(i=(0,N["default"])(i,function(e){return n.indexOf(e.attributeName)!==-1})),i}function u(e,t){switch(t.type){case"facet":return e.removeFacetRefinement(t.attributeName,t.name);case"disjunctive":return e.removeDisjunctiveFacetRefinement(t.attributeName,t.name);case"hierarchical":return e.clearRefinements(t.attributeName);case"exclude":return e.removeExcludeRefinement(t.attributeName,t.name);case"numeric":return e.removeNumericRefinement(t.attributeName,t.operator,t.numericValue);case"tag":return e.removeTagRefinement(t.name);default:throw new Error("clearRefinement: type "+t.type+" is not handled")}}function c(e,t){e.setState(u(e.state,t)).search()}Object.defineProperty(n,"__esModule",{value:!0});var l=e("react"),f=r(l),p=e("react-dom"),d=r(p),h=e("../../lib/utils.js"),m=e("classnames"),v=r(m),y=e("lodash/isUndefined"),g=r(y),b=e("lodash/isBoolean"),_=r(b),w=e("lodash/isString"),C=r(w),j=e("lodash/isArray"),x=r(j),R=e("lodash/isPlainObject"),P=r(R),E=e("lodash/isFunction"),O=r(E),S=e("lodash/isEmpty"),T=r(S),k=e("lodash/map"),M=r(k),A=e("lodash/reduce"),I=r(A),F=e("lodash/filter"),N=r(F),D=e("../../decorators/headerFooter.js"),L=r(D),U=e("../../decorators/autoHideContainer"),H=r(U),V=e("./defaultTemplates"),q=r(V),B=e("../../components/CurrentRefinedValues/CurrentRefinedValues.js"),W=r(B),K=(0,h.bemHelper)("ais-current-refined-values"),z="Usage:\ncurrentRefinedValues({\n container,\n [ attributes: [{name[, label, template, transformData]}] ],\n [ onlyListedAttributes = false ],\n [ clearAll = 'before' ] // One of ['before', 'after', false]\n [ templates.{header,item,clearAll,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer = true ],\n [ cssClasses.{root, header, body, clearAll, list, item, link, count, footer} = {} ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/CurrentRefinedValues/CurrentRefinedValues.js":113,"../../decorators/autoHideContainer":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates":144,classnames:59,"lodash/filter":405,"lodash/isArray":420,"lodash/isBoolean":423,"lodash/isEmpty":425,"lodash/isFunction":427,"lodash/isPlainObject":434,"lodash/isString":435,"lodash/isUndefined":438,"lodash/map":442,"lodash/reduce":457,react:633,"react-dom":479}],144:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'{{#label}}{{label}}{{^operator}}:{{/operator}} {{/label}}{{#operator}}{{{displayOperator}}} {{/operator}}{{#exclude}}-{{/exclude}}{{name}} <span class="{{cssClasses.count}}">{{count}}</span>',clearAll:"Clear all",footer:""}},{}],145:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'<a class="{{cssClasses.link}}" href="{{url}}">{{name}} <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span></a>',footer:""}},{}],146:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.attributes,r=e.separator,i=void 0===r?" > ":r,o=e.rootPath,s=void 0===o?null:o,l=e.showParentLevel,p=void 0===l||l,h=e.limit,v=void 0===h?10:h,g=e.sortBy,C=void 0===g?["name:asc"]:g,j=e.cssClasses,x=void 0===j?{}:j,R=e.autoHideContainer,P=void 0===R||R,E=e.templates,O=void 0===E?y["default"]:E,S=e.collapsible,T=void 0!==S&&S,k=e.transformData;if(!t||!n||!n.length)throw new Error(w);var M=(0,c.getContainerNode)(t),A=(0,m["default"])(b["default"]);P===!0&&(A=(0,d["default"])(A));var I=n[0],F={root:(0,f["default"])(_(null),x.root),header:(0,f["default"])(_("header"),x.header),body:(0,f["default"])(_("body"),x.body),footer:(0,f["default"])(_("footer"),x.footer),list:(0,f["default"])(_("list"),x.list),depth:_("list","lvl"),item:(0,f["default"])(_("item"),x.item),active:(0,f["default"])(_("item","active"),x.active),link:(0,f["default"])(_("link"),x.link),count:(0,f["default"])(_("count"),x.count)};return{getConfiguration:function(e){return{hierarchicalFacets:[{name:I,attributes:n,separator:i,rootPath:s,showParentLevel:p}],maxValuesPerFacet:void 0!==e.maxValuesPerFacet?Math.max(e.maxValuesPerFacet,v):v}},init:function(e){var t=e.helper,n=e.templatesConfig;this._toggleRefinement=function(e){return t.toggleRefinement(I,e).search()},this._templateProps=(0,c.prepareTemplateProps)({transformData:k,defaultTemplates:y["default"],templatesConfig:n,templates:O})},_prepareFacetValues:function(e,t){var n=this;return e.slice(0,v).map(function(e){return Array.isArray(e.data)&&(e.data=n._prepareFacetValues(e.data,t)),e})},render:function(e){function t(e){return i(r.toggleRefinement(I,e))}var n=e.results,r=e.state,i=e.createURL,o=n.getFacetValues(I,{sortBy:C}).data||[];o=this._prepareFacetValues(o,r),u["default"].render(a["default"].createElement(A,{attributeNameKey:"path",collapsible:T,createURL:t,cssClasses:F,facetValues:o,shouldAutoHideContainer:0===o.length,templateProps:this._templateProps,toggleRefinement:this._toggleRefinement}),M)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("classnames"),f=r(l),p=e("../../decorators/autoHideContainer.js"),d=r(p),h=e("../../decorators/headerFooter.js"),m=r(h),v=e("./defaultTemplates.js"),y=r(v),g=e("../../components/RefinementList/RefinementList.js"),b=r(g),_=(0,c.bemHelper)("ais-hierarchical-menu"),w="Usage:\nhierarchicalMenu({\n container,\n attributes,\n [ separator=' > ' ],\n [ rootPath ],\n [ showParentLevel=true ],\n [ limit=10 ],\n [ sortBy=['name:asc'] ],\n [ cssClasses.{root , header, body, footer, list, depth, item, active, link}={} ],\n [ templates.{header, item, footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":145,classnames:59,react:633,"react-dom":479}],147:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.options,r=e.cssClasses,i=void 0===r?{}:r,o=e.autoHideContainer,s=void 0!==o&&o,l=n;if(!t||!l)throw new Error(b);var p=(0,c.getContainerNode)(t),h=y["default"];s===!0&&(h=(0,m["default"])(h));var v={root:(0,d["default"])(g(null),i.root),item:(0,d["default"])(g("item"),i.item)};return{init:function(e){var t=e.helper,n=e.state,r=(0,f["default"])(l,function(e){return Number(n.hitsPerPage)===Number(e.value)});r||(void 0===n.hitsPerPage?window.console&&window.console.log("[Warning][hitsPerPageSelector] hitsPerPage not defined.\nYou should probably use a `hits` widget or set the value `hitsPerPage`\nusing the searchParameters attribute of the instantsearch constructor."):window.console&&window.console.log("[Warning][hitsPerPageSelector] No option in `options`\nwith `value: hitsPerPage` (hitsPerPage: "+n.hitsPerPage+")"),l=[{value:void 0,label:""}].concat(l)),this.setHitsPerPage=function(e){return t.setQueryParameter("hitsPerPage",Number(e)).search()}},render:function(e){var t=e.state,n=e.results,r=t.hitsPerPage,i=0===n.nbHits;u["default"].render(a["default"].createElement(h,{cssClasses:v,currentValue:r,options:l,setValue:this.setHitsPerPage,shouldAutoHideContainer:i}),p)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("lodash/some"),f=r(l),p=e("classnames"),d=r(p),h=e("../../decorators/autoHideContainer.js"),m=r(h),v=e("../../components/Selector.js"),y=r(v),g=(0,c.bemHelper)("ais-hits-per-page-selector"),b="Usage:\nhitsPerPageSelector({\n container,\n options,\n [ cssClasses.{root,item}={} ],\n [ autoHideContainer=false ]\n})";n["default"]=i},{"../../components/Selector.js":124,"../../decorators/autoHideContainer.js":128,"../../lib/utils.js":136,classnames:59,"lodash/some":458,react:633,"react-dom":479}],148:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={empty:"No results",item:function(e){return JSON.stringify(e,null,2)}}},{}],149:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.cssClasses,r=void 0===n?{}:n,i=e.templates,o=void 0===i?m["default"]:i,s=e.transformData,l=e.hitsPerPage,p=void 0===l?20:l;if(!t)throw new Error("Must provide a container."+y);if(o.item&&o.allItems)throw new Error("Must contain only allItems OR item template."+y);var h=(0,c.getContainerNode)(t),g={root:(0,f["default"])(v(null),r.root),item:(0,f["default"])(v("item"),r.item),empty:(0,f["default"])(v(null,"empty"),r.empty)};return{getConfiguration:function(){return{hitsPerPage:p}},init:function(e){var t=e.templatesConfig;this._templateProps=(0,c.prepareTemplateProps)({transformData:s,defaultTemplates:m["default"],templatesConfig:t,templates:o})},render:function(e){var t=e.results;u["default"].render(a["default"].createElement(d["default"],{cssClasses:g,hits:t.hits,results:t,templateProps:this._templateProps}),h)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("classnames"),f=r(l),p=e("../../components/Hits.js"),d=r(p),h=e("./defaultTemplates.js"),m=r(h),v=(0,c.bemHelper)("ais-hits"),y="\nUsage:\nhits({\n container,\n [ cssClasses.{root,empty,item}={} ],\n [ templates.{empty,item} | templates.{empty, allItems} ],\n [ transformData.{empty,item} | transformData.{empty, allItems} ],\n [ hitsPerPage=20 ]\n})";n["default"]=i},{"../../components/Hits.js":114,"../../lib/utils.js":136,"./defaultTemplates.js":148,classnames:59,react:633,"react-dom":479}],150:[function(e,t,n){arguments[4][148][0].apply(n,arguments)},{dup:148}],151:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(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 o(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.cssClasses,r=void 0===n?{}:n,o=e.showMoreLabel,a=void 0===o?"Show more results":o,u=e.templates,f=void 0===u?v["default"]:u,d=e.transformData,m=e.hitsPerPage,b=void 0===m?20:m;if(!t)throw new Error("Must provide a container."+g);var _=(0,l.getContainerNode)(t),w={root:(0,p["default"])(y(null),r.root),item:(0,p["default"])(y("item"),r.item),empty:(0,p["default"])(y(null,"empty"),r.empty),showmore:(0,p["default"])(y("showmore"),r.showmore)},C=[],j=function(e){return function(){return e.nextPage().search()}};return{getConfiguration:function(){return{hitsPerPage:b}},init:function(e){var t=e.templatesConfig,n=e.helper;this._templateProps=(0,l.prepareTemplateProps)({transformData:d,defaultTemplates:v["default"],templatesConfig:t,templates:f}),this.showMore=j(n)},render:function(e){var t=e.results,n=e.state;0===n.page&&(C=[]),C=[].concat(i(C),i(t.hits));var r=t.nbPages<=t.page+1;c["default"].render(s["default"].createElement(h["default"],{cssClasses:w,hits:C,results:t,showMore:this.showMore,showMoreLabel:a,isLastPage:r,templateProps:this._templateProps}),_)}}}Object.defineProperty(n,"__esModule",{value:!0});var a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../../lib/utils.js"),f=e("classnames"),p=r(f),d=e("../../components/InfiniteHits.js"),h=r(d),m=e("./defaultTemplates.js"),v=r(m),y=(0,l.bemHelper)("ais-infinite-hits"),g='\nUsage:\ninfiniteHits({\n container,\n [ cssClasses.{root,empty,item}={} ],\n [ templates.{empty,item} | templates.{empty} ],\n [ showMoreLabel="Show more results" ]\n [ transformData.{empty,item} | transformData.{empty} ],\n [ hitsPerPage=20 ]\n})';n["default"]=o},{"../../components/InfiniteHits.js":115,"../../lib/utils.js":136,"./defaultTemplates.js":150,classnames:59,react:633,"react-dom":479}],152:[function(e,t,n){arguments[4][145][0].apply(n,arguments)},{dup:145}],153:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.attributeName,r=e.sortBy,i=void 0===r?["count:desc","name:asc"]:r,a=e.limit,u=void 0===a?10:a,f=e.cssClasses,d=void 0===f?{}:f,m=e.templates,y=void 0===m?_["default"]:m,b=e.collapsible,w=void 0!==b&&b,R=e.transformData,P=e.autoHideContainer,E=void 0===P||P,O=e.showMore,S=void 0!==O&&O,T=(0,g["default"])(S);if(T&&T.limit<u)throw new Error("showMore.limit configuration should be > than the limit in the main configuration");var k=T&&T.limit||u;if(!t||!n)throw new Error(x);var M=(0,l.getContainerNode)(t),A=(0,v["default"])(C["default"]);E===!0&&(A=(0,h["default"])(A));var I=n,F=T&&(0,l.prefixKeys)("show-more-",T.templates),N=F?o({},y,F):y,D={root:(0,p["default"])(j(null),d.root),header:(0,p["default"])(j("header"),d.header),body:(0,p["default"])(j("body"),d.body),footer:(0,p["default"])(j("footer"),d.footer),list:(0,p["default"])(j("list"),d.list),item:(0,p["default"])(j("item"),d.item),active:(0,p["default"])(j("item","active"),d.active),link:(0,p["default"])(j("link"),d.link),count:(0,p["default"])(j("count"),d.count)};return{getConfiguration:function(e){var t={hierarchicalFacets:[{name:I,attributes:[n]}]},r=e.maxValuesPerFacet||0;return t.maxValuesPerFacet=Math.max(r,k),t},init:function(e){var t=e.templatesConfig,n=e.helper,r=e.createURL;this._templateProps=(0,l.prepareTemplateProps)({transformData:R,defaultTemplates:_["default"],templatesConfig:t,templates:N}),this._createURL=function(e,t){return r(e.toggleRefinement(I,t))},this._toggleRefinement=function(e){return n.toggleRefinement(I,e).search()}},_prepareFacetValues:function(e,t){var n=this;return e.map(function(e){return e.url=n._createURL(t,e),e})},render:function(e){function t(e){return a(o.toggleRefinement(n,e))}var r=e.results,o=e.state,a=e.createURL,l=r.getFacetValues(I,{sortBy:i}).data||[];l=this._prepareFacetValues(l,o),c["default"].render(s["default"].createElement(A,{collapsible:w,createURL:t,cssClasses:D,facetValues:l,limitMax:k,limitMin:u,shouldAutoHideContainer:0===l.length,showMore:null!==T,templateProps:this._templateProps,toggleRefinement:this._toggleRefinement}),M)}}}Object.defineProperty(n,"__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},a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../../lib/utils.js"),f=e("classnames"),p=r(f),d=e("../../decorators/autoHideContainer.js"),h=r(d),m=e("../../decorators/headerFooter.js"),v=r(m),y=e("../../lib/show-more/getShowMoreConfig.js"),g=r(y),b=e("./defaultTemplates.js"),_=r(b),w=e("../../components/RefinementList/RefinementList.js"),C=r(w),j=(0,l.bemHelper)("ais-menu"),x="Usage:\nmenu({\n container,\n attributeName,\n [ sortBy=['count:desc', 'name:asc'] ],\n [ limit=10 ],\n [ cssClasses.{root,list,item} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer ],\n [ showMore.{templates: {active, inactive}, limit} ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/show-more/getShowMoreConfig.js":134,"../../lib/utils.js":136,"./defaultTemplates.js":152,classnames:59,react:633,"react-dom":479}],154:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="radio" class="{{cssClasses.radio}}" name="{{attributeName}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n</label>',footer:""}},{}],155:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e){var t=e.container,n=e.attributeName,r=e.options,i=e.cssClasses,s=void 0===i?{}:i,c=e.templates,f=void 0===c?R["default"]:c,h=e.collapsible,v=void 0!==h&&h,y=e.transformData,g=e.autoHideContainer,b=void 0===g||g;if(!t||!n||!r)throw new Error(S);var _=(0,d.getContainerNode)(t),C=(0,j["default"])(E["default"]);b===!0&&(C=(0,w["default"])(C));var x={root:(0,m["default"])(O(null),s.root),header:(0,m["default"])(O("header"),s.header),body:(0,m["default"])(O("body"),s.body),footer:(0,m["default"])(O("footer"),s.footer),list:(0,m["default"])(O("list"),s.list),item:(0,m["default"])(O("item"),s.item),label:(0,m["default"])(O("label"),s.label),radio:(0,m["default"])(O("radio"),s.radio),active:(0,m["default"])(O("item","active"),s.active)};return{init:function(e){var t=e.templatesConfig,i=e.helper;this._templateProps=(0,d.prepareTemplateProps)({transformData:y,defaultTemplates:R["default"],templatesConfig:t,templates:f}),this._toggleRefinement=function(e){var t=a(i.state,n,r,e);i.setState(t).search()}},render:function(e){function t(e){return c(a(s,n,r,e))}var i=e.results,s=e.state,c=e.createURL,f=r.map(function(e){return u({},e,{isRefined:o(s,n,e),attributeName:n})});p["default"].render(l["default"].createElement(C,{collapsible:v,createURL:t,cssClasses:x,facetValues:f,shouldAutoHideContainer:0===i.nbHits,templateProps:this._templateProps,toggleRefinement:this._toggleRefinement}),_)}}}function o(e,t,n){var r=e.getNumericRefinements(t);return void 0!==n.start&&void 0!==n.end&&n.start===n.end?s(r,"=",n.start):void 0!==n.start?s(r,">=",n.start):void 0!==n.end?s(r,"<=",n.end):void 0===n.start&&void 0===n.end?0===Object.keys(r).length:void 0}function a(e,t,n,r){var i=e,a=(0,y["default"])(n,{name:r}),u=i.getNumericRefinements(t);if(void 0===a.start&&void 0===a.end)return i.clearRefinements(t);if(o(i,t,a)||(i=i.clearRefinements(t)),void 0!==a.start&&void 0!==a.end){if(a.start>a.end)throw new Error("option.start should be > to option.end"); if(a.start===a.end)return i=s(u,"=",a.start)?i.removeNumericRefinement(t,"=",a.start):i.addNumericRefinement(t,"=",a.start)}return void 0!==a.start&&(i=s(u,">=",a.start)?i.removeNumericRefinement(t,">=",a.start):i.addNumericRefinement(t,">=",a.start)),void 0!==a.end&&(i=s(u,"<=",a.end)?i.removeNumericRefinement(t,"<=",a.end):i.addNumericRefinement(t,"<=",a.end)),i}function s(e,t,n){var r=void 0!==e[t],i=(0,b["default"])(e[t],n);return r&&i}Object.defineProperty(n,"__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},c=e("react"),l=r(c),f=e("react-dom"),p=r(f),d=e("../../lib/utils.js"),h=e("classnames"),m=r(h),v=e("lodash/find"),y=r(v),g=e("lodash/includes"),b=r(g),_=e("../../decorators/autoHideContainer.js"),w=r(_),C=e("../../decorators/headerFooter.js"),j=r(C),x=e("./defaultTemplates.js"),R=r(x),P=e("../../components/RefinementList/RefinementList.js"),E=r(P),O=(0,d.bemHelper)("ais-refinement-list"),S="Usage:\nnumericRefinementList({\n container,\n attributeName,\n options,\n [ cssClasses.{root,header,body,footer,list,item,active,label,radio,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":154,classnames:59,"lodash/find":406,"lodash/includes":415,react:633,"react-dom":479}],156:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(e){var t=e.container,n=e.operator,r=void 0===n?"=":n,o=e.attributeName,a=e.options,u=e.cssClasses,f=void 0===u?{}:u,d=e.autoHideContainer,m=void 0!==d&&d,g=(0,l.getContainerNode)(t),b="Usage: numericSelector({\n container,\n attributeName,\n options,\n cssClasses.{root,item},\n autoHideContainer\n })",_=v["default"];if(m===!0&&(_=(0,h["default"])(_)),!t||!a||0===a.length||!o)throw new Error(b);var w={root:(0,p["default"])(y(null),f.root),item:(0,p["default"])(y("item"),f.item)};return{getConfiguration:function(e,t){return{numericRefinements:i({},o,i({},r,[this._getRefinedValue(t)]))}},init:function(e){var t=e.helper;this._refine=function(e){t.clearRefinements(o),void 0!==e&&t.addNumericRefinement(o,r,e),t.search()}},render:function(e){var t=e.helper,n=e.results;c["default"].render(s["default"].createElement(_,{cssClasses:w,currentValue:this._getRefinedValue(t.state),options:a,setValue:this._refine,shouldAutoHideContainer:0===n.nbHits}),g)},_getRefinedValue:function(e){return e&&e.numericRefinements&&void 0!==e.numericRefinements[o]&&void 0!==e.numericRefinements[o][r]&&void 0!==e.numericRefinements[o][r][0]?e.numericRefinements[o][r][0]:a[0].value}}}Object.defineProperty(n,"__esModule",{value:!0});var a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../../lib/utils.js"),f=e("classnames"),p=r(f),d=e("../../decorators/autoHideContainer.js"),h=r(d),m=e("../../components/Selector.js"),v=r(m),y=(0,l.bemHelper)("ais-numeric-selector");n["default"]=o},{"../../components/Selector.js":124,"../../decorators/autoHideContainer.js":128,"../../lib/utils.js":136,classnames:59,react:633,"react-dom":479}],157:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.cssClasses,r=void 0===n?{}:n,i=e.labels,o=void 0===i?{}:i,s=e.maxPages,c=e.padding,f=void 0===c?3:c,h=e.showFirstLast,v=void 0===h||h,w=e.autoHideContainer,C=void 0===w||w,j=e.scrollTo,x=void 0===j?"body":j,R=x;if(!t)throw new Error(_);R===!0&&(R="body");var P=(0,d.getContainerNode)(t),E=R!==!1&&(0,d.getContainerNode)(R),O=y["default"];C===!0&&(O=(0,m["default"])(O));var S={root:(0,p["default"])(b(null),r.root),item:(0,p["default"])(b("item"),r.item),link:(0,p["default"])(b("link"),r.link),page:(0,p["default"])(b("item","page"),r.page),previous:(0,p["default"])(b("item","previous"),r.previous),next:(0,p["default"])(b("item","next"),r.next),first:(0,p["default"])(b("item","first"),r.first),last:(0,p["default"])(b("item","last"),r.last),active:(0,p["default"])(b("item","active"),r.active),disabled:(0,p["default"])(b("item","disabled"),r.disabled)},T=(0,l["default"])(o,g);return{init:function(e){var t=e.helper;this.setCurrentPage=function(e){t.setCurrentPage(e),E!==!1&&E.scrollIntoView(),t.search()}},getMaxPage:function(e){return void 0!==s?Math.min(s,e.nbPages):e.nbPages},render:function(e){var t=e.results,n=e.state,r=e.createURL;u["default"].render(a["default"].createElement(O,{createURL:function(e){return r(n.setPage(e))},cssClasses:S,currentPage:t.page,labels:T,nbHits:t.nbHits,nbPages:this.getMaxPage(t),padding:f,setCurrentPage:this.setCurrentPage,shouldAutoHideContainer:0===t.nbHits,showFirstLast:v}),P)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("lodash/defaults"),l=r(c),f=e("classnames"),p=r(f),d=e("../../lib/utils.js"),h=e("../../decorators/autoHideContainer.js"),m=r(h),v=e("../../components/Pagination/Pagination.js"),y=r(v),g={previous:"‹",next:"›",first:"«",last:"»"},b=(0,d.bemHelper)("ais-pagination"),_="Usage:\npagination({\n container,\n [ cssClasses.{root,item,page,previous,next,first,last,active,disabled}={} ],\n [ labels.{previous,next,first,last} ],\n [ maxPages ],\n [ padding=3 ],\n [ showFirstLast=true ],\n [ autoHideContainer=true ],\n [ scrollTo='body' ]\n})";n["default"]=i},{"../../components/Pagination/Pagination.js":116,"../../decorators/autoHideContainer.js":128,"../../lib/utils.js":136,classnames:59,"lodash/defaults":402,react:633,"react-dom":479}],158:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:"\n {{#from}}\n {{^to}}\n &ge;\n {{/to}}\n {{currency}}{{#helpers.formatNumber}}{{from}}{{/helpers.formatNumber}}\n {{/from}}\n {{#to}}\n {{#from}}\n -\n {{/from}}\n {{^from}}\n &le;\n {{/from}}\n {{#helpers.formatNumber}}{{to}}{{/helpers.formatNumber}}\n {{/to}}\n ",footer:""}},{}],159:[function(e,t,n){"use strict";function r(e,t){var n=Math.round(e/t)*t;return n<1&&(n=1),n}function i(e){if(e.min===e.max)return[];var t=void 0;t=e.avg<100?1:e.avg<1e3?10:100;for(var n=r(Math.round(e.avg),t),i=Math.ceil(e.min),o=r(Math.floor(e.max),t);o>e.max;)o-=t;var a=void 0,s=void 0,u=[];if(i!==o){for(a=i,u.push({to:a});a<n;)s=u[u.length-1].to,a=r(s+(n-i)/3,t),a<=s&&(a=s+1),u.push({from:s,to:a});for(;a<o;)s=u[u.length-1].to,a=r(s+(o-n)/3,t),a<=s&&(a=s+1),u.push({from:s,to:a});1===u.length&&a!==n&&(u.push({from:a,to:n}),a=n),1===u.length?(u[0].from=e.min,u[0].to=e.max):delete u[u.length-1].to}return u}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i},{}],160:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.attributeName,r=e.cssClasses,i=void 0===r?{}:r,a=e.templates,u=void 0===a?h["default"]:a,f=e.collapsible,d=void 0!==f&&f,m=e.labels,y=void 0===m?{}:m,b=e.currency,w=void 0===b?"$":b,R=e.autoHideContainer,P=void 0===R||R,E=w;if(!t||!n)throw new Error(x);var O=(0,l.getContainerNode)(t),S=(0,g["default"])(C["default"]);P===!0&&(S=(0,v["default"])(S));var T=o({button:"Go",separator:"to"},y),k={root:(0,_["default"])(j(null),i.root),header:(0,_["default"])(j("header"),i.header),body:(0,_["default"])(j("body"),i.body),list:(0,_["default"])(j("list"),i.list),link:(0,_["default"])(j("link"),i.link),item:(0,_["default"])(j("item"),i.item),active:(0,_["default"])(j("item","active"),i.active),form:(0,_["default"])(j("form"),i.form),label:(0,_["default"])(j("label"),i.label),input:(0,_["default"])(j("input"),i.input),currency:(0,_["default"])(j("currency"),i.currency),button:(0,_["default"])(j("button"),i.button),separator:(0,_["default"])(j("separator"),i.separator),footer:(0,_["default"])(j("footer"),i.footer)};return void 0!==y.currency&&y.currency!==E&&(E=y.currency),{getConfiguration:function(){return{facets:[n]}},_generateRanges:function(e){var t=e.getFacetStats(n);return(0,p["default"])(t)},_extractRefinedRange:function(e){var t=e.getRefinements(n),r=void 0,i=void 0;return 0===t.length?[]:(t.forEach(function(e){e.operator.indexOf(">")!==-1?r=Math.floor(e.value[0]):e.operator.indexOf("<")!==-1&&(i=Math.ceil(e.value[0]))}),[{from:r,to:i,isRefined:!0}])},_refine:function(e,t,r){var i=this._extractRefinedRange(e);e.clearRefinements(n),0!==i.length&&i[0].from===t&&i[0].to===r||("undefined"!=typeof t&&e.addNumericRefinement(n,">=",Math.floor(t)),"undefined"!=typeof r&&e.addNumericRefinement(n,"<=",Math.ceil(r))),e.search()},init:function(e){var t=e.helper,n=e.templatesConfig;this._refine=this._refine.bind(this,t),this._templateProps=(0,l.prepareTemplateProps)({defaultTemplates:h["default"],templatesConfig:n,templates:u})},render:function(e){var t=e.results,r=e.helper,i=e.state,o=e.createURL,a=void 0;t.hits.length>0?(a=this._extractRefinedRange(r),0===a.length&&(a=this._generateRanges(t))):a=[],a.map(function(e){var t=i.clearRefinements(n);return e.isRefined||(void 0!==e.from&&(t=t.addNumericRefinement(n,">=",Math.floor(e.from))),void 0!==e.to&&(t=t.addNumericRefinement(n,"<=",Math.ceil(e.to)))),e.url=o(t),e}),c["default"].render(s["default"].createElement(S,{collapsible:d,cssClasses:k,currency:E,facetValues:a,labels:T,refine:this._refine,shouldAutoHideContainer:0===a.length,templateProps:this._templateProps}),O)}}}Object.defineProperty(n,"__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},a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../../lib/utils.js"),f=e("./generate-ranges.js"),p=r(f),d=e("./defaultTemplates.js"),h=r(d),m=e("../../decorators/autoHideContainer.js"),v=r(m),y=e("../../decorators/headerFooter.js"),g=r(y),b=e("classnames"),_=r(b),w=e("../../components/PriceRanges/PriceRanges.js"),C=r(w),j=(0,l.bemHelper)("ais-price-ranges"),x="Usage:\npriceRanges({\n container,\n attributeName,\n [ currency=$ ],\n [ cssClasses.{root,header,body,list,item,active,link,form,label,input,currency,separator,button,footer} ],\n [ templates.{header,item,footer} ],\n [ labels.{currency,separator,button} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/PriceRanges/PriceRanges.js":119,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":158,"./generate-ranges.js":159,classnames:59,react:633,"react-dom":479}],161:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.attributeName,r=e.tooltips,o=void 0===r||r,a=e.templates,u=void 0===a?C:a,f=e.collapsible,d=void 0!==f&&f,m=e.cssClasses,y=void 0===m?{}:m,b=e.step,x=void 0===b?1:b,R=e.pips,P=void 0===R||R,E=e.autoHideContainer,O=void 0===E||E,S=e.min,T=e.max,k=e.precision,M=void 0===k?2:k;if(!t||!n)throw new Error(j);var A=function(e){return Number(Number(e).toFixed(M))},I={from:function(e){return e},to:function(e){return A(e).toLocaleString()}},F=(0,l.getContainerNode)(t),N=(0,v["default"])(_["default"]);O===!0&&(N=(0,h["default"])(N));var D={root:(0,g["default"])(w(null),y.root),header:(0,g["default"])(w("header"),y.header),body:(0,g["default"])(w("body"),y.body),footer:(0,g["default"])(w("footer"),y.footer)};return{getConfiguration:function(e){var t={disjunctiveFacets:[n]};return void 0===S&&void 0===T||e&&(!e.numericRefinements||void 0!==e.numericRefinements[n])||(t.numericRefinements=i({},n,{}),void 0!==S&&(t.numericRefinements[n][">="]=[S]),void 0!==T&&(t.numericRefinements[n]["<="]=[T])),t},_getCurrentRefinement:function(e){var t=e.state.getNumericRefinement(n,">="),r=e.state.getNumericRefinement(n,"<=");return t=t&&t.length?t[0]:-(1/0),r=r&&r.length?r[0]:1/0,{min:t,max:r}},_refine:function(e,t,r){e.clearRefinements(n),r[0]>t.min&&e.addNumericRefinement(n,">=",A(r[0])),r[1]<t.max&&e.addNumericRefinement(n,"<=",A(r[1])),e.search()},init:function(e){var t=e.templatesConfig;this._templateProps=(0,l.prepareTemplateProps)({defaultTemplates:C,templatesConfig:t,templates:u})},render:function(e){var t=e.results,r=e.helper,i=(0,p["default"])(t.disjunctiveFacets,{name:n}),a=void 0!==i&&void 0!==i.stats?i.stats:{min:null,max:null};void 0!==S&&(a.min=S),void 0!==T&&(a.max=T);var u=this._getCurrentRefinement(r);void 0!==o.format&&(o=[{to:o.format},{to:o.format}]),c["default"].render(s["default"].createElement(N,{collapsible:d,cssClasses:D,onChange:this._refine.bind(this,r,a),pips:P,range:{min:Math.floor(a.min),max:Math.ceil(a.max)},shouldAutoHideContainer:a.min===a.max,start:[u.min,u.max],step:x,templateProps:this._templateProps,tooltips:o,format:I}),F)}}}Object.defineProperty(n,"__esModule",{value:!0});var a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../../lib/utils.js"),f=e("lodash/find"),p=r(f),d=e("../../decorators/autoHideContainer.js"),h=r(d),m=e("../../decorators/headerFooter.js"),v=r(m),y=e("classnames"),g=r(y),b=e("../../components/Slider/Slider.js"),_=r(b),w=(0,l.bemHelper)("ais-range-slider"),C={header:"",footer:""},j="Usage:\nrangeSlider({\n container,\n attributeName,\n [ tooltips=true ],\n [ templates.{header, footer} ],\n [ cssClasses.{root, header, body, footer} ],\n [ step=1 ],\n [ pips=true ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ min ],\n [ max ]\n});\n";n["default"]=o},{"../../components/Slider/Slider.js":125,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,classnames:59,"lodash/find":406,react:633,"react-dom":479}],162:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox"\n class="{{cssClasses.checkbox}}"\n value="{{name}}"\n {{#isRefined}}checked{{/isRefined}} />\n {{{highlighted}}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',footer:""}},{}],163:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}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 o(e){var t=e.container,n=e.attributeName,r=e.operator,o=void 0===r?"or":r,s=e.sortBy,c=void 0===s?["count:desc","name:asc"]:s,p=e.limit,h=void 0===p?10:p,v=e.cssClasses,g=void 0===v?{}:v,_=e.templates,C=void 0===_?j["default"]:_,x=e.collapsible,O=void 0!==x&&x,S=e.transformData,T=e.autoHideContainer,k=void 0===T||T,M=e.showMore,A=void 0!==M&&M,I=e.searchForFacetValues,F=void 0!==I&&I,N=(0,w["default"])(A);if(N&&N.limit<h)throw new Error("showMore.limit configuration should be > than the limit in the main configuration");var D=N&&N.limit||h,L=R["default"];if(!t||!n)throw new Error(E);L=(0,b["default"])(L),k===!0&&(L=(0,y["default"])(L));var U=(0,f.getContainerNode)(t);if(o&&(o=o.toLowerCase(),"and"!==o&&"or"!==o))throw new Error(E);var H=N?(0,f.prefixKeys)("show-more-",N.templates):{},V=F?F.templates:{},q=a({},C,H,V),B={root:(0,d["default"])(P(null),g.root),header:(0,d["default"])(P("header"),g.header),body:(0,d["default"])(P("body"),g.body),footer:(0,d["default"])(P("footer"),g.footer),list:(0,d["default"])(P("list"),g.list),item:(0,d["default"])(P("item"),g.item),active:(0,d["default"])(P("item","active"),g.active),label:(0,d["default"])(P("label"),g.label),checkbox:(0,d["default"])(P("checkbox"),g.checkbox),count:(0,d["default"])(P("count"),g.count)},W=function(e,t,r,i,o,a,s){function c(e){return r(t.toggleRefinement(n,e))}var f=(0,m["default"])(e,{isRefined:!0}).length,p={header:{refinedFacetsCount:f}},d=i&&i(t,r,i,o,a);l["default"].render(u["default"].createElement(L,{collapsible:O,createURL:c,cssClasses:B,facetValues:e,headerFooterData:p,limitMax:D,limitMin:h,shouldAutoHideContainer:!s&&0===e.length,showMore:null!==N,templateProps:o,toggleRefinement:a,searchFacetValues:d,searchPlaceholder:F.placeholder||"Search for other...",isFromSearch:s}),U)},K=null,z=function(e){return function(t,r,i,o,a){return function(s){""===s&&K?W(K,t,r,i,o,a,!1):e.searchForFacetValues(n,s).then(function(e){var n=e.facetHits.map(function(e){return e.name=e.value,e});W(n,t,r,i,o,a,!0)})}}};return{getConfiguration:function(e){var t=i({},"and"===o?"facets":"disjunctiveFacets",[n]),r=e.maxValuesPerFacet||0;return t.maxValuesPerFacet=Math.max(r,D),t},init:function(e){var t=e.templatesConfig,r=e.helper;this._templateProps=(0,f.prepareTemplateProps)({transformData:S,defaultTemplates:j["default"],templatesConfig:t,templates:q}),this.toggleRefinement=function(e){return r.toggleRefinement(n,e).search()},this.searchFacetValues=F?z(r):null},render:function(e){var t=e.results,r=e.state,i=e.createURL,o=t.getFacetValues(n,{sortBy:c}).map(function(e){return e.highlighted=e.name,e});K=o,W(o,r,i,this.searchFacetValues,this._templateProps,this.toggleRefinement,!1)}}}Object.defineProperty(n,"__esModule",{value:!0});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},s=e("react"),u=r(s),c=e("react-dom"),l=r(c),f=e("../../lib/utils.js"),p=e("classnames"),d=r(p),h=e("lodash/filter"),m=r(h),v=e("../../decorators/autoHideContainer.js"),y=r(v),g=e("../../decorators/headerFooter.js"),b=r(g),_=e("../../lib/show-more/getShowMoreConfig.js"),w=r(_),C=e("./defaultTemplates.js"),j=r(C),x=e("../../components/RefinementList/RefinementList.js"),R=r(x),P=(0,f.bemHelper)("ais-refinement-list"),E="Usage:\nrefinementList({\n container,\n attributeName,\n [ operator='or' ],\n [ sortBy=['count:desc', 'name:asc'] ],\n [ limit=10 ],\n [ cssClasses.{root, header, body, footer, list, item, active, label, checkbox, count}],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ],\n [ showMore.{templates: {active, inactive}, limit} ],\n [ collapsible=false ],\n [ searchForFacetValues.{placeholder, templates: {noResults}}],\n})";n["default"]=o},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/show-more/getShowMoreConfig.js":134,"../../lib/utils.js":136,"./defaultTemplates.js":162,classnames:59,"lodash/filter":405,react:633,"react-dom":479}],164:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={poweredBy:'\n<div class="{{cssClasses.root}}">\n Search by\n <a class="{{cssClasses.link}}" href="{{url}}" target="_blank">Algolia</a>\n</div>'}},{}],165:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e){var t=e.container,n=e.placeholder,r=void 0===n?"":n,i=e.cssClasses,a=void 0===i?{}:i,f=e.poweredBy,d=void 0!==f&&f,m=e.wrapInput,y=void 0===m||m,b=e.autofocus,w=void 0===b?"auto":b,E=e.searchOnEnterKeyPressOnly,O=void 0!==E&&E,S=e.queryHook,T=window.addEventListener?"input":"propertychange";if(!t)throw new Error(P);return t=(0,l.getContainerNode)(t),"boolean"!=typeof w&&(w="auto"),d===!0&&(d={}),{getInput:function(){return"INPUT"===t.tagName?t:document.createElement("input")},wrapInput:function(e){var t=document.createElement("div"),n=(0,g["default"])(j(null),a.root).split(" ");return n.forEach(function(e){return t.classList.add(e)}),t.appendChild(e),t},addDefaultAttributesToInput:function(e,t){var n={autocapitalize:"off",autocomplete:"off",autocorrect:"off",placeholder:r,role:"textbox",spellcheck:"false",type:"text",value:t};(0,p["default"])(n,function(t,n){e.hasAttribute(n)||e.setAttribute(n,t)});var i=(0,g["default"])(j("input"),a.input).split(" ");i.forEach(function(t){return e.classList.add(t)})},addPoweredBy:function(e){d=c({cssClasses:{},template:C["default"].poweredBy},d);var t={root:(0,g["default"])(j("powered-by"),d.cssClasses.root),link:(0,g["default"])(j("powered-by-link"),d.cssClasses.link)},n="https://www.algolia.com/?utm_source=instantsearch.js&utm_medium=website&"+("utm_content="+location.hostname+"&")+"utm_campaign=poweredby",r={cssClasses:t,url:n},i=d.template,o=void 0;(0,h["default"])(i)&&(o=_["default"].compile(i).render(r)),(0,v["default"])(i)&&(o=i(r));var a=document.createElement("div");a.innerHTML="<span>"+o.trim()+"</span>";var s=a.firstChild;e.parentNode.insertBefore(s,e.nextSibling)},init:function(e){function n(e){return S?void S(e,a):void i(e)}function r(e){e!==l.state.query&&(m=l.state.query,l.setQuery(e))}function i(e){void 0!==m&&m!==e&&l.search()}function a(e){r(e),i(e)}var c=e.state,l=e.helper,f=e.onHistoryChange,p="INPUT"===t.tagName,h=this._input=this.getInput(),m=void 0;if(this.addDefaultAttributesToInput(h,c.query),S||o(h,T,u(r)),O?o(h,"keyup",s(x,u(n))):(o(h,T,u(n)),("propertychange"===T||window.attachEvent)&&(o(h,"keyup",s(R,u(r))),o(h,"keyup",s(R,u(n))))),p){var v=document.createElement("div");h.parentNode.insertBefore(v,h);var g=h.parentNode,b=y?this.wrapInput(h):h;g.replaceChild(b,v)}else{var _=y?this.wrapInput(h):h;t.appendChild(_)}d&&this.addPoweredBy(h),f(function(e){h.value=e.query||""}),window.addEventListener("pageshow",function(){h.value=l.state.query}),(w===!0||"auto"===w&&""===l.state.query)&&(h.focus(),h.setSelectionRange(l.state.query.length,l.state.query.length))},render:function(e){var t=e.helper;document.activeElement!==this._input&&t.state.query!==this._input.value&&(this._input.value=t.state.query)}}}function o(e,t,n){e.addEventListener?e.addEventListener(t,n):e.attachEvent("on"+t,n)}function a(e){return(e.currentTarget?e.currentTarget:e.srcElement).value}function s(e,t){return function(n){return n.keyCode===e&&t(n)}}function u(e){return function(t){return e(a(t))}}Object.defineProperty(n,"__esModule",{value:!0});var 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=e("../../lib/utils.js"),f=e("lodash/forEach"),p=r(f),d=e("lodash/isString"),h=r(d),m=e("lodash/isFunction"),v=r(m),y=e("classnames"),g=r(y),b=e("hogan.js"),_=r(b),w=e("./defaultTemplates.js"),C=r(w),j=(0,l.bemHelper)("ais-search-box"),x=13,R=8,P="Usage:\nsearchBox({\n container,\n [ placeholder ],\n [ cssClasses.{input,poweredBy} ],\n [ poweredBy=false || poweredBy.{template, cssClasses.{root,link}} ],\n [ wrapInput ],\n [ autofocus ],\n [ searchOnEnterKeyPressOnly ],\n [ queryHook ]\n})";n["default"]=i},{"../../lib/utils.js":136,"./defaultTemplates.js":164,classnames:59,"hogan.js":108,"lodash/forEach":409,"lodash/isFunction":427,"lodash/isString":435}],166:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.indices,r=e.cssClasses,i=void 0===r?{}:r,o=e.autoHideContainer,s=void 0!==o&&o;if(!t||!n)throw new Error(w);var c=(0,d.getContainerNode)(t),f=b["default"];s===!0&&(f=(0,y["default"])(f));var h=(0,p["default"])(n,function(e){return{label:e.label,value:e.name}}),v={root:(0,m["default"])(_(null),i.root),item:(0,m["default"])(_("item"),i.item)};return{init:function(e){var t=e.helper,r=t.getIndex(),i=(0,l["default"])(n,{name:r})!==-1;if(!i)throw new Error("[sortBySelector]: Index "+r+" not present in `indices`");this.setIndex=function(e){return t.setIndex(e).search()}},render:function(e){var t=e.helper,n=e.results;u["default"].render(a["default"].createElement(f,{cssClasses:v,currentValue:t.getIndex(),options:h,setValue:this.setIndex,shouldAutoHideContainer:0===n.nbHits}),c)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("lodash/findIndex"),l=r(c),f=e("lodash/map"),p=r(f),d=e("../../lib/utils.js"),h=e("classnames"),m=r(h),v=e("../../decorators/autoHideContainer.js"),y=r(v),g=e("../../components/Selector.js"),b=r(g),_=(0,d.bemHelper)("ais-sort-by-selector"),w="Usage:\nsortBySelector({\n container,\n indices,\n [cssClasses.{root,item}={}],\n [autoHideContainer=false]\n})";n["default"]=i},{"../../components/Selector.js":124,"../../decorators/autoHideContainer.js":128,"../../lib/utils.js":136,classnames:59,"lodash/findIndex":407,"lodash/map":442,react:633,"react-dom":479}],167:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={andUp:"& Up"}},{}],168:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'<a class="{{cssClasses.link}}{{^count}} {{cssClasses.disabledLink}}{{/count}}" {{#count}}href="{{href}}"{{/count}}>\n {{#stars}}<span class="{{#.}}{{cssClasses.star}}{{/.}}{{^.}}{{cssClasses.emptyStar}}{{/.}}"></span>{{/stars}}\n {{labels.andUp}}\n {{#count}}<span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>{{/count}}\n</a>',footer:""}},{}],169:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e){var t=e.container,n=e.attributeName,r=e.max,i=void 0===r?5:r,o=e.cssClasses,s=void 0===o?{}:o,l=e.labels,p=void 0===l?b["default"]:l,h=e.templates,v=void 0===h?y["default"]:h,g=e.collapsible,_=void 0!==g&&g,x=e.transformData,R=e.autoHideContainer,P=void 0===R||R,E=(0,c.getContainerNode)(t),O=(0,m["default"])(w["default"]);if(P===!0&&(O=(0,d["default"])(O)),!t||!n)throw new Error(j);var S={root:(0,f["default"])(C(null),s.root),header:(0,f["default"])(C("header"),s.header),body:(0,f["default"])(C("body"),s.body),footer:(0,f["default"])(C("footer"),s.footer),list:(0,f["default"])(C("list"),s.list),item:(0,f["default"])(C("item"),s.item),link:(0,f["default"])(C("link"),s.link),disabledLink:(0,f["default"])(C("link","disabled"),s.disabledLink),count:(0,f["default"])(C("count"),s.count),star:(0,f["default"])(C("star"),s.star),emptyStar:(0,f["default"])(C("star","empty"),s.emptyStar),active:(0,f["default"])(C("item","active"),s.active)};return{getConfiguration:function(){return{disjunctiveFacets:[n]}},init:function(e){var t=e.templatesConfig,n=e.helper;this._templateProps=(0,c.prepareTemplateProps)({transformData:x,defaultTemplates:y["default"],templatesConfig:t,templates:v}),this._toggleRefinement=this._toggleRefinement.bind(this,n)},render:function(e){function t(e){return c(s.toggleRefinement(n,e))}for(var r=e.helper,o=e.results,s=e.state,c=e.createURL,l=[],f={},d=i-1;d>=0;--d)f[d]=0;o.getFacetValues(n).forEach(function(e){var t=Math.round(e.name);if(t&&!(t>i-1))for(var n=t;n>=1;--n)f[n]+=e.count});for(var h=this._getRefinedStar(r),m=i-1;m>=1;--m){var v=f[m];if(!h||m===h||0!==v){for(var y=[],g=1;g<=i;++g)y.push(g<=m);l.push({stars:y,name:String(m),count:v,isRefined:h===m,labels:p})}}u["default"].render(a["default"].createElement(O,{collapsible:_,createURL:t,cssClasses:S,facetValues:l,shouldAutoHideContainer:0===o.nbHits,templateProps:this._templateProps,toggleRefinement:this._toggleRefinement}),E)},_toggleRefinement:function(e,t){var r=this._getRefinedStar(e)===Number(t);if(e.clearRefinements(n),!r)for(var o=Number(t);o<=i;++o)e.addDisjunctiveFacetRefinement(n,o);e.search()},_getRefinedStar:function(e){var t=void 0,r=e.getRefinements(n);return r.forEach(function(e){(!t||Number(e.value)<t)&&(t=Number(e.value))}),t}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("classnames"),f=r(l),p=e("../../decorators/autoHideContainer.js"),d=r(p),h=e("../../decorators/headerFooter.js"),m=r(h),v=e("./defaultTemplates.js"),y=r(v),g=e("./defaultLabels.js"),b=r(g),_=e("../../components/RefinementList/RefinementList.js"),w=r(_),C=(0,c.bemHelper)("ais-star-rating"),j="Usage:\nstarRating({\n container,\n attributeName,\n [ max=5 ],\n [ cssClasses.{root,header,body,footer,list,item,active,link,disabledLink,star,emptyStar,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ labels.{andUp} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultLabels.js":167,"./defaultTemplates.js":168,classnames:59,react:633,"react-dom":479}],170:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",body:'{{#hasNoResults}}No results{{/hasNoResults}}\n {{#hasOneResult}}1 result{{/hasOneResult}}\n {{#hasManyResults}}{{#helpers.formatNumber}}{{nbHits}}{{/helpers.formatNumber}} results{{/hasManyResults}}\n <span class="{{cssClasses.time}}">found in {{processingTimeMS}}ms</span>',footer:""}},{}],171:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.cssClasses,r=void 0===n?{}:n,i=e.autoHideContainer,o=void 0===i||i,s=e.templates,l=void 0===s?b["default"]:s,p=e.collapsible,h=void 0!==p&&p,v=e.transformData;if(!t)throw new Error(w);var g=(0,c.getContainerNode)(t),C=(0,d["default"])(m["default"]);if(o===!0&&(C=(0,f["default"])(C)),!g)throw new Error(w);var j={body:(0,y["default"])(_("body"),r.body),footer:(0,y["default"])(_("footer"),r.footer),header:(0,y["default"])(_("header"),r.header),root:(0,y["default"])(_(null),r.root),time:(0,y["default"])(_("time"),r.time)};return{init:function(e){var t=e.templatesConfig;this._templateProps=(0,c.prepareTemplateProps)({transformData:v,defaultTemplates:b["default"],templatesConfig:t,templates:l})},render:function(e){var t=e.results;u["default"].render(a["default"].createElement(C,{collapsible:h,cssClasses:j,hitsPerPage:t.hitsPerPage,nbHits:t.nbHits,nbPages:t.nbPages,page:t.page,processingTimeMS:t.processingTimeMS,query:t.query,shouldAutoHideContainer:0===t.nbHits,templateProps:this._templateProps}),g)}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("react"),a=r(o),s=e("react-dom"),u=r(s),c=e("../../lib/utils.js"),l=e("../../decorators/autoHideContainer.js"),f=r(l),p=e("../../decorators/headerFooter.js"),d=r(p),h=e("../../components/Stats/Stats.js"),m=r(h),v=e("classnames"),y=r(v),g=e("./defaultTemplates.js"),b=r(g),_=(0,c.bemHelper)("ais-stats"),w="Usage:\nstats({\n container,\n [ templates.{header,body,footer} ],\n [ transformData.{body} ],\n [ autoHideContainer]\n})";n["default"]=i},{"../../components/Stats/Stats.js":126,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":170,classnames:59,react:633,"react-dom":479}],172:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]={header:"",item:'<label class="{{cssClasses.label}}">\n <input type="checkbox" class="{{cssClasses.checkbox}}" value="{{name}}" {{#isRefined}}checked{{/isRefined}} />{{name}}\n <span class="{{cssClasses.count}}">{{#helpers.formatNumber}}{{count}}{{/helpers.formatNumber}}</span>\n</label>',footer:""}},{}],173:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var i=e("lodash/find"),o=r(i),a=e("react"),s=r(a),u=e("react-dom"),c=r(u),l=e("../defaultTemplates.js"),f=r(l),p=e("../../../lib/utils.js"),d=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.attributeName,n=e.label,r=e.userValues,i=e.templates,a=e.collapsible,u=e.transformData,l=e.hasAnOffValue,d=e.containerNode,h=e.RefinementList,m=e.cssClasses,v=r?(0, p.escapeRefinement)(r.on):void 0,y=r?(0,p.escapeRefinement)(r.off):void 0;return{getConfiguration:function(){return{disjunctiveFacets:[t]}},toggleRefinement:function(e,n,r){r?(e.removeDisjunctiveFacetRefinement(t,v),l&&e.addDisjunctiveFacetRefinement(t,y)):(l&&e.removeDisjunctiveFacetRefinement(t,y),e.addDisjunctiveFacetRefinement(t,v)),e.search()},init:function(e){var n=e.state,r=e.helper,o=e.templatesConfig;if(this._templateProps=(0,p.prepareTemplateProps)({transformData:u,defaultTemplates:f["default"],templatesConfig:o,templates:i}),this.toggleRefinement=this.toggleRefinement.bind(this,r),l){var a=n.isDisjunctiveFacetRefined(t,v);a||r.addDisjunctiveFacetRefinement(t,y)}},render:function(e){function r(){return g(f.removeDisjunctiveFacetRefinement(t,b?_:y).addDisjunctiveFacetRefinement(t,b?y:_))}var i=e.helper,u=e.results,f=e.state,g=e.createURL,b=i.state.isDisjunctiveFacetRefined(t,v),_=v,w=void 0!==y&&y,C=u.getFacetValues(t),j=(0,o["default"])(C,{name:(0,p.unescapeRefinement)(_)}),x={name:n,isRefined:void 0!==j&&j.isRefined,count:void 0===j?null:j.count},R=l?(0,o["default"])(C,{name:(0,p.unescapeRefinement)(w)}):void 0,P={name:n,isRefined:void 0!==R&&R.isRefined,count:void 0===R?u.nbHits:R.count},E=b?P:x,O={name:n,isRefined:b,count:void 0===E?null:E.count,onFacetValue:x,offFacetValue:P};c["default"].render(s["default"].createElement(h,{collapsible:a,createURL:r,cssClasses:m,facetValues:[O],shouldAutoHideContainer:0===O.count||null===O.count,templateProps:this._templateProps,toggleRefinement:this.toggleRefinement}),d)}}};n["default"]=d},{"../../../lib/utils.js":136,"../defaultTemplates.js":172,"lodash/find":406,react:633,"react-dom":479}],174:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.attributeName,n=e.label,r=e.userValues,i=e.templates,o=e.collapsible,s=e.transformData,c=e.hasAnOffValue,f=e.containerNode,h=e.RefinementList,m=e.cssClasses;return{getConfiguration:function(){return{facets:[t]}},toggleRefinement:function(e,n,i){var o=r.on,a=r.off;i?(e.removeFacetRefinement(t,o),c&&e.addFacetRefinement(t,a)):(c&&e.removeFacetRefinement(t,a),e.addFacetRefinement(t,o)),e.search()},init:function(e){var n=e.state,o=e.helper,a=e.templatesConfig;if(this._templateProps=(0,d.prepareTemplateProps)({transformData:s,defaultTemplates:p["default"],templatesConfig:a,templates:i}),this.toggleRefinement=this.toggleRefinement.bind(this,o),c){var u=n.isFacetRefined(t,r.on);u||o.addFacetRefinement(t,r.off)}},render:function(e){function i(){return d(p.toggleRefinement(t,v))}var s=e.helper,c=e.results,p=e.state,d=e.createURL,v=s.state.isFacetRefined(t,r.on),y=v?r.on:r.off,g=void 0;if("number"==typeof y)g=c.getFacetStats(t).sum;else{var b=(0,a["default"])(c.getFacetValues(t),{name:v.toString()});g=void 0!==b?b.count:null}var _={name:n,isRefined:v,count:g};l["default"].render(u["default"].createElement(h,{collapsible:o,createURL:i,cssClasses:m,facetValues:[_],shouldAutoHideContainer:0===c.nbHits,templateProps:this._templateProps,toggleRefinement:this.toggleRefinement}),f)}}}Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=i;var o=e("lodash/find"),a=r(o),s=e("react"),u=r(s),c=e("react-dom"),l=r(c),f=e("../defaultTemplates.js"),p=r(f),d=e("../../../lib/utils.js")},{"../../../lib/utils.js":136,"../defaultTemplates.js":172,"lodash/find":406,react:633,"react-dom":479}],175:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.container,n=e.attributeName,r=e.label,i=e.values,a=void 0===i?{on:!0,off:void 0}:i,u=e.templates,l=void 0===u?s["default"]:u,p=e.collapsible,h=void 0!==p&&p,v=e.cssClasses,g=void 0===v?{}:v,j=e.transformData,x=e.autoHideContainer,R=void 0===x||x,P=(0,o.getContainerNode)(t);if(!t||!n||!r)throw new Error(C);var E=(0,d["default"])(m["default"]);R===!0&&(E=(0,f["default"])(E));var O=void 0!==a.off,S={root:(0,c["default"])(_(null),g.root),header:(0,c["default"])(_("header"),g.header),body:(0,c["default"])(_("body"),g.body),footer:(0,c["default"])(_("footer"),g.footer),list:(0,c["default"])(_("list"),g.list),item:(0,c["default"])(_("item"),g.item),active:(0,c["default"])(_("item","active"),g.active),label:(0,c["default"])(_("label"),g.label),checkbox:(0,c["default"])(_("checkbox"),g.checkbox),count:(0,c["default"])(_("count"),g.count)},T={attributeName:n,label:r,userValues:a,templates:l,collapsible:h,transformData:j,hasAnOffValue:O,containerNode:P,RefinementList:E,cssClasses:S};return{getConfiguration:function(e,t){var r=w(n,e)||w(n,t),i=r?(0,b["default"])(T):(0,y["default"])(T);return this.init=i.init.bind(i),this.render=i.render.bind(i),i.getConfiguration(e,t)},init:function(){},render:function(){}}}Object.defineProperty(n,"__esModule",{value:!0});var o=e("../../lib/utils.js"),a=e("./defaultTemplates.js"),s=r(a),u=e("classnames"),c=r(u),l=e("../../decorators/autoHideContainer.js"),f=r(l),p=e("../../decorators/headerFooter.js"),d=r(p),h=e("../../components/RefinementList/RefinementList.js"),m=r(h),v=e("./implementations/currentToggle"),y=r(v),g=e("./implementations/legacyToggle"),b=r(g),_=(0,o.bemHelper)("ais-toggle"),w=function(e,t){return t&&t.facetsRefinements&&void 0!==t.facetsRefinements[e]},C="Usage:\ntoggle({\n container,\n attributeName,\n label,\n [ values={on: true, off: undefined} ],\n [ cssClasses.{root,header,body,footer,list,item,active,label,checkbox,count} ],\n [ templates.{header,item,footer} ],\n [ transformData.{item} ],\n [ autoHideContainer=true ],\n [ collapsible=false ]\n})";n["default"]=i},{"../../components/RefinementList/RefinementList.js":121,"../../decorators/autoHideContainer.js":128,"../../decorators/headerFooter.js":129,"../../lib/utils.js":136,"./defaultTemplates.js":172,"./implementations/currentToggle":173,"./implementations/legacyToggle":174,classnames:59}],176:[function(e,t,n){var r={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},{}],177:[function(e,t,n){var r=e("./_getNative"),i=e("./_root"),o=r(i,"DataView");t.exports=o},{"./_getNative":319,"./_root":373}],178:[function(e,t,n){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 i=e("./_hashClear"),o=e("./_hashDelete"),a=e("./_hashGet"),s=e("./_hashHas"),u=e("./_hashSet");r.prototype.clear=i,r.prototype["delete"]=o,r.prototype.get=a,r.prototype.has=s,r.prototype.set=u,t.exports=r},{"./_hashClear":329,"./_hashDelete":330,"./_hashGet":331,"./_hashHas":332,"./_hashSet":333}],179:[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 i=e("./_baseCreate"),o=e("./_baseLodash"),a=4294967295;r.prototype=i(o.prototype),r.prototype.constructor=r,t.exports=r},{"./_baseCreate":212,"./_baseLodash":237}],180:[function(e,t,n){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 i=e("./_listCacheClear"),o=e("./_listCacheDelete"),a=e("./_listCacheGet"),s=e("./_listCacheHas"),u=e("./_listCacheSet");r.prototype.clear=i,r.prototype["delete"]=o,r.prototype.get=a,r.prototype.has=s,r.prototype.set=u,t.exports=r},{"./_listCacheClear":347,"./_listCacheDelete":348,"./_listCacheGet":349,"./_listCacheHas":350,"./_listCacheSet":351}],181:[function(e,t,n){function r(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}var i=e("./_baseCreate"),o=e("./_baseLodash");r.prototype=i(o.prototype),r.prototype.constructor=r,t.exports=r},{"./_baseCreate":212,"./_baseLodash":237}],182:[function(e,t,n){var r=e("./_getNative"),i=e("./_root"),o=r(i,"Map");t.exports=o},{"./_getNative":319,"./_root":373}],183:[function(e,t,n){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 i=e("./_mapCacheClear"),o=e("./_mapCacheDelete"),a=e("./_mapCacheGet"),s=e("./_mapCacheHas"),u=e("./_mapCacheSet");r.prototype.clear=i,r.prototype["delete"]=o,r.prototype.get=a,r.prototype.has=s,r.prototype.set=u,t.exports=r},{"./_mapCacheClear":352,"./_mapCacheDelete":353,"./_mapCacheGet":354,"./_mapCacheHas":355,"./_mapCacheSet":356}],184:[function(e,t,n){var r=e("./_getNative"),i=e("./_root"),o=r(i,"Promise");t.exports=o},{"./_getNative":319,"./_root":373}],185:[function(e,t,n){var r=e("./_getNative"),i=e("./_root"),o=r(i,"Set");t.exports=o},{"./_getNative":319,"./_root":373}],186:[function(e,t,n){function r(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new i;++t<n;)this.add(e[t])}var i=e("./_MapCache"),o=e("./_setCacheAdd"),a=e("./_setCacheHas");r.prototype.add=r.prototype.push=o,r.prototype.has=a,t.exports=r},{"./_MapCache":183,"./_setCacheAdd":374,"./_setCacheHas":375}],187:[function(e,t,n){function r(e){var t=this.__data__=new i(e);this.size=t.size}var i=e("./_ListCache"),o=e("./_stackClear"),a=e("./_stackDelete"),s=e("./_stackGet"),u=e("./_stackHas"),c=e("./_stackSet");r.prototype.clear=o,r.prototype["delete"]=a,r.prototype.get=s,r.prototype.has=u,r.prototype.set=c,t.exports=r},{"./_ListCache":180,"./_stackClear":381,"./_stackDelete":382,"./_stackGet":383,"./_stackHas":384,"./_stackSet":385}],188:[function(e,t,n){var r=e("./_root"),i=r.Symbol;t.exports=i},{"./_root":373}],189:[function(e,t,n){var r=e("./_root"),i=r.Uint8Array;t.exports=i},{"./_root":373}],190:[function(e,t,n){var r=e("./_getNative"),i=e("./_root"),o=r(i,"WeakMap");t.exports=o},{"./_getNative":319,"./_root":373}],191:[function(e,t,n){function r(e,t){return e.set(t[0],t[1]),e}t.exports=r},{}],192:[function(e,t,n){function r(e,t){return e.add(t),e}t.exports=r},{}],193:[function(e,t,n){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.exports=r},{}],194:[function(e,t,n){function r(e,t){for(var n=-1,r=null==e?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}t.exports=r},{}],195:[function(e,t,n){function r(e,t){for(var n=-1,r=null==e?0:e.length,i=0,o=[];++n<r;){var a=e[n];t(a,n,e)&&(o[i++]=a)}return o}t.exports=r},{}],196:[function(e,t,n){function r(e,t){var n=null==e?0:e.length;return!!n&&i(e,t,0)>-1}var i=e("./_baseIndexOf");t.exports=r},{"./_baseIndexOf":224}],197:[function(e,t,n){function r(e,t,n){for(var r=-1,i=null==e?0:e.length;++r<i;)if(n(t,e[r]))return!0;return!1}t.exports=r},{}],198:[function(e,t,n){function r(e,t){var n=a(e),r=!n&&o(e),l=!n&&!r&&s(e),p=!n&&!r&&!l&&c(e),d=n||r||l||p,h=d?i(e.length,String):[],m=h.length;for(var v in e)!t&&!f.call(e,v)||d&&("length"==v||l&&("offset"==v||"parent"==v)||p&&("buffer"==v||"byteLength"==v||"byteOffset"==v)||u(v,m))||h.push(v);return h}var i=e("./_baseTimes"),o=e("./isArguments"),a=e("./isArray"),s=e("./isBuffer"),u=e("./_isIndex"),c=e("./isTypedArray"),l=Object.prototype,f=l.hasOwnProperty;t.exports=r},{"./_baseTimes":258,"./_isIndex":339,"./isArguments":419,"./isArray":420,"./isBuffer":424,"./isTypedArray":437}],199:[function(e,t,n){function r(e,t){for(var n=-1,r=null==e?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}t.exports=r},{}],200:[function(e,t,n){function r(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}t.exports=r},{}],201:[function(e,t,n){function r(e,t,n,r){var i=-1,o=null==e?0:e.length;for(r&&o&&(n=e[++i]);++i<o;)n=t(n,e[i],i,e);return n}t.exports=r},{}],202:[function(e,t,n){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.exports=r},{}],203:[function(e,t,n){function r(e){return e.split("")}t.exports=r},{}],204:[function(e,t,n){function r(e,t,n){(void 0===n||o(e[t],n))&&(void 0!==n||t in e)||i(e,t,n)}var i=e("./_baseAssignValue"),o=e("./eq");t.exports=r},{"./_baseAssignValue":209,"./eq":404}],205:[function(e,t,n){function r(e,t,n){var r=e[t];s.call(e,t)&&o(r,n)&&(void 0!==n||t in e)||i(e,t,n)}var i=e("./_baseAssignValue"),o=e("./eq"),a=Object.prototype,s=a.hasOwnProperty;t.exports=r},{"./_baseAssignValue":209,"./eq":404}],206:[function(e,t,n){function r(e,t){for(var n=e.length;n--;)if(i(e[n][0],t))return n;return-1}var i=e("./eq");t.exports=r},{"./eq":404}],207:[function(e,t,n){function r(e,t){return e&&i(t,o(t),e)}var i=e("./_copyObject"),o=e("./keys");t.exports=r},{"./_copyObject":284,"./keys":439}],208:[function(e,t,n){function r(e,t){return e&&i(t,o(t),e)}var i=e("./_copyObject"),o=e("./keysIn");t.exports=r},{"./_copyObject":284,"./keysIn":440}],209:[function(e,t,n){function r(e,t,n){"__proto__"==t&&i?i(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}var i=e("./_defineProperty");t.exports=r},{"./_defineProperty":306}],210:[function(e,t,n){function r(e,t,n){return e===e&&(void 0!==n&&(e=e<=n?e:n),void 0!==t&&(e=e>=t?e:t)),e}t.exports=r},{}],211:[function(e,t,n){function r(e,t,n,E,O,S){var T,A=t&j,I=t&x,N=t&R;if(n&&(T=O?n(e,E,O,S):n(e)),void 0!==T)return T;if(!w(e))return e;var D=b(e);if(D){if(T=v(e),!A)return l(e,T)}else{var L=m(e),U=L==k||L==M;if(_(e))return c(e,A);if(L==F||L==P||U&&!O){if(T=I||U?{}:g(e),!A)return I?p(e,u(T,e)):f(e,s(T,e))}else{if(!X[L])return O?e:{};T=y(e,L,r,A)}}S||(S=new i);var H=S.get(e);if(H)return H;S.set(e,T);var V=N?I?h:d:I?keysIn:C,q=D?void 0:V(e);return o(q||e,function(i,o){q&&(o=i,i=e[o]),a(T,o,r(i,t,n,o,e,S))}),T}var i=e("./_Stack"),o=e("./_arrayEach"),a=e("./_assignValue"),s=e("./_baseAssign"),u=e("./_baseAssignIn"),c=e("./_cloneBuffer"),l=e("./_copyArray"),f=e("./_copySymbols"),p=e("./_copySymbolsIn"),d=e("./_getAllKeys"),h=e("./_getAllKeysIn"),m=e("./_getTag"),v=e("./_initCloneArray"),y=e("./_initCloneByTag"),g=e("./_initCloneObject"),b=e("./isArray"),_=e("./isBuffer"),w=e("./isObject"),C=e("./keys"),j=1,x=2,R=4,P="[object Arguments]",E="[object Array]",O="[object Boolean]",S="[object Date]",T="[object Error]",k="[object Function]",M="[object GeneratorFunction]",A="[object Map]",I="[object Number]",F="[object Object]",N="[object RegExp]",D="[object Set]",L="[object String]",U="[object Symbol]",H="[object WeakMap]",V="[object ArrayBuffer]",q="[object DataView]",B="[object Float32Array]",W="[object Float64Array]",K="[object Int8Array]",z="[object Int16Array]",Q="[object Int32Array]",$="[object Uint8Array]",G="[object Uint8ClampedArray]",Y="[object Uint16Array]",J="[object Uint32Array]",X={};X[P]=X[E]=X[V]=X[q]=X[O]=X[S]=X[B]=X[W]=X[K]=X[z]=X[Q]=X[A]=X[I]=X[F]=X[N]=X[D]=X[L]=X[U]=X[$]=X[G]=X[Y]=X[J]=!0,X[T]=X[k]=X[H]=!1,t.exports=r},{"./_Stack":187,"./_arrayEach":194,"./_assignValue":205,"./_baseAssign":207,"./_baseAssignIn":208,"./_cloneBuffer":272,"./_copyArray":283,"./_copySymbols":285,"./_copySymbolsIn":286,"./_getAllKeys":312,"./_getAllKeysIn":313,"./_getTag":324,"./_initCloneArray":334,"./_initCloneByTag":335,"./_initCloneObject":336,"./isArray":420,"./isBuffer":424,"./isObject":432,"./keys":439}],212:[function(e,t,n){var r=e("./isObject"),i=Object.create,o=function(){function e(){}return function(t){if(!r(t))return{};if(i)return i(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}}();t.exports=o},{"./isObject":432}],213:[function(e,t,n){var r=e("./_baseForOwn"),i=e("./_createBaseEach"),o=i(r);t.exports=o},{"./_baseForOwn":218,"./_createBaseEach":290}],214:[function(e,t,n){function r(e,t){var n=[];return i(e,function(e,r,i){t(e,r,i)&&n.push(e)}),n}var i=e("./_baseEach");t.exports=r},{"./_baseEach":213}],215:[function(e,t,n){function r(e,t,n,r){for(var i=e.length,o=n+(r?1:-1);r?o--:++o<i;)if(t(e[o],o,e))return o;return-1}t.exports=r},{}],216:[function(e,t,n){function r(e,t,n,a,s){var u=-1,c=e.length;for(n||(n=o),s||(s=[]);++u<c;){var l=e[u];t>0&&n(l)?t>1?r(l,t-1,n,a,s):i(s,l):a||(s[s.length]=l)}return s}var i=e("./_arrayPush"),o=e("./_isFlattenable");t.exports=r},{"./_arrayPush":200,"./_isFlattenable":338}],217:[function(e,t,n){var r=e("./_createBaseFor"),i=r();t.exports=i},{"./_createBaseFor":291}],218:[function(e,t,n){function r(e,t){return e&&i(e,t,o)}var i=e("./_baseFor"),o=e("./keys");t.exports=r},{"./_baseFor":217,"./keys":439}],219:[function(e,t,n){function r(e,t){t=i(t,e);for(var n=0,r=t.length;null!=e&&n<r;)e=e[o(t[n++])];return n&&n==r?e:void 0}var i=e("./_castPath"),o=e("./_toKey");t.exports=r},{"./_castPath":267,"./_toKey":389}],220:[function(e,t,n){function r(e,t,n){var r=t(e);return o(e)?r:i(r,n(e))}var i=e("./_arrayPush"),o=e("./isArray");t.exports=r},{"./_arrayPush":200,"./isArray":420}],221:[function(e,t,n){function r(e){return null==e?void 0===e?u:s:c&&c in Object(e)?o(e):a(e)}var i=e("./_Symbol"),o=e("./_getRawTag"),a=e("./_objectToString"),s="[object Null]",u="[object Undefined]",c=i?i.toStringTag:void 0;t.exports=r},{"./_Symbol":188,"./_getRawTag":321,"./_objectToString":366}],222:[function(e,t,n){function r(e,t){return null!=e&&o.call(e,t)}var i=Object.prototype,o=i.hasOwnProperty;t.exports=r},{}],223:[function(e,t,n){function r(e,t){return null!=e&&t in Object(e)}t.exports=r},{}],224:[function(e,t,n){function r(e,t,n){return t===t?a(e,t,n):i(e,o,n)}var i=e("./_baseFindIndex"),o=e("./_baseIsNaN"),a=e("./_strictIndexOf");t.exports=r},{"./_baseFindIndex":215,"./_baseIsNaN":231,"./_strictIndexOf":386}],225:[function(e,t,n){function r(e,t,n){for(var r=n?a:o,f=e[0].length,p=e.length,d=p,h=Array(p),m=1/0,v=[];d--;){var y=e[d];d&&t&&(y=s(y,u(t))),m=l(y.length,m),h[d]=!n&&(t||f>=120&&y.length>=120)?new i(d&&y):void 0}y=e[0];var g=-1,b=h[0];e:for(;++g<f&&v.length<m;){var _=y[g],w=t?t(_):_;if(_=n||0!==_?_:0,!(b?c(b,w):r(v,w,n))){for(d=p;--d;){var C=h[d];if(!(C?c(C,w):r(e[d],w,n)))continue e}b&&b.push(w),v.push(_)}}return v}var i=e("./_SetCache"),o=e("./_arrayIncludes"),a=e("./_arrayIncludesWith"),s=e("./_arrayMap"),u=e("./_baseUnary"),c=e("./_cacheHas"),l=Math.min;t.exports=r},{"./_SetCache":186,"./_arrayIncludes":196,"./_arrayIncludesWith":197,"./_arrayMap":199,"./_baseUnary":260,"./_cacheHas":264}],226:[function(e,t,n){function r(e,t,n,r){return i(e,function(e,i,o){t(r,n(e),i,o)}),r}var i=e("./_baseForOwn");t.exports=r},{"./_baseForOwn":218}],227:[function(e,t,n){function r(e){return o(e)&&i(e)==a}var i=e("./_baseGetTag"),o=e("./isObjectLike"),a="[object Arguments]";t.exports=r},{"./_baseGetTag":221,"./isObjectLike":433}],228:[function(e,t,n){function r(e,t,n,a,s){return e===t||(null==e||null==t||!o(e)&&!o(t)?e!==e&&t!==t:i(e,t,n,a,r,s))}var i=e("./_baseIsEqualDeep"),o=e("./isObjectLike");t.exports=r},{"./_baseIsEqualDeep":229,"./isObjectLike":433}],229:[function(e,t,n){function r(e,t,n,r,v,g){var b=c(e),_=c(t),w=b?h:u(e),C=_?h:u(t);w=w==d?m:w,C=C==d?m:C;var j=w==m,x=C==m,R=w==C;if(R&&l(e)){if(!l(t))return!1;b=!0,j=!1}if(R&&!j)return g||(g=new i),b||f(e)?o(e,t,n,r,v,g):a(e,t,w,n,r,v,g);if(!(n&p)){var P=j&&y.call(e,"__wrapped__"),E=x&&y.call(t,"__wrapped__");if(P||E){var O=P?e.value():e,S=E?t.value():t;return g||(g=new i),v(O,S,n,r,g)}}return!!R&&(g||(g=new i),s(e,t,n,r,v,g))}var i=e("./_Stack"),o=e("./_equalArrays"),a=e("./_equalByTag"),s=e("./_equalObjects"),u=e("./_getTag"),c=e("./isArray"),l=e("./isBuffer"),f=e("./isTypedArray"),p=1,d="[object Arguments]",h="[object Array]",m="[object Object]",v=Object.prototype,y=v.hasOwnProperty;t.exports=r},{"./_Stack":187,"./_equalArrays":307,"./_equalByTag":308,"./_equalObjects":309,"./_getTag":324,"./isArray":420,"./isBuffer":424,"./isTypedArray":437}],230:[function(e,t,n){function r(e,t,n,r){var u=n.length,c=u,l=!r;if(null==e)return!c;for(e=Object(e);u--;){var f=n[u];if(l&&f[2]?f[1]!==e[f[0]]:!(f[0]in e))return!1}for(;++u<c;){f=n[u];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 m=new i;if(r)var v=r(d,h,p,e,t,m);if(!(void 0===v?o(h,d,a|s,r,m):v))return!1}}return!0}var i=e("./_Stack"),o=e("./_baseIsEqual"),a=1,s=2;t.exports=r},{"./_Stack":187,"./_baseIsEqual":228}],231:[function(e,t,n){function r(e){return e!==e}t.exports=r},{}],232:[function(e,t,n){function r(e){if(!a(e)||o(e))return!1;var t=i(e)?h:c;return t.test(s(e))}var i=e("./isFunction"),o=e("./_isMasked"),a=e("./isObject"),s=e("./_toSource"),u=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,l=Function.prototype,f=Object.prototype,p=l.toString,d=f.hasOwnProperty,h=RegExp("^"+p.call(d).replace(u,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=r},{"./_isMasked":344,"./_toSource":390,"./isFunction":427,"./isObject":432}],233:[function(e,t,n){function r(e){return a(e)&&o(e.length)&&!!k[i(e)]}var i=e("./_baseGetTag"),o=e("./isLength"),a=e("./isObjectLike"),s="[object Arguments]",u="[object Array]",c="[object Boolean]",l="[object Date]",f="[object Error]",p="[object Function]",d="[object Map]",h="[object Number]",m="[object Object]",v="[object RegExp]",y="[object Set]",g="[object String]",b="[object WeakMap]",_="[object ArrayBuffer]",w="[object DataView]",C="[object Float32Array]",j="[object Float64Array]",x="[object Int8Array]",R="[object Int16Array]",P="[object Int32Array]",E="[object Uint8Array]",O="[object Uint8ClampedArray]",S="[object Uint16Array]",T="[object Uint32Array]",k={};k[C]=k[j]=k[x]=k[R]=k[P]=k[E]=k[O]=k[S]=k[T]=!0,k[s]=k[u]=k[_]=k[c]=k[w]=k[l]=k[f]=k[p]=k[d]=k[h]=k[m]=k[v]=k[y]=k[g]=k[b]=!1,t.exports=r},{"./_baseGetTag":221,"./isLength":428,"./isObjectLike":433}],234:[function(e,t,n){function r(e){return"function"==typeof e?e:null==e?a:"object"==typeof e?s(e)?o(e[0],e[1]):i(e):u(e)}var i=e("./_baseMatches"),o=e("./_baseMatchesProperty"),a=e("./identity"),s=e("./isArray"),u=e("./property");t.exports=r},{"./_baseMatches":239,"./_baseMatchesProperty":240,"./identity":414,"./isArray":420,"./property":455}],235:[function(e,t,n){function r(e){if(!i(e))return o(e);var t=[];for(var n in Object(e))s.call(e,n)&&"constructor"!=n&&t.push(n);return t}var i=e("./_isPrototype"),o=e("./_nativeKeys"),a=Object.prototype,s=a.hasOwnProperty;t.exports=r},{"./_isPrototype":345,"./_nativeKeys":363}],236:[function(e,t,n){function r(e){if(!i(e))return a(e);var t=o(e),n=[];for(var r in e)("constructor"!=r||!t&&u.call(e,r))&&n.push(r);return n}var i=e("./isObject"),o=e("./_isPrototype"),a=e("./_nativeKeysIn"),s=Object.prototype,u=s.hasOwnProperty;t.exports=r},{"./_isPrototype":345,"./_nativeKeysIn":364,"./isObject":432}],237:[function(e,t,n){function r(){}t.exports=r},{}],238:[function(e,t,n){function r(e,t){var n=-1,r=o(e)?Array(e.length):[];return i(e,function(e,i,o){r[++n]=t(e,i,o)}),r}var i=e("./_baseEach"),o=e("./isArrayLike");t.exports=r},{"./_baseEach":213,"./isArrayLike":421}],239:[function(e,t,n){function r(e){var t=o(e);return 1==t.length&&t[0][2]?a(t[0][0],t[0][1]):function(n){return n===e||i(n,e,t)}}var i=e("./_baseIsMatch"),o=e("./_getMatchData"),a=e("./_matchesStrictComparable");t.exports=r},{"./_baseIsMatch":230,"./_getMatchData":318,"./_matchesStrictComparable":358}],240:[function(e,t,n){function r(e,t){return s(e)&&u(t)?c(l(e),t):function(n){var r=o(n,e);return void 0===r&&r===t?a(n,e):i(t,r,f|p)}}var i=e("./_baseIsEqual"),o=e("./get"),a=e("./hasIn"),s=e("./_isKey"),u=e("./_isStrictComparable"),c=e("./_matchesStrictComparable"),l=e("./_toKey"),f=1,p=2;t.exports=r},{"./_baseIsEqual":228,"./_isKey":341,"./_isStrictComparable":346,"./_matchesStrictComparable":358,"./_toKey":389,"./get":411,"./hasIn":413}],241:[function(e,t,n){function r(e,t,n,l,f){e!==t&&a(t,function(a,c){if(u(a))f||(f=new i),s(e,t,c,n,r,l,f);else{var p=l?l(e[c],a,c+"",e,t,f):void 0;void 0===p&&(p=a),o(e,c,p)}},c)}var i=e("./_Stack"),o=e("./_assignMergeValue"),a=e("./_baseFor"),s=e("./_baseMergeDeep"),u=e("./isObject"),c=e("./keysIn");t.exports=r},{"./_Stack":187,"./_assignMergeValue":204,"./_baseFor":217,"./_baseMergeDeep":242,"./isObject":432,"./keysIn":440}],242:[function(e,t,n){function r(e,t,n,r,g,b,_){var w=e[n],C=t[n],j=_.get(C);if(j)return void i(e,n,j);var x=b?b(w,C,n+"",e,t,_):void 0,R=void 0===x;if(R){var P=l(C),E=!P&&p(C),O=!P&&!E&&v(C);x=C,P||E||O?l(w)?x=w:f(w)?x=s(w):E?(R=!1,x=o(C,!0)):O?(R=!1,x=a(C,!0)):x=[]:m(C)||c(C)?(x=w,c(w)?x=y(w):(!h(w)||r&&d(w))&&(x=u(C))):R=!1}R&&(_.set(C,x),g(x,C,r,b,_),_["delete"](C)),i(e,n,x)}var i=e("./_assignMergeValue"),o=e("./_cloneBuffer"),a=e("./_cloneTypedArray"),s=e("./_copyArray"),u=e("./_initCloneObject"),c=e("./isArguments"),l=e("./isArray"),f=e("./isArrayLikeObject"),p=e("./isBuffer"),d=e("./isFunction"),h=e("./isObject"),m=e("./isPlainObject"),v=e("./isTypedArray"),y=e("./toPlainObject");t.exports=r},{"./_assignMergeValue":204,"./_cloneBuffer":272,"./_cloneTypedArray":278,"./_copyArray":283,"./_initCloneObject":336,"./isArguments":419,"./isArray":420,"./isArrayLikeObject":422,"./isBuffer":424,"./isFunction":427,"./isObject":432,"./isPlainObject":434,"./isTypedArray":437,"./toPlainObject":466}],243:[function(e,t,n){function r(e,t,n){var r=-1;t=i(t.length?t:[l],u(o));var f=a(e,function(e,n,o){var a=i(t,function(t){return t(e)});return{criteria:a,index:++r,value:e}});return s(f,function(e,t){return c(e,t,n)})}var i=e("./_arrayMap"),o=e("./_baseIteratee"),a=e("./_baseMap"),s=e("./_baseSortBy"),u=e("./_baseUnary"),c=e("./_compareMultiple"),l=e("./identity");t.exports=r},{"./_arrayMap":199,"./_baseIteratee":234,"./_baseMap":238,"./_baseSortBy":256,"./_baseUnary":260,"./_compareMultiple":280,"./identity":414}],244:[function(e,t,n){function r(e,t){return i(e,t,function(t,n){return o(e,n)})}var i=e("./_basePickBy"),o=e("./hasIn");t.exports=r},{"./_basePickBy":245,"./hasIn":413}],245:[function(e,t,n){function r(e,t,n){for(var r=-1,s=t.length,u={};++r<s;){var c=t[r],l=i(e,c);n(l,c)&&o(u,a(c,e),l)}return u}var i=e("./_baseGet"),o=e("./_baseSet"),a=e("./_castPath");t.exports=r},{"./_baseGet":219,"./_baseSet":251,"./_castPath":267}],246:[function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}t.exports=r},{}],247:[function(e,t,n){function r(e){return function(t){return i(t,e)}}var i=e("./_baseGet");t.exports=r},{"./_baseGet":219}],248:[function(e,t,n){function r(e,t,n,r){for(var a=-1,s=o(i((t-e)/(n||1)),0),u=Array(s);s--;)u[r?s:++a]=e,e+=n;return u}var i=Math.ceil,o=Math.max;t.exports=r},{}],249:[function(e,t,n){function r(e,t,n,r,i){return i(e,function(e,i,o){n=r?(r=!1,e):t(n,e,i,o)}),n}t.exports=r},{}],250:[function(e,t,n){function r(e,t){return a(o(e,t,i),e+"")}var i=e("./identity"),o=e("./_overRest"),a=e("./_setToString");t.exports=r},{"./_overRest":368,"./_setToString":378,"./identity":414}],251:[function(e,t,n){function r(e,t,n,r){if(!s(e))return e;t=o(t,e);for(var c=-1,l=t.length,f=l-1,p=e;null!=p&&++c<l;){var d=u(t[c]),h=n;if(c!=f){var m=p[d];h=r?r(m,d,p):void 0,void 0===h&&(h=s(m)?m:a(t[c+1])?[]:{})}i(p,d,h),p=p[d]}return e}var i=e("./_assignValue"),o=e("./_castPath"),a=e("./_isIndex"),s=e("./isObject"),u=e("./_toKey");t.exports=r},{"./_assignValue":205,"./_castPath":267,"./_isIndex":339,"./_toKey":389,"./isObject":432}],252:[function(e,t,n){var r=e("./identity"),i=e("./_metaMap"),o=i?function(e,t){return i.set(e,t),e}:r;t.exports=o},{"./_metaMap":361,"./identity":414}],253:[function(e,t,n){var r=e("./constant"),i=e("./_defineProperty"),o=e("./identity"),a=i?function(e,t){return i(e,"toString",{configurable:!0,enumerable:!1,value:r(t),writable:!0})}:o;t.exports=a},{"./_defineProperty":306,"./constant":400,"./identity":414}],254:[function(e,t,n){function r(e,t,n){var r=-1,i=e.length;t<0&&(t=-t>i?0:i+t),n=n>i?i:n,n<0&&(n+=i),i=t>n?0:n-t>>>0,t>>>=0;for(var o=Array(i);++r<i;)o[r]=e[r+t];return o}t.exports=r},{}],255:[function(e,t,n){function r(e,t){var n;return i(e,function(e,r,i){return n=t(e,r,i),!n}),!!n}var i=e("./_baseEach");t.exports=r},{"./_baseEach":213}],256:[function(e,t,n){function r(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}t.exports=r},{}],257:[function(e,t,n){function r(e,t){for(var n,r=-1,i=e.length;++r<i;){var o=t(e[r]);void 0!==o&&(n=void 0===n?o:n+o)}return n}t.exports=r},{}],258:[function(e,t,n){function r(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}t.exports=r},{}],259:[function(e,t,n){function r(e){if("string"==typeof e)return e;if(a(e))return o(e,r)+"";if(s(e))return l?l.call(e):"";var t=e+"";return"0"==t&&1/e==-u?"-0":t}var i=e("./_Symbol"),o=e("./_arrayMap"),a=e("./isArray"),s=e("./isSymbol"),u=1/0,c=i?i.prototype:void 0,l=c?c.toString:void 0;t.exports=r},{"./_Symbol":188,"./_arrayMap":199,"./isArray":420,"./isSymbol":436}],260:[function(e,t,n){function r(e){return function(t){return e(t)}}t.exports=r},{}],261:[function(e,t,n){function r(e,t,n){var r=-1,f=o,p=e.length,d=!0,h=[],m=h;if(n)d=!1,f=a;else if(p>=l){var v=t?null:u(e);if(v)return c(v);d=!1,f=s,m=new i}else m=t?[]:h;e:for(;++r<p;){var y=e[r],g=t?t(y):y;if(y=n||0!==y?y:0,d&&g===g){for(var b=m.length;b--;)if(m[b]===g)continue e;t&&m.push(g),h.push(y)}else f(m,g,n)||(m!==h&&m.push(g),h.push(y))}return h}var i=e("./_SetCache"),o=e("./_arrayIncludes"),a=e("./_arrayIncludesWith"),s=e("./_cacheHas"),u=e("./_createSet"),c=e("./_setToArray"),l=200;t.exports=r},{"./_SetCache":186,"./_arrayIncludes":196,"./_arrayIncludesWith":197,"./_cacheHas":264,"./_createSet":301,"./_setToArray":377}],262:[function(e,t,n){function r(e,t){return t=i(t,e),e=a(e,t),null==e||delete e[s(o(t))]}var i=e("./_castPath"),o=e("./last"),a=e("./_parent"),s=e("./_toKey");t.exports=r},{"./_castPath":267,"./_parent":369,"./_toKey":389,"./last":441}],263:[function(e,t,n){function r(e,t){return i(t,function(t){return e[t]})}var i=e("./_arrayMap");t.exports=r},{"./_arrayMap":199}],264:[function(e,t,n){function r(e,t){return e.has(t)}t.exports=r},{}],265:[function(e,t,n){function r(e){return i(e)?e:[]}var i=e("./isArrayLikeObject");t.exports=r},{"./isArrayLikeObject":422}],266:[function(e,t,n){function r(e){return"function"==typeof e?e:i}var i=e("./identity");t.exports=r},{"./identity":414}],267:[function(e,t,n){function r(e,t){return i(e)?e:o(e,t)?[e]:a(s(e))}var i=e("./isArray"),o=e("./_isKey"),a=e("./_stringToPath"),s=e("./toString");t.exports=r},{"./_isKey":341,"./_stringToPath":388,"./isArray":420,"./toString":467}],268:[function(e,t,n){function r(e,t,n){var r=e.length;return n=void 0===n?r:n,!t&&n>=r?e:i(e,t,n)}var i=e("./_baseSlice");t.exports=r},{"./_baseSlice":254}],269:[function(e,t,n){function r(e,t){for(var n=e.length;n--&&i(t,e[n],0)>-1;);return n}var i=e("./_baseIndexOf");t.exports=r},{"./_baseIndexOf":224}],270:[function(e,t,n){function r(e,t){for(var n=-1,r=e.length;++n<r&&i(t,e[n],0)>-1;);return n}var i=e("./_baseIndexOf");t.exports=r},{"./_baseIndexOf":224}],271:[function(e,t,n){function r(e){var t=new e.constructor(e.byteLength);return new i(t).set(new i(e)),t}var i=e("./_Uint8Array");t.exports=r},{"./_Uint8Array":189}],272:[function(e,t,n){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 i=e("./_root"),o="object"==typeof n&&n&&!n.nodeType&&n,a=o&&"object"==typeof t&&t&&!t.nodeType&&t,s=a&&a.exports===o,u=s?i.Buffer:void 0,c=u?u.allocUnsafe:void 0;t.exports=r},{"./_root":373}],273:[function(e,t,n){function r(e,t){var n=t?i(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var i=e("./_cloneArrayBuffer");t.exports=r},{"./_cloneArrayBuffer":271}],274:[function(e,t,n){function r(e,t,n){var r=t?n(a(e),s):a(e);return o(r,i,new e.constructor)}var i=e("./_addMapEntry"),o=e("./_arrayReduce"),a=e("./_mapToArray"),s=1;t.exports=r},{"./_addMapEntry":191,"./_arrayReduce":201,"./_mapToArray":357}],275:[function(e,t,n){function r(e){var t=new e.constructor(e.source,i.exec(e));return t.lastIndex=e.lastIndex,t}var i=/\w*$/;t.exports=r},{}],276:[function(e,t,n){function r(e,t,n){var r=t?n(a(e),s):a(e);return o(r,i,new e.constructor)}var i=e("./_addSetEntry"),o=e("./_arrayReduce"),a=e("./_setToArray"),s=1;t.exports=r},{"./_addSetEntry":192,"./_arrayReduce":201,"./_setToArray":377}],277:[function(e,t,n){function r(e){return a?Object(a.call(e)):{}}var i=e("./_Symbol"),o=i?i.prototype:void 0,a=o?o.valueOf:void 0;t.exports=r},{"./_Symbol":188}],278:[function(e,t,n){function r(e,t){var n=t?i(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}var i=e("./_cloneArrayBuffer");t.exports=r},{"./_cloneArrayBuffer":271}],279:[function(e,t,n){function r(e,t){if(e!==t){var n=void 0!==e,r=null===e,o=e===e,a=i(e),s=void 0!==t,u=null===t,c=t===t,l=i(t); if(!u&&!l&&!a&&e>t||a&&s&&c&&!u&&!l||r&&s&&c||!n&&c||!o)return 1;if(!r&&!a&&!l&&e<t||l&&n&&o&&!r&&!a||u&&n&&o||!s&&o||!c)return-1}return 0}var i=e("./isSymbol");t.exports=r},{"./isSymbol":436}],280:[function(e,t,n){function r(e,t,n){for(var r=-1,o=e.criteria,a=t.criteria,s=o.length,u=n.length;++r<s;){var c=i(o[r],a[r]);if(c){if(r>=u)return c;var l=n[r];return c*("desc"==l?-1:1)}}return e.index-t.index}var i=e("./_compareAscending");t.exports=r},{"./_compareAscending":279}],281:[function(e,t,n){function r(e,t,n,r){for(var o=-1,a=e.length,s=n.length,u=-1,c=t.length,l=i(a-s,0),f=Array(c+l),p=!r;++u<c;)f[u]=t[u];for(;++o<s;)(p||o<a)&&(f[n[o]]=e[o]);for(;l--;)f[u++]=e[o++];return f}var i=Math.max;t.exports=r},{}],282:[function(e,t,n){function r(e,t,n,r){for(var o=-1,a=e.length,s=-1,u=n.length,c=-1,l=t.length,f=i(a-u,0),p=Array(f+l),d=!r;++o<f;)p[o]=e[o];for(var h=o;++c<l;)p[h+c]=t[c];for(;++s<u;)(d||o<a)&&(p[h+n[s]]=e[o++]);return p}var i=Math.max;t.exports=r},{}],283:[function(e,t,n){function r(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}t.exports=r},{}],284:[function(e,t,n){function r(e,t,n,r){var a=!n;n||(n={});for(var s=-1,u=t.length;++s<u;){var c=t[s],l=r?r(n[c],e[c],c,n,e):void 0;void 0===l&&(l=e[c]),a?o(n,c,l):i(n,c,l)}return n}var i=e("./_assignValue"),o=e("./_baseAssignValue");t.exports=r},{"./_assignValue":205,"./_baseAssignValue":209}],285:[function(e,t,n){function r(e,t){return i(e,o(e),t)}var i=e("./_copyObject"),o=e("./_getSymbols");t.exports=r},{"./_copyObject":284,"./_getSymbols":322}],286:[function(e,t,n){function r(e,t){return i(e,o(e),t)}var i=e("./_copyObject"),o=e("./_getSymbolsIn");t.exports=r},{"./_copyObject":284,"./_getSymbolsIn":323}],287:[function(e,t,n){var r=e("./_root"),i=r["__core-js_shared__"];t.exports=i},{"./_root":373}],288:[function(e,t,n){function r(e,t){for(var n=e.length,r=0;n--;)e[n]===t&&++r;return r}t.exports=r},{}],289:[function(e,t,n){function r(e){return i(function(t,n){var r=-1,i=n.length,a=i>1?n[i-1]:void 0,s=i>2?n[2]:void 0;for(a=e.length>3&&"function"==typeof a?(i--,a):void 0,s&&o(n[0],n[1],s)&&(a=i<3?void 0:a,i=1),t=Object(t);++r<i;){var u=n[r];u&&e(t,u,r,a)}return t})}var i=e("./_baseRest"),o=e("./_isIterateeCall");t.exports=r},{"./_baseRest":250,"./_isIterateeCall":340}],290:[function(e,t,n){function r(e,t){return function(n,r){if(null==n)return n;if(!i(n))return e(n,r);for(var o=n.length,a=t?o:-1,s=Object(n);(t?a--:++a<o)&&r(s[a],a,s)!==!1;);return n}}var i=e("./isArrayLike");t.exports=r},{"./isArrayLike":421}],291:[function(e,t,n){function r(e){return function(t,n,r){for(var i=-1,o=Object(t),a=r(t),s=a.length;s--;){var u=a[e?s:++i];if(n(o[u],u,o)===!1)break}return t}}t.exports=r},{}],292:[function(e,t,n){function r(e,t,n){function r(){var t=this&&this!==o&&this instanceof r?u:e;return t.apply(s?n:this,arguments)}var s=t&a,u=i(e);return r}var i=e("./_createCtor"),o=e("./_root"),a=1;t.exports=r},{"./_createCtor":293,"./_root":373}],293:[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=i(e.prototype),r=e.apply(n,t);return o(r)?r:n}}var i=e("./_baseCreate"),o=e("./isObject");t.exports=r},{"./_baseCreate":212,"./isObject":432}],294:[function(e,t,n){function r(e,t,n){function r(){for(var o=arguments.length,p=Array(o),d=o,h=u(r);d--;)p[d]=arguments[d];var m=o<3&&p[0]!==h&&p[o-1]!==h?[]:c(p,h);if(o-=m.length,o<n)return s(e,t,a,r.placeholder,void 0,p,m,void 0,void 0,n-o);var v=this&&this!==l&&this instanceof r?f:e;return i(v,this,p)}var f=o(e);return r}var i=e("./_apply"),o=e("./_createCtor"),a=e("./_createHybrid"),s=e("./_createRecurry"),u=e("./_getHolder"),c=e("./_replaceHolders"),l=e("./_root");t.exports=r},{"./_apply":193,"./_createCtor":293,"./_createHybrid":296,"./_createRecurry":300,"./_getHolder":316,"./_replaceHolders":372,"./_root":373}],295:[function(e,t,n){function r(e){return function(t,n,r){var s=Object(t);if(!o(t)){var u=i(n,3);t=a(t),n=function(e){return u(s[e],e,s)}}var c=e(t,n,r);return c>-1?s[u?t[c]:c]:void 0}}var i=e("./_baseIteratee"),o=e("./isArrayLike"),a=e("./keys");t.exports=r},{"./_baseIteratee":234,"./isArrayLike":421,"./keys":439}],296:[function(e,t,n){function r(e,t,n,b,_,w,C,j,x,R){function P(){for(var d=arguments.length,h=Array(d),m=d;m--;)h[m]=arguments[m];if(T)var v=c(P),y=a(h,v);if(b&&(h=i(h,b,_,T)),w&&(h=o(h,w,C,T)),d-=y,T&&d<R){var g=f(h,v);return u(e,t,r,P.placeholder,n,h,g,j,x,R-d)}var A=O?n:this,I=S?A[e]:e;return d=h.length,j?h=l(h,j):k&&d>1&&h.reverse(),E&&x<d&&(h.length=x),this&&this!==p&&this instanceof P&&(I=M||s(I)),I.apply(A,h)}var E=t&y,O=t&d,S=t&h,T=t&(m|v),k=t&g,M=S?void 0:s(e);return P}var i=e("./_composeArgs"),o=e("./_composeArgsRight"),a=e("./_countHolders"),s=e("./_createCtor"),u=e("./_createRecurry"),c=e("./_getHolder"),l=e("./_reorder"),f=e("./_replaceHolders"),p=e("./_root"),d=1,h=2,m=8,v=16,y=128,g=512;t.exports=r},{"./_composeArgs":281,"./_composeArgsRight":282,"./_countHolders":288,"./_createCtor":293,"./_createRecurry":300,"./_getHolder":316,"./_reorder":371,"./_replaceHolders":372,"./_root":373}],297:[function(e,t,n){function r(e,t){return function(n,r){return i(n,e,t(r),{})}}var i=e("./_baseInverter");t.exports=r},{"./_baseInverter":226}],298:[function(e,t,n){function r(e,t,n,r){function u(){for(var t=-1,o=arguments.length,s=-1,f=r.length,p=Array(f+o),d=this&&this!==a&&this instanceof u?l:e;++s<f;)p[s]=r[s];for(;o--;)p[s++]=arguments[++t];return i(d,c?n:this,p)}var c=t&s,l=o(e);return u}var i=e("./_apply"),o=e("./_createCtor"),a=e("./_root"),s=1;t.exports=r},{"./_apply":193,"./_createCtor":293,"./_root":373}],299:[function(e,t,n){function r(e){return function(t,n,r){return r&&"number"!=typeof r&&o(t,n,r)&&(n=r=void 0),t=a(t),void 0===n?(n=t,t=0):n=a(n),r=void 0===r?t<n?1:-1:a(r),i(t,n,r,e)}}var i=e("./_baseRange"),o=e("./_isIterateeCall"),a=e("./toFinite");t.exports=r},{"./_baseRange":248,"./_isIterateeCall":340,"./toFinite":463}],300:[function(e,t,n){function r(e,t,n,r,d,h,m,v,y,g){var b=t&l,_=b?m:void 0,w=b?void 0:m,C=b?h:void 0,j=b?void 0:h;t|=b?f:p,t&=~(b?p:f),t&c||(t&=~(s|u));var x=[e,t,d,C,_,j,w,v,y,g],R=n.apply(void 0,x);return i(e)&&o(R,x),R.placeholder=r,a(R,e,t)}var i=e("./_isLaziable"),o=e("./_setData"),a=e("./_setWrapToString"),s=1,u=2,c=4,l=8,f=32,p=64;t.exports=r},{"./_isLaziable":343,"./_setData":376,"./_setWrapToString":379}],301:[function(e,t,n){var r=e("./_Set"),i=e("./noop"),o=e("./_setToArray"),a=1/0,s=r&&1/o(new r([,-0]))[1]==a?function(e){return new r(e)}:i;t.exports=s},{"./_Set":185,"./_setToArray":377,"./noop":448}],302:[function(e,t,n){function r(e,t,n,r,C,j,x,R){var P=t&v;if(!P&&"function"!=typeof e)throw new TypeError(h);var E=r?r.length:0;if(E||(t&=~(b|_),r=C=void 0),x=void 0===x?x:w(d(x),0),R=void 0===R?R:d(R),E-=C?C.length:0,t&_){var O=r,S=C;r=C=void 0}var T=P?void 0:c(e),k=[e,t,n,r,C,O,S,j,x,R];if(T&&l(k,T),e=k[0],t=k[1],n=k[2],r=k[3],C=k[4],R=k[9]=void 0===k[9]?P?0:e.length:w(k[9]-E,0),!R&&t&(y|g)&&(t&=~(y|g)),t&&t!=m)M=t==y||t==g?a(e,t,R):t!=b&&t!=(m|b)||C.length?s.apply(void 0,k):u(e,t,n,r);else var M=o(e,t,n);var A=T?i:f;return p(A(M,k),e,t)}var i=e("./_baseSetData"),o=e("./_createBind"),a=e("./_createCurry"),s=e("./_createHybrid"),u=e("./_createPartial"),c=e("./_getData"),l=e("./_mergeData"),f=e("./_setData"),p=e("./_setWrapToString"),d=e("./toInteger"),h="Expected a function",m=1,v=2,y=8,g=16,b=32,_=64,w=Math.max;t.exports=r},{"./_baseSetData":252,"./_createBind":292,"./_createCurry":294,"./_createHybrid":296,"./_createPartial":298,"./_getData":314,"./_mergeData":360,"./_setData":376,"./_setWrapToString":379,"./toInteger":464}],303:[function(e,t,n){function r(e,t,n,r){return void 0===e||i(e,o[n])&&!a.call(r,n)?t:e}var i=e("./eq"),o=Object.prototype,a=o.hasOwnProperty;t.exports=r},{"./eq":404}],304:[function(e,t,n){function r(e,t,n,a,s,u){return o(e)&&o(t)&&(u.set(t,e),i(e,t,void 0,r,u),u["delete"](t)),e}var i=e("./_baseMerge"),o=e("./isObject");t.exports=r},{"./_baseMerge":241,"./isObject":432}],305:[function(e,t,n){function r(e){return i(e)?void 0:e}var i=e("./isPlainObject");t.exports=r},{"./isPlainObject":434}],306:[function(e,t,n){var r=e("./_getNative"),i=function(){try{var e=r(Object,"defineProperty");return e({},"",{}),e}catch(t){}}();t.exports=i},{"./_getNative":319}],307:[function(e,t,n){function r(e,t,n,r,c,l){var f=n&s,p=e.length,d=t.length;if(p!=d&&!(f&&d>p))return!1;var h=l.get(e);if(h&&l.get(t))return h==t;var m=-1,v=!0,y=n&u?new i:void 0;for(l.set(e,t),l.set(t,e);++m<p;){var g=e[m],b=t[m];if(r)var _=f?r(b,g,m,t,e,l):r(g,b,m,e,t,l);if(void 0!==_){if(_)continue;v=!1;break}if(y){if(!o(t,function(e,t){if(!a(y,t)&&(g===e||c(g,e,n,r,l)))return y.push(t)})){v=!1;break}}else if(g!==b&&!c(g,b,n,r,l)){v=!1;break}}return l["delete"](e),l["delete"](t),v}var i=e("./_SetCache"),o=e("./_arraySome"),a=e("./_cacheHas"),s=1,u=2;t.exports=r},{"./_SetCache":186,"./_arraySome":202,"./_cacheHas":264}],308:[function(e,t,n){function r(e,t,n,r,i,j,R){switch(n){case C:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case w:return!(e.byteLength!=t.byteLength||!j(new o(e),new o(t)));case p:case d:case v:return a(+e,+t);case h:return e.name==t.name&&e.message==t.message;case y:case b:return e==t+"";case m:var P=u;case g:var E=r&l;if(P||(P=c),e.size!=t.size&&!E)return!1;var O=R.get(e);if(O)return O==t;r|=f,R.set(e,t);var S=s(P(e),P(t),r,i,j,R);return R["delete"](e),S;case _:if(x)return x.call(e)==x.call(t)}return!1}var i=e("./_Symbol"),o=e("./_Uint8Array"),a=e("./eq"),s=e("./_equalArrays"),u=e("./_mapToArray"),c=e("./_setToArray"),l=1,f=2,p="[object Boolean]",d="[object Date]",h="[object Error]",m="[object Map]",v="[object Number]",y="[object RegExp]",g="[object Set]",b="[object String]",_="[object Symbol]",w="[object ArrayBuffer]",C="[object DataView]",j=i?i.prototype:void 0,x=j?j.valueOf:void 0;t.exports=r},{"./_Symbol":188,"./_Uint8Array":189,"./_equalArrays":307,"./_mapToArray":357,"./_setToArray":377,"./eq":404}],309:[function(e,t,n){function r(e,t,n,r,a,u){var c=n&o,l=i(e),f=l.length,p=i(t),d=p.length;if(f!=d&&!c)return!1;for(var h=f;h--;){var m=l[h];if(!(c?m in t:s.call(t,m)))return!1}var v=u.get(e);if(v&&u.get(t))return v==t;var y=!0;u.set(e,t),u.set(t,e);for(var g=c;++h<f;){m=l[h];var b=e[m],_=t[m];if(r)var w=c?r(_,b,m,t,e,u):r(b,_,m,e,t,u);if(!(void 0===w?b===_||a(b,_,n,r,u):w)){y=!1;break}g||(g="constructor"==m)}if(y&&!g){var C=e.constructor,j=t.constructor;C!=j&&"constructor"in e&&"constructor"in t&&!("function"==typeof C&&C instanceof C&&"function"==typeof j&&j instanceof j)&&(y=!1)}return u["delete"](e),u["delete"](t),y}var i=e("./_getAllKeys"),o=1,a=Object.prototype,s=a.hasOwnProperty;t.exports=r},{"./_getAllKeys":312}],310:[function(e,t,n){function r(e){return a(o(e,void 0,i),e+"")}var i=e("./flatten"),o=e("./_overRest"),a=e("./_setToString");t.exports=r},{"./_overRest":368,"./_setToString":378,"./flatten":408}],311:[function(e,t,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],312:[function(e,t,n){function r(e){return i(e,a,o)}var i=e("./_baseGetAllKeys"),o=e("./_getSymbols"),a=e("./keys");t.exports=r},{"./_baseGetAllKeys":220,"./_getSymbols":322,"./keys":439}],313:[function(e,t,n){function r(e){return i(e,a,o)}var i=e("./_baseGetAllKeys"),o=e("./_getSymbolsIn"),a=e("./keysIn");t.exports=r},{"./_baseGetAllKeys":220,"./_getSymbolsIn":323,"./keysIn":440}],314:[function(e,t,n){var r=e("./_metaMap"),i=e("./noop"),o=r?function(e){return r.get(e)}:i;t.exports=o},{"./_metaMap":361,"./noop":448}],315:[function(e,t,n){function r(e){for(var t=e.name+"",n=i[t],r=a.call(i,t)?n.length:0;r--;){var o=n[r],s=o.func;if(null==s||s==e)return o.name}return t}var i=e("./_realNames"),o=Object.prototype,a=o.hasOwnProperty;t.exports=r},{"./_realNames":370}],316:[function(e,t,n){function r(e){var t=e;return t.placeholder}t.exports=r},{}],317:[function(e,t,n){function r(e,t){var n=e.__data__;return i(t)?n["string"==typeof t?"string":"hash"]:n.map}var i=e("./_isKeyable");t.exports=r},{"./_isKeyable":342}],318:[function(e,t,n){function r(e){for(var t=o(e),n=t.length;n--;){var r=t[n],a=e[r];t[n]=[r,a,i(a)]}return t}var i=e("./_isStrictComparable"),o=e("./keys");t.exports=r},{"./_isStrictComparable":346,"./keys":439}],319:[function(e,t,n){function r(e,t){var n=o(e,t);return i(n)?n:void 0}var i=e("./_baseIsNative"),o=e("./_getValue");t.exports=r},{"./_baseIsNative":232,"./_getValue":325}],320:[function(e,t,n){var r=e("./_overArg"),i=r(Object.getPrototypeOf,Object);t.exports=i},{"./_overArg":367}],321:[function(e,t,n){function r(e){var t=a.call(e,u),n=e[u];try{e[u]=void 0;var r=!0}catch(i){}var o=s.call(e);return r&&(t?e[u]=n:delete e[u]),o}var i=e("./_Symbol"),o=Object.prototype,a=o.hasOwnProperty,s=o.toString,u=i?i.toStringTag:void 0;t.exports=r},{"./_Symbol":188}],322:[function(e,t,n){var r=e("./_arrayFilter"),i=e("./stubArray"),o=Object.prototype,a=o.propertyIsEnumerable,s=Object.getOwnPropertySymbols,u=s?function(e){return null==e?[]:(e=Object(e),r(s(e),function(t){return a.call(e,t)}))}:i;t.exports=u},{"./_arrayFilter":195,"./stubArray":460}],323:[function(e,t,n){var r=e("./_arrayPush"),i=e("./_getPrototype"),o=e("./_getSymbols"),a=e("./stubArray"),s=Object.getOwnPropertySymbols,u=s?function(e){for(var t=[];e;)r(t,o(e)),e=i(e);return t}:a;t.exports=u},{"./_arrayPush":200,"./_getPrototype":320,"./_getSymbols":322,"./stubArray":460}],324:[function(e,t,n){var r=e("./_DataView"),i=e("./_Map"),o=e("./_Promise"),a=e("./_Set"),s=e("./_WeakMap"),u=e("./_baseGetTag"),c=e("./_toSource"),l="[object Map]",f="[object Object]",p="[object Promise]",d="[object Set]",h="[object WeakMap]",m="[object DataView]",v=c(r),y=c(i),g=c(o),b=c(a),_=c(s),w=u;(r&&w(new r(new ArrayBuffer(1)))!=m||i&&w(new i)!=l||o&&w(o.resolve())!=p||a&&w(new a)!=d||s&&w(new s)!=h)&&(w=function(e){var t=u(e),n=t==f?e.constructor:void 0,r=n?c(n):"";if(r)switch(r){case v:return m;case y:return l;case g:return p;case b:return d;case _:return h}return t}),t.exports=w},{"./_DataView":177,"./_Map":182,"./_Promise":184,"./_Set":185,"./_WeakMap":190,"./_baseGetTag":221,"./_toSource":390}],325:[function(e,t,n){function r(e,t){return null==e?void 0:e[t]}t.exports=r},{}],326:[function(e,t,n){function r(e){var t=e.match(i);return t?t[1].split(o):[]}var i=/\{\n\/\* \[wrapped with (.+)\] \*/,o=/,? & /;t.exports=r},{}],327:[function(e,t,n){function r(e,t,n){t=i(t,e);for(var r=-1,l=t.length,f=!1;++r<l;){var p=c(t[r]);if(!(f=null!=e&&n(e,p)))break;e=e[p]}return f||++r!=l?f:(l=null==e?0:e.length,!!l&&u(l)&&s(p,l)&&(a(e)||o(e)))}var i=e("./_castPath"),o=e("./isArguments"),a=e("./isArray"),s=e("./_isIndex"),u=e("./isLength"),c=e("./_toKey");t.exports=r},{"./_castPath":267,"./_isIndex":339,"./_toKey":389,"./isArguments":419,"./isArray":420,"./isLength":428}],328:[function(e,t,n){function r(e){return f.test(e)}var i="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",s="\\u20d0-\\u20ff",u=o+a+s,c="\\ufe0e\\ufe0f",l="\\u200d",f=RegExp("["+l+i+u+c+"]");t.exports=r},{}],329:[function(e,t,n){function r(){this.__data__=i?i(null):{},this.size=0}var i=e("./_nativeCreate");t.exports=r},{"./_nativeCreate":362}],330:[function(e,t,n){function r(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}t.exports=r},{}],331:[function(e,t,n){function r(e){var t=this.__data__;if(i){var n=t[e];return n===o?void 0:n}return s.call(t,e)?t[e]:void 0}var i=e("./_nativeCreate"),o="__lodash_hash_undefined__",a=Object.prototype,s=a.hasOwnProperty;t.exports=r},{"./_nativeCreate":362}],332:[function(e,t,n){function r(e){var t=this.__data__;return i?void 0!==t[e]:a.call(t,e)}var i=e("./_nativeCreate"),o=Object.prototype,a=o.hasOwnProperty;t.exports=r},{"./_nativeCreate":362}],333:[function(e,t,n){function r(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=i&&void 0===t?o:t,this}var i=e("./_nativeCreate"),o="__lodash_hash_undefined__";t.exports=r},{"./_nativeCreate":362}],334:[function(e,t,n){function r(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&o.call(e,"index")&&(n.index=e.index,n.input=e.input),n}var i=Object.prototype,o=i.hasOwnProperty;t.exports=r},{}],335:[function(e,t,n){function r(e,t,n,r){var T=e.constructor;switch(t){case b:return i(e);case f:case p:return new T((+e));case _:return o(e,r);case w:case C:case j:case x:case R:case P:case E:case O:case S:return l(e,r);case d:return a(e,r,n);case h:case y:return new T(e);case m:return s(e);case v:return u(e,r,n);case g:return c(e)}}var i=e("./_cloneArrayBuffer"),o=e("./_cloneDataView"),a=e("./_cloneMap"),s=e("./_cloneRegExp"),u=e("./_cloneSet"),c=e("./_cloneSymbol"),l=e("./_cloneTypedArray"),f="[object Boolean]",p="[object Date]",d="[object Map]",h="[object Number]",m="[object RegExp]",v="[object Set]",y="[object String]",g="[object Symbol]",b="[object ArrayBuffer]",_="[object DataView]",w="[object Float32Array]",C="[object Float64Array]",j="[object Int8Array]",x="[object Int16Array]",R="[object Int32Array]",P="[object Uint8Array]",E="[object Uint8ClampedArray]",O="[object Uint16Array]",S="[object Uint32Array]";t.exports=r},{"./_cloneArrayBuffer":271,"./_cloneDataView":273,"./_cloneMap":274,"./_cloneRegExp":275,"./_cloneSet":276,"./_cloneSymbol":277,"./_cloneTypedArray":278}],336:[function(e,t,n){function r(e){return"function"!=typeof e.constructor||a(e)?{}:i(o(e))}var i=e("./_baseCreate"),o=e("./_getPrototype"),a=e("./_isPrototype");t.exports=r},{"./_baseCreate":212,"./_getPrototype":320,"./_isPrototype":345}],337:[function(e,t,n){function r(e,t){var n=t.length;if(!n)return e;var r=n-1;return t[r]=(n>1?"& ":"")+t[r],t=t.join(n>2?", ":" "),e.replace(i,"{\n/* [wrapped with "+t+"] */\n")}var i=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;t.exports=r},{}],338:[function(e,t,n){function r(e){return a(e)||o(e)||!!(s&&e&&e[s])}var i=e("./_Symbol"),o=e("./isArguments"),a=e("./isArray"),s=i?i.isConcatSpreadable:void 0;t.exports=r},{"./_Symbol":188,"./isArguments":419,"./isArray":420}],339:[function(e,t,n){function r(e,t){return t=null==t?i:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var i=9007199254740991,o=/^(?:0|[1-9]\d*)$/;t.exports=r},{}],340:[function(e,t,n){function r(e,t,n){if(!s(n))return!1;var r=typeof t;return!!("number"==r?o(n)&&a(t,n.length):"string"==r&&t in n)&&i(n[t],e)}var i=e("./eq"),o=e("./isArrayLike"),a=e("./_isIndex"),s=e("./isObject");t.exports=r},{"./_isIndex":339,"./eq":404,"./isArrayLike":421,"./isObject":432}],341:[function(e,t,n){function r(e,t){if(i(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!o(e))||(s.test(e)||!a.test(e)||null!=t&&e in Object(t))}var i=e("./isArray"),o=e("./isSymbol"),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,s=/^\w*$/;t.exports=r},{"./isArray":420,"./isSymbol":436}],342:[function(e,t,n){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}t.exports=r},{}],343:[function(e,t,n){function r(e){var t=a(e),n=s[t];if("function"!=typeof n||!(t in i.prototype))return!1;if(e===n)return!0;var r=o(n);return!!r&&e===r[0]}var i=e("./_LazyWrapper"),o=e("./_getData"),a=e("./_getFuncName"),s=e("./wrapperLodash");t.exports=r},{"./_LazyWrapper":179,"./_getData":314,"./_getFuncName":315,"./wrapperLodash":472}],344:[function(e,t,n){function r(e){return!!o&&o in e}var i=e("./_coreJsData"),o=function(){var e=/[^.]+$/.exec(i&&i.keys&&i.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();t.exports=r},{"./_coreJsData":287}],345:[function(e,t,n){function r(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||i;return e===n}var i=Object.prototype;t.exports=r},{}],346:[function(e,t,n){function r(e){return e===e&&!i(e)}var i=e("./isObject");t.exports=r},{"./isObject":432}],347:[function(e,t,n){function r(){this.__data__=[],this.size=0}t.exports=r},{}],348:[function(e,t,n){function r(e){var t=this.__data__,n=i(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():a.call(t,n,1),--this.size,!0}var i=e("./_assocIndexOf"),o=Array.prototype,a=o.splice;t.exports=r},{"./_assocIndexOf":206}],349:[function(e,t,n){function r(e){var t=this.__data__,n=i(t,e);return n<0?void 0:t[n][1]}var i=e("./_assocIndexOf");t.exports=r},{"./_assocIndexOf":206}],350:[function(e,t,n){function r(e){return i(this.__data__,e)>-1}var i=e("./_assocIndexOf");t.exports=r},{"./_assocIndexOf":206}],351:[function(e,t,n){function r(e,t){var n=this.__data__,r=i(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var i=e("./_assocIndexOf");t.exports=r},{"./_assocIndexOf":206}],352:[function(e,t,n){function r(){this.size=0,this.__data__={hash:new i,map:new(a||o),string:new i}}var i=e("./_Hash"),o=e("./_ListCache"),a=e("./_Map");t.exports=r},{"./_Hash":178,"./_ListCache":180,"./_Map":182}],353:[function(e,t,n){function r(e){var t=i(this,e)["delete"](e);return this.size-=t?1:0,t}var i=e("./_getMapData");t.exports=r},{"./_getMapData":317}],354:[function(e,t,n){function r(e){return i(this,e).get(e)}var i=e("./_getMapData");t.exports=r},{"./_getMapData":317}],355:[function(e,t,n){function r(e){return i(this,e).has(e)}var i=e("./_getMapData");t.exports=r},{"./_getMapData":317}],356:[function(e,t,n){function r(e,t){var n=i(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var i=e("./_getMapData");t.exports=r},{"./_getMapData":317}],357:[function(e,t,n){function r(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}t.exports=r},{}],358:[function(e,t,n){function r(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}t.exports=r},{}],359:[function(e,t,n){function r(e){var t=i(e,function(e){return n.size===o&&n.clear(),e}),n=t.cache;return t}var i=e("./memoize"),o=500;t.exports=r},{"./memoize":445}],360:[function(e,t,n){function r(e,t){var n=e[1],r=t[1],m=n|r,v=m<(u|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(!v&&!y)return e;r&u&&(e[2]=t[2],m|=n&u?0:l);var g=t[3];if(g){var b=e[3];e[3]=b?i(b,g,t[4]):g,e[4]=b?a(e[3],s):t[4]}return g=t[5],g&&(b=e[5],e[5]=b?o(b,g,t[6]):g,e[6]=b?a(e[5],s):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]=m,e}var i=e("./_composeArgs"),o=e("./_composeArgsRight"),a=e("./_replaceHolders"),s="__lodash_placeholder__",u=1,c=2,l=4,f=8,p=128,d=256,h=Math.min;t.exports=r},{"./_composeArgs":281,"./_composeArgsRight":282,"./_replaceHolders":372}],361:[function(e,t,n){var r=e("./_WeakMap"),i=r&&new r;t.exports=i},{"./_WeakMap":190}],362:[function(e,t,n){var r=e("./_getNative"),i=r(Object,"create");t.exports=i},{"./_getNative":319}],363:[function(e,t,n){var r=e("./_overArg"),i=r(Object.keys,Object);t.exports=i},{"./_overArg":367}],364:[function(e,t,n){function r(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}t.exports=r},{}],365:[function(e,t,n){var r=e("./_freeGlobal"),i="object"==typeof n&&n&&!n.nodeType&&n,o=i&&"object"==typeof t&&t&&!t.nodeType&&t,a=o&&o.exports===i,s=a&&r.process,u=function(){try{return s&&s.binding&&s.binding("util")}catch(e){}}();t.exports=u},{"./_freeGlobal":311}],366:[function(e,t,n){function r(e){return o.call(e)}var i=Object.prototype,o=i.toString;t.exports=r},{}],367:[function(e,t,n){function r(e,t){return function(n){return e(t(n))}}t.exports=r},{}],368:[function(e,t,n){function r(e,t,n){return t=o(void 0===t?e.length-1:t,0),function(){for(var r=arguments,a=-1,s=o(r.length-t,0),u=Array(s);++a<s;)u[a]=r[t+a];a=-1;for(var c=Array(t+1);++a<t;)c[a]=r[a];return c[t]=n(u),i(e,this,c)}}var i=e("./_apply"),o=Math.max;t.exports=r},{"./_apply":193}],369:[function(e,t,n){function r(e,t){return t.length<2?e:i(e,o(t,0,-1))}var i=e("./_baseGet"),o=e("./_baseSlice");t.exports=r},{"./_baseGet":219,"./_baseSlice":254}],370:[function(e,t,n){var r={};t.exports=r},{}],371:[function(e,t,n){function r(e,t){for(var n=e.length,r=a(t.length,n),s=i(e);r--;){var u=t[r];e[r]=o(u,n)?s[u]:void 0}return e}var i=e("./_copyArray"),o=e("./_isIndex"),a=Math.min;t.exports=r},{"./_copyArray":283,"./_isIndex":339}],372:[function(e,t,n){function r(e,t){for(var n=-1,r=e.length,o=0,a=[];++n<r;){var s=e[n];s!==t&&s!==i||(e[n]=i,a[o++]=n)}return a}var i="__lodash_placeholder__";t.exports=r},{}],373:[function(e,t,n){var r=e("./_freeGlobal"),i="object"==typeof self&&self&&self.Object===Object&&self,o=r||i||Function("return this")();t.exports=o},{"./_freeGlobal":311}],374:[function(e,t,n){function r(e){return this.__data__.set(e,i),this}var i="__lodash_hash_undefined__";t.exports=r},{}],375:[function(e,t,n){function r(e){return this.__data__.has(e)}t.exports=r},{}],376:[function(e,t,n){var r=e("./_baseSetData"),i=e("./_shortOut"),o=i(r);t.exports=o},{"./_baseSetData":252,"./_shortOut":380}],377:[function(e,t,n){function r(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}t.exports=r},{}],378:[function(e,t,n){var r=e("./_baseSetToString"),i=e("./_shortOut"),o=i(r);t.exports=o},{"./_baseSetToString":253,"./_shortOut":380}],379:[function(e,t,n){function r(e,t,n){var r=t+"";return a(e,o(r,s(i(r),n)))}var i=e("./_getWrapDetails"),o=e("./_insertWrapDetails"),a=e("./_setToString"),s=e("./_updateWrapDetails");t.exports=r},{"./_getWrapDetails":326,"./_insertWrapDetails":337,"./_setToString":378,"./_updateWrapDetails":392}],380:[function(e,t,n){function r(e){var t=0,n=0;return function(){var r=a(),s=o-(r-n);if(n=r,s>0){if(++t>=i)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var i=800,o=16,a=Date.now;t.exports=r},{}],381:[function(e,t,n){function r(){this.__data__=new i,this.size=0}var i=e("./_ListCache");t.exports=r},{"./_ListCache":180}],382:[function(e,t,n){function r(e){var t=this.__data__,n=t["delete"](e);return this.size=t.size,n}t.exports=r},{}],383:[function(e,t,n){function r(e){return this.__data__.get(e)}t.exports=r},{}],384:[function(e,t,n){function r(e){return this.__data__.has(e)}t.exports=r},{}],385:[function(e,t,n){function r(e,t){var n=this.__data__;if(n instanceof i){var r=n.__data__;if(!o||r.length<s-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new a(r)}return n.set(e,t),this.size=n.size,this}var i=e("./_ListCache"),o=e("./_Map"),a=e("./_MapCache"),s=200;t.exports=r},{"./_ListCache":180,"./_Map":182,"./_MapCache":183}],386:[function(e,t,n){function r(e,t,n){for(var r=n-1,i=e.length;++r<i;)if(e[r]===t)return r;return-1}t.exports=r},{}],387:[function(e,t,n){function r(e){return o(e)?a(e):i(e)}var i=e("./_asciiToArray"),o=e("./_hasUnicode"),a=e("./_unicodeToArray");t.exports=r},{"./_asciiToArray":203,"./_hasUnicode":328,"./_unicodeToArray":391}],388:[function(e,t,n){var r=e("./_memoizeCapped"),i=/^\./,o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,a=/\\(\\)?/g,s=r(function(e){var t=[];return i.test(e)&&t.push(""),e.replace(o,function(e,n,r,i){t.push(r?i.replace(a,"$1"):n||e)}),t});t.exports=s},{"./_memoizeCapped":359}],389:[function(e,t,n){function r(e){if("string"==typeof e||i(e))return e;var t=e+"";return"0"==t&&1/e==-o?"-0":t}var i=e("./isSymbol"),o=1/0;t.exports=r},{"./isSymbol":436}],390:[function(e,t,n){function r(e){if(null!=e){try{return o.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var i=Function.prototype,o=i.toString;t.exports=r},{}],391:[function(e,t,n){function r(e){return e.match(j)||[]}var i="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",s="\\u20d0-\\u20ff",u=o+a+s,c="\\ufe0e\\ufe0f",l="["+i+"]",f="["+u+"]",p="\\ud83c[\\udffb-\\udfff]",d="(?:"+f+"|"+p+")",h="[^"+i+"]",m="(?:\\ud83c[\\udde6-\\uddff]){2}",v="[\\ud800-\\udbff][\\udc00-\\udfff]",y="\\u200d",g=d+"?",b="["+c+"]?",_="(?:"+y+"(?:"+[h,m,v].join("|")+")"+b+g+")*",w=b+g+_,C="(?:"+[h+f+"?",f,m,v,l].join("|")+")",j=RegExp(p+"(?="+p+")|"+C+w,"g");t.exports=r},{}],392:[function(e,t,n){function r(e,t){return i(m,function(n){var r="_."+n[0];t&n[1]&&!o(e,r)&&e.push(r)}),e.sort()}var i=e("./_arrayEach"),o=e("./_arrayIncludes"),a=1,s=2,u=8,c=16,l=32,f=64,p=128,d=256,h=512,m=[["ary",p],["bind",a],["bindKey",s],["curry",u],["curryRight",c],["flip",h],["partial",l],["partialRight",f],["rearg",d]];t.exports=r},{"./_arrayEach":194,"./_arrayIncludes":196}],393:[function(e,t,n){function r(e){if(e instanceof i)return e.clone();var t=new o(e.__wrapped__,e.__chain__);return t.__actions__=a(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var i=e("./_LazyWrapper"),o=e("./_LodashWrapper"),a=e("./_copyArray");t.exports=r},{"./_LazyWrapper":179,"./_LodashWrapper":181,"./_copyArray":283}],394:[function(e,t,n){var r=e("./_assignValue"),i=e("./_copyObject"),o=e("./_createAssigner"),a=e("./isArrayLike"),s=e("./_isPrototype"),u=e("./keys"),c=Object.prototype,l=c.hasOwnProperty,f=o(function(e,t){if(s(t)||a(t))return void i(t,u(t),e);for(var n in t)l.call(t,n)&&r(e,n,t[n])});t.exports=f},{"./_assignValue":205,"./_copyObject":284,"./_createAssigner":289,"./_isPrototype":345,"./isArrayLike":421,"./keys":439}],395:[function(e,t,n){var r=e("./_copyObject"),i=e("./_createAssigner"),o=e("./keysIn"),a=i(function(e,t,n,i){r(t,o(t),e,i)});t.exports=a},{"./_copyObject":284,"./_createAssigner":289,"./keysIn":440}],396:[function(e,t,n){var r=e("./_baseRest"),i=e("./_createWrap"),o=e("./_getHolder"),a=e("./_replaceHolders"),s=1,u=32,c=r(function(e,t,n){var r=s;if(n.length){var l=a(n,o(c));r|=u}return i(e,r,t,n,l)});c.placeholder={},t.exports=c},{"./_baseRest":250,"./_createWrap":302,"./_getHolder":316,"./_replaceHolders":372}],397:[function(e,t,n){function r(e){return i(e,o)}var i=e("./_baseClone"),o=4;t.exports=r},{"./_baseClone":211}],398:[function(e,t,n){function r(e){return i(e,o|a)}var i=e("./_baseClone"),o=1,a=4;t.exports=r},{"./_baseClone":211}],399:[function(e,t,n){function r(e){for(var t=-1,n=null==e?0:e.length,r=0,i=[];++t<n;){var o=e[t];o&&(i[r++]=o)}return i}t.exports=r},{}],400:[function(e,t,n){function r(e){return function(){return e}}t.exports=r},{}],401:[function(e,t,n){function r(e,t,n){t=n?void 0:t;var a=i(e,o,void 0,void 0,void 0,void 0,void 0,t);return a.placeholder=r.placeholder,a}var i=e("./_createWrap"),o=8;r.placeholder={},t.exports=r},{"./_createWrap":302}],402:[function(e,t,n){var r=e("./_apply"),i=e("./assignInWith"),o=e("./_baseRest"),a=e("./_customDefaultsAssignIn"),s=o(function(e){return e.push(void 0,a),r(i,void 0,e)});t.exports=s},{"./_apply":193,"./_baseRest":250,"./_customDefaultsAssignIn":303,"./assignInWith":395}],403:[function(e,t,n){var r=e("./_apply"),i=e("./_baseRest"),o=e("./_customDefaultsMerge"),a=e("./mergeWith"),s=i(function(e){return e.push(void 0,o),r(a,void 0,e)});t.exports=s},{"./_apply":193,"./_baseRest":250,"./_customDefaultsMerge":304,"./mergeWith":447}],404:[function(e,t,n){function r(e,t){return e===t||e!==e&&t!==t}t.exports=r},{}],405:[function(e,t,n){function r(e,t){var n=s(e)?i:o;return n(e,a(t,3))}var i=e("./_arrayFilter"),o=e("./_baseFilter"),a=e("./_baseIteratee"),s=e("./isArray");t.exports=r},{"./_arrayFilter":195,"./_baseFilter":214,"./_baseIteratee":234,"./isArray":420}],406:[function(e,t,n){var r=e("./_createFind"),i=e("./findIndex"),o=r(i);t.exports=o},{"./_createFind":295,"./findIndex":407}],407:[function(e,t,n){function r(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var u=null==n?0:a(n);return u<0&&(u=s(r+u,0)),i(e,o(t,3),u)}var i=e("./_baseFindIndex"),o=e("./_baseIteratee"),a=e("./toInteger"),s=Math.max;t.exports=r},{"./_baseFindIndex":215,"./_baseIteratee":234,"./toInteger":464}],408:[function(e,t,n){function r(e){var t=null==e?0:e.length;return t?i(e,1):[]}var i=e("./_baseFlatten");t.exports=r},{"./_baseFlatten":216}],409:[function(e,t,n){function r(e,t){var n=s(e)?i:o;return n(e,a(t))}var i=e("./_arrayEach"),o=e("./_baseEach"),a=e("./_castFunction"),s=e("./isArray");t.exports=r; },{"./_arrayEach":194,"./_baseEach":213,"./_castFunction":266,"./isArray":420}],410:[function(e,t,n){function r(e,t){return e&&i(e,o(t))}var i=e("./_baseForOwn"),o=e("./_castFunction");t.exports=r},{"./_baseForOwn":218,"./_castFunction":266}],411:[function(e,t,n){function r(e,t,n){var r=null==e?void 0:i(e,t);return void 0===r?n:r}var i=e("./_baseGet");t.exports=r},{"./_baseGet":219}],412:[function(e,t,n){function r(e,t){return null!=e&&o(e,t,i)}var i=e("./_baseHas"),o=e("./_hasPath");t.exports=r},{"./_baseHas":222,"./_hasPath":327}],413:[function(e,t,n){function r(e,t){return null!=e&&o(e,t,i)}var i=e("./_baseHasIn"),o=e("./_hasPath");t.exports=r},{"./_baseHasIn":223,"./_hasPath":327}],414:[function(e,t,n){function r(e){return e}t.exports=r},{}],415:[function(e,t,n){function r(e,t,n,r){e=o(e)?e:u(e),n=n&&!r?s(n):0;var l=e.length;return n<0&&(n=c(l+n,0)),a(e)?n<=l&&e.indexOf(t,n)>-1:!!l&&i(e,t,n)>-1}var i=e("./_baseIndexOf"),o=e("./isArrayLike"),a=e("./isString"),s=e("./toInteger"),u=e("./values"),c=Math.max;t.exports=r},{"./_baseIndexOf":224,"./isArrayLike":421,"./isString":435,"./toInteger":464,"./values":471}],416:[function(e,t,n){function r(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var s=null==n?0:o(n);return s<0&&(s=a(r+s,0)),i(e,t,s)}var i=e("./_baseIndexOf"),o=e("./toInteger"),a=Math.max;t.exports=r},{"./_baseIndexOf":224,"./toInteger":464}],417:[function(e,t,n){var r=e("./_arrayMap"),i=e("./_baseIntersection"),o=e("./_baseRest"),a=e("./_castArrayLikeObject"),s=o(function(e){var t=r(e,a);return t.length&&t[0]===e[0]?i(t):[]});t.exports=s},{"./_arrayMap":199,"./_baseIntersection":225,"./_baseRest":250,"./_castArrayLikeObject":265}],418:[function(e,t,n){var r=e("./constant"),i=e("./_createInverter"),o=e("./identity"),a=i(function(e,t,n){e[t]=n},r(o));t.exports=a},{"./_createInverter":297,"./constant":400,"./identity":414}],419:[function(e,t,n){var r=e("./_baseIsArguments"),i=e("./isObjectLike"),o=Object.prototype,a=o.hasOwnProperty,s=o.propertyIsEnumerable,u=r(function(){return arguments}())?r:function(e){return i(e)&&a.call(e,"callee")&&!s.call(e,"callee")};t.exports=u},{"./_baseIsArguments":227,"./isObjectLike":433}],420:[function(e,t,n){var r=Array.isArray;t.exports=r},{}],421:[function(e,t,n){function r(e){return null!=e&&o(e.length)&&!i(e)}var i=e("./isFunction"),o=e("./isLength");t.exports=r},{"./isFunction":427,"./isLength":428}],422:[function(e,t,n){function r(e){return o(e)&&i(e)}var i=e("./isArrayLike"),o=e("./isObjectLike");t.exports=r},{"./isArrayLike":421,"./isObjectLike":433}],423:[function(e,t,n){function r(e){return e===!0||e===!1||o(e)&&i(e)==a}var i=e("./_baseGetTag"),o=e("./isObjectLike"),a="[object Boolean]";t.exports=r},{"./_baseGetTag":221,"./isObjectLike":433}],424:[function(e,t,n){var r=e("./_root"),i=e("./stubFalse"),o="object"==typeof n&&n&&!n.nodeType&&n,a=o&&"object"==typeof t&&t&&!t.nodeType&&t,s=a&&a.exports===o,u=s?r.Buffer:void 0,c=u?u.isBuffer:void 0,l=c||i;t.exports=l},{"./_root":373,"./stubFalse":461}],425:[function(e,t,n){function r(e){if(null==e)return!0;if(u(e)&&(s(e)||"string"==typeof e||"function"==typeof e.splice||c(e)||f(e)||a(e)))return!e.length;var t=o(e);if(t==p||t==d)return!e.size;if(l(e))return!i(e).length;for(var n in e)if(m.call(e,n))return!1;return!0}var i=e("./_baseKeys"),o=e("./_getTag"),a=e("./isArguments"),s=e("./isArray"),u=e("./isArrayLike"),c=e("./isBuffer"),l=e("./_isPrototype"),f=e("./isTypedArray"),p="[object Map]",d="[object Set]",h=Object.prototype,m=h.hasOwnProperty;t.exports=r},{"./_baseKeys":235,"./_getTag":324,"./_isPrototype":345,"./isArguments":419,"./isArray":420,"./isArrayLike":421,"./isBuffer":424,"./isTypedArray":437}],426:[function(e,t,n){function r(e,t){return i(e,t)}var i=e("./_baseIsEqual");t.exports=r},{"./_baseIsEqual":228}],427:[function(e,t,n){function r(e){if(!o(e))return!1;var t=i(e);return t==s||t==u||t==a||t==c}var i=e("./_baseGetTag"),o=e("./isObject"),a="[object AsyncFunction]",s="[object Function]",u="[object GeneratorFunction]",c="[object Proxy]";t.exports=r},{"./_baseGetTag":221,"./isObject":432}],428:[function(e,t,n){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}var i=9007199254740991;t.exports=r},{}],429:[function(e,t,n){function r(e){return i(e)&&e!=+e}var i=e("./isNumber");t.exports=r},{"./isNumber":431}],430:[function(e,t,n){function r(e){return null===e}t.exports=r},{}],431:[function(e,t,n){function r(e){return"number"==typeof e||o(e)&&i(e)==a}var i=e("./_baseGetTag"),o=e("./isObjectLike"),a="[object Number]";t.exports=r},{"./_baseGetTag":221,"./isObjectLike":433}],432:[function(e,t,n){function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}t.exports=r},{}],433:[function(e,t,n){function r(e){return null!=e&&"object"==typeof e}t.exports=r},{}],434:[function(e,t,n){function r(e){if(!a(e)||i(e)!=s)return!1;var t=o(e);if(null===t)return!0;var n=f.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&l.call(n)==p}var i=e("./_baseGetTag"),o=e("./_getPrototype"),a=e("./isObjectLike"),s="[object Object]",u=Function.prototype,c=Object.prototype,l=u.toString,f=c.hasOwnProperty,p=l.call(Object);t.exports=r},{"./_baseGetTag":221,"./_getPrototype":320,"./isObjectLike":433}],435:[function(e,t,n){function r(e){return"string"==typeof e||!o(e)&&a(e)&&i(e)==s}var i=e("./_baseGetTag"),o=e("./isArray"),a=e("./isObjectLike"),s="[object String]";t.exports=r},{"./_baseGetTag":221,"./isArray":420,"./isObjectLike":433}],436:[function(e,t,n){function r(e){return"symbol"==typeof e||o(e)&&i(e)==a}var i=e("./_baseGetTag"),o=e("./isObjectLike"),a="[object Symbol]";t.exports=r},{"./_baseGetTag":221,"./isObjectLike":433}],437:[function(e,t,n){var r=e("./_baseIsTypedArray"),i=e("./_baseUnary"),o=e("./_nodeUtil"),a=o&&o.isTypedArray,s=a?i(a):r;t.exports=s},{"./_baseIsTypedArray":233,"./_baseUnary":260,"./_nodeUtil":365}],438:[function(e,t,n){function r(e){return void 0===e}t.exports=r},{}],439:[function(e,t,n){function r(e){return a(e)?i(e):o(e)}var i=e("./_arrayLikeKeys"),o=e("./_baseKeys"),a=e("./isArrayLike");t.exports=r},{"./_arrayLikeKeys":198,"./_baseKeys":235,"./isArrayLike":421}],440:[function(e,t,n){function r(e){return a(e)?i(e,!0):o(e)}var i=e("./_arrayLikeKeys"),o=e("./_baseKeysIn"),a=e("./isArrayLike");t.exports=r},{"./_arrayLikeKeys":198,"./_baseKeysIn":236,"./isArrayLike":421}],441:[function(e,t,n){function r(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}t.exports=r},{}],442:[function(e,t,n){function r(e,t){var n=s(e)?i:a;return n(e,o(t,3))}var i=e("./_arrayMap"),o=e("./_baseIteratee"),a=e("./_baseMap"),s=e("./isArray");t.exports=r},{"./_arrayMap":199,"./_baseIteratee":234,"./_baseMap":238,"./isArray":420}],443:[function(e,t,n){function r(e,t){var n={};return t=a(t,3),o(e,function(e,r,o){i(n,t(e,r,o),e)}),n}var i=e("./_baseAssignValue"),o=e("./_baseForOwn"),a=e("./_baseIteratee");t.exports=r},{"./_baseAssignValue":209,"./_baseForOwn":218,"./_baseIteratee":234}],444:[function(e,t,n){function r(e,t){var n={};return t=a(t,3),o(e,function(e,r,o){i(n,r,t(e,r,o))}),n}var i=e("./_baseAssignValue"),o=e("./_baseForOwn"),a=e("./_baseIteratee");t.exports=r},{"./_baseAssignValue":209,"./_baseForOwn":218,"./_baseIteratee":234}],445:[function(e,t,n){function r(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(o);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=e.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(r.Cache||i),n}var i=e("./_MapCache"),o="Expected a function";r.Cache=i,t.exports=r},{"./_MapCache":183}],446:[function(e,t,n){var r=e("./_baseMerge"),i=e("./_createAssigner"),o=i(function(e,t,n){r(e,t,n)});t.exports=o},{"./_baseMerge":241,"./_createAssigner":289}],447:[function(e,t,n){var r=e("./_baseMerge"),i=e("./_createAssigner"),o=i(function(e,t,n,i){r(e,t,n,i)});t.exports=o},{"./_baseMerge":241,"./_createAssigner":289}],448:[function(e,t,n){function r(){}t.exports=r},{}],449:[function(e,t,n){var r=e("./_arrayMap"),i=e("./_baseClone"),o=e("./_baseUnset"),a=e("./_castPath"),s=e("./_copyObject"),u=e("./_customOmitClone"),c=e("./_flatRest"),l=e("./_getAllKeysIn"),f=1,p=2,d=4,h=c(function(e,t){var n={};if(null==e)return n;var c=!1;t=r(t,function(t){return t=a(t,e),c||(c=t.length>1),t}),s(e,l(e),n),c&&(n=i(n,f|p|d,u));for(var h=t.length;h--;)o(n,t[h]);return n});t.exports=h},{"./_arrayMap":199,"./_baseClone":211,"./_baseUnset":262,"./_castPath":267,"./_copyObject":284,"./_customOmitClone":305,"./_flatRest":310,"./_getAllKeysIn":313}],450:[function(e,t,n){function r(e,t,n,r){return null==e?[]:(o(t)||(t=null==t?[]:[t]),n=r?void 0:n,o(n)||(n=null==n?[]:[n]),i(e,t,n))}var i=e("./_baseOrderBy"),o=e("./isArray");t.exports=r},{"./_baseOrderBy":243,"./isArray":420}],451:[function(e,t,n){var r=e("./_baseRest"),i=e("./_createWrap"),o=e("./_getHolder"),a=e("./_replaceHolders"),s=32,u=r(function(e,t){var n=a(t,o(u));return i(e,s,void 0,t,n)});u.placeholder={},t.exports=u},{"./_baseRest":250,"./_createWrap":302,"./_getHolder":316,"./_replaceHolders":372}],452:[function(e,t,n){var r=e("./_baseRest"),i=e("./_createWrap"),o=e("./_getHolder"),a=e("./_replaceHolders"),s=64,u=r(function(e,t){var n=a(t,o(u));return i(e,s,void 0,t,n)});u.placeholder={},t.exports=u},{"./_baseRest":250,"./_createWrap":302,"./_getHolder":316,"./_replaceHolders":372}],453:[function(e,t,n){var r=e("./_basePick"),i=e("./_flatRest"),o=i(function(e,t){return null==e?{}:r(e,t)});t.exports=o},{"./_basePick":244,"./_flatRest":310}],454:[function(e,t,n){function r(e,t){if(null==e)return{};var n=i(s(e),function(e){return[e]});return t=o(t),a(e,n,function(e,n){return t(e,n[0])})}var i=e("./_arrayMap"),o=e("./_baseIteratee"),a=e("./_basePickBy"),s=e("./_getAllKeysIn");t.exports=r},{"./_arrayMap":199,"./_baseIteratee":234,"./_basePickBy":245,"./_getAllKeysIn":313}],455:[function(e,t,n){function r(e){return a(e)?i(s(e)):o(e)}var i=e("./_baseProperty"),o=e("./_basePropertyDeep"),a=e("./_isKey"),s=e("./_toKey");t.exports=r},{"./_baseProperty":246,"./_basePropertyDeep":247,"./_isKey":341,"./_toKey":389}],456:[function(e,t,n){var r=e("./_createRange"),i=r();t.exports=i},{"./_createRange":299}],457:[function(e,t,n){function r(e,t,n){var r=u(e)?i:s,c=arguments.length<3;return r(e,a(t,4),n,c,o)}var i=e("./_arrayReduce"),o=e("./_baseEach"),a=e("./_baseIteratee"),s=e("./_baseReduce"),u=e("./isArray");t.exports=r},{"./_arrayReduce":201,"./_baseEach":213,"./_baseIteratee":234,"./_baseReduce":249,"./isArray":420}],458:[function(e,t,n){function r(e,t,n){var r=s(e)?i:a;return n&&u(e,t,n)&&(t=void 0),r(e,o(t,3))}var i=e("./_arraySome"),o=e("./_baseIteratee"),a=e("./_baseSome"),s=e("./isArray"),u=e("./_isIterateeCall");t.exports=r},{"./_arraySome":202,"./_baseIteratee":234,"./_baseSome":255,"./_isIterateeCall":340,"./isArray":420}],459:[function(e,t,n){function r(e,t,n){return e=s(e),n=null==n?0:i(a(n),0,e.length),t=o(t),e.slice(n,n+t.length)==t}var i=e("./_baseClamp"),o=e("./_baseToString"),a=e("./toInteger"),s=e("./toString");t.exports=r},{"./_baseClamp":210,"./_baseToString":259,"./toInteger":464,"./toString":467}],460:[function(e,t,n){function r(){return[]}t.exports=r},{}],461:[function(e,t,n){function r(){return!1}t.exports=r},{}],462:[function(e,t,n){function r(e,t){return e&&e.length?o(e,i(t,2)):0}var i=e("./_baseIteratee"),o=e("./_baseSum");t.exports=r},{"./_baseIteratee":234,"./_baseSum":257}],463:[function(e,t,n){function r(e){if(!e)return 0===e?e:0;if(e=i(e),e===o||e===-o){var t=e<0?-1:1;return t*a}return e===e?e:0}var i=e("./toNumber"),o=1/0,a=1.7976931348623157e308;t.exports=r},{"./toNumber":465}],464:[function(e,t,n){function r(e){var t=i(e),n=t%1;return t===t?n?t-n:t:0}var i=e("./toFinite");t.exports=r},{"./toFinite":463}],465:[function(e,t,n){function r(e){if("number"==typeof e)return e;if(o(e))return a;if(i(e)){var t="function"==typeof 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=c.test(e);return n||l.test(e)?f(e.slice(2),n?2:8):u.test(e)?a:+e}var i=e("./isObject"),o=e("./isSymbol"),a=NaN,s=/^\s+|\s+$/g,u=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,l=/^0o[0-7]+$/i,f=parseInt;t.exports=r},{"./isObject":432,"./isSymbol":436}],466:[function(e,t,n){function r(e){return i(e,o(e))}var i=e("./_copyObject"),o=e("./keysIn");t.exports=r},{"./_copyObject":284,"./keysIn":440}],467:[function(e,t,n){function r(e){return null==e?"":i(e)}var i=e("./_baseToString");t.exports=r},{"./_baseToString":259}],468:[function(e,t,n){function r(e,t,n){if(e=c(e),e&&(n||void 0===t))return e.replace(l,"");if(!e||!(t=i(t)))return e;var r=u(e),f=u(t),p=s(r,f),d=a(r,f)+1;return o(r,p,d).join("")}var i=e("./_baseToString"),o=e("./_castSlice"),a=e("./_charsEndIndex"),s=e("./_charsStartIndex"),u=e("./_stringToArray"),c=e("./toString"),l=/^\s+|\s+$/g;t.exports=r},{"./_baseToString":259,"./_castSlice":268,"./_charsEndIndex":269,"./_charsStartIndex":270,"./_stringToArray":387,"./toString":467}],469:[function(e,t,n){var r=e("./_baseFlatten"),i=e("./_baseRest"),o=e("./_baseUniq"),a=e("./isArrayLikeObject"),s=i(function(e){return o(r(e,1,a,!0))});t.exports=s},{"./_baseFlatten":216,"./_baseRest":250,"./_baseUniq":261,"./isArrayLikeObject":422}],470:[function(e,t,n){function r(e){return e&&e.length?i(e):[]}var i=e("./_baseUniq");t.exports=r},{"./_baseUniq":261}],471:[function(e,t,n){function r(e){return null==e?[]:i(e,o(e))}var i=e("./_baseValues"),o=e("./keys");t.exports=r},{"./_baseValues":263,"./keys":439}],472:[function(e,t,n){function r(e){if(u(e)&&!s(e)&&!(e instanceof i)){if(e instanceof o)return e;if(f.call(e,"__wrapped__"))return c(e)}return new o(e)}var i=e("./_LazyWrapper"),o=e("./_LodashWrapper"),a=e("./_baseLodash"),s=e("./isArray"),u=e("./isObjectLike"),c=e("./_wrapperClone"),l=Object.prototype,f=l.hasOwnProperty;r.prototype=a.prototype,r.prototype.constructor=r,t.exports=r},{"./_LazyWrapper":179,"./_LodashWrapper":181,"./_baseLodash":237,"./_wrapperClone":393,"./isArray":420,"./isObjectLike":433}],473:[function(e,t,n){function r(e){if(e=String(e),!(e.length>1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*f;case"days":case"day":case"d":return n*l;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function i(e){return e>=l?Math.round(e/l)+"d":e>=c?Math.round(e/c)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function o(e){return a(e,l,"day")||a(e,c,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var s=1e3,u=60*s,c=60*u,l=24*c,f=365.25*l;t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return r(e);if("number"===n&&isNaN(e)===!1)return t["long"]?o(e):i(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],474:[function(t,n,r){!function(t){"function"==typeof e&&e.amd?e([],t):"object"==typeof r?n.exports=t():window.noUiSlider=t()}(function(){"use strict";function e(e){return e.filter(function(e){return!this[e]&&(this[e]=!0)},{})}function t(e,t){return Math.round(e/t)*t}function n(e){var t=e.getBoundingClientRect(),n=e.ownerDocument,r=n.documentElement,i=f();return/webkit.*Chrome.*Mobile/i.test(navigator.userAgent)&&(i.x=0),{top:t.top+i.y-r.clientTop,left:t.left+i.x-r.clientLeft}}function r(e){return"number"==typeof e&&!isNaN(e)&&isFinite(e)}function i(e,t,n){u(e,t),setTimeout(function(){c(e,t)},n)}function o(e){return Math.max(Math.min(e,100),0)}function a(e){return Array.isArray(e)?e:[e]}function s(e){var t=e.split(".");return t.length>1?t[1].length:0}function u(e,t){e.classList?e.classList.add(t):e.className+=" "+t}function c(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")}function l(e,t){return e.classList?e.classList.contains(t):new RegExp("\\b"+t+"\\b").test(e.className)}function f(){var e=void 0!==window.pageXOffset,t="CSS1Compat"===(document.compatMode||""),n=e?window.pageXOffset:t?document.documentElement.scrollLeft:document.body.scrollLeft,r=e?window.pageYOffset:t?document.documentElement.scrollTop:document.body.scrollTop;return{x:n,y:r}}function p(){return window.navigator.pointerEnabled?{start:"pointerdown",move:"pointermove",end:"pointerup"}:window.navigator.msPointerEnabled?{start:"MSPointerDown",move:"MSPointerMove",end:"MSPointerUp"}:{start:"mousedown touchstart",move:"mousemove touchmove",end:"mouseup touchend"}}function d(e,t){return 100/(t-e)}function h(e,t){return 100*t/(e[1]-e[0])}function m(e,t){return h(e,e[0]<0?t+Math.abs(e[0]):t-e[0])}function v(e,t){return t*(e[1]-e[0])/100+e[0]}function y(e,t){for(var n=1;e>=t[n];)n+=1;return n}function g(e,t,n){if(n>=e.slice(-1)[0])return 100;var r,i,o,a,s=y(n,e);return r=e[s-1],i=e[s],o=t[s-1],a=t[s],o+m([r,i],n)/d(o,a)}function b(e,t,n){if(n>=100)return e.slice(-1)[0];var r,i,o,a,s=y(n,t);return r=e[s-1],i=e[s],o=t[s-1],a=t[s],v([r,i],(n-o)*d(o,a))}function _(e,n,r,i){if(100===i)return i;var o,a,s=y(i,e);return r?(o=e[s-1],a=e[s],i-o>(a-o)/2?a:o):n[s-1]?e[s-1]+t(i-e[s-1],n[s-1]):i}function w(e,t,n){var i;if("number"==typeof t&&(t=[t]),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("noUiSlider: 'range' contains invalid value.");if(i="min"===e?0:"max"===e?100:parseFloat(e),!r(i)||!r(t[0]))throw new Error("noUiSlider: 'range' value isn't numeric.");n.xPct.push(i),n.xVal.push(t[0]),i?n.xSteps.push(!isNaN(t[1])&&t[1]):isNaN(t[1])||(n.xSteps[0]=t[1])}function C(e,t,n){return!t||void(n.xSteps[e]=h([n.xVal[e],n.xVal[e+1]],t)/d(n.xPct[e],n.xPct[e+1]))}function j(e,t,n,r){this.xPct=[],this.xVal=[],this.xSteps=[r||!1],this.xNumSteps=[!1],this.snap=t,this.direction=n;var i,o=[];for(i in e)e.hasOwnProperty(i)&&o.push([e[i],i]);for(o.length&&"object"==typeof o[0][0]?o.sort(function(e,t){return e[0][0]-t[0][0]}):o.sort(function(e,t){return e[0]-t[0]}),i=0;i<o.length;i++)w(o[i][1],o[i][0],this);for(this.xNumSteps=this.xSteps.slice(0),i=0;i<this.xNumSteps.length;i++)C(i,this.xNumSteps[i],this)}function x(e,t){if(!r(t))throw new Error("noUiSlider: 'step' is not numeric.");e.singleStep=t}function R(e,t){if("object"!=typeof t||Array.isArray(t))throw new Error("noUiSlider: 'range' is not an object.");if(void 0===t.min||void 0===t.max)throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");if(t.min===t.max)throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal.");e.spectrum=new j(t,e.snap,e.dir,e.singleStep)}function P(e,t){if(t=a(t),!Array.isArray(t)||!t.length||t.length>2)throw new Error("noUiSlider: 'start' option is incorrect.");e.handles=t.length,e.start=t}function E(e,t){if(e.snap=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'snap' option must be a boolean.")}function O(e,t){if(e.animate=t,"boolean"!=typeof t)throw new Error("noUiSlider: 'animate' option must be a boolean.")}function S(e,t){if(e.animationDuration=t,"number"!=typeof t)throw new Error("noUiSlider: 'animationDuration' option must be a number.")}function T(e,t){if("lower"===t&&1===e.handles)e.connect=1;else if("upper"===t&&1===e.handles)e.connect=2;else if(t===!0&&2===e.handles)e.connect=3;else{if(t!==!1)throw new Error("noUiSlider: 'connect' option doesn't match handle count.");e.connect=0}}function k(e,t){switch(t){case"horizontal":e.ort=0;break;case"vertical":e.ort=1;break;default:throw new Error("noUiSlider: 'orientation' option is invalid.")}}function M(e,t){if(!r(t))throw new Error("noUiSlider: 'margin' option must be numeric.");if(0!==t&&(e.margin=e.spectrum.getMargin(t),!e.margin))throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.")}function A(e,t){if(!r(t))throw new Error("noUiSlider: 'limit' option must be numeric.");if(e.limit=e.spectrum.getMargin(t),!e.limit)throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.")}function I(e,t){switch(t){case"ltr":e.dir=0;break;case"rtl":e.dir=1,e.connect=[0,2,1,3][e.connect];break;default:throw new Error("noUiSlider: 'direction' option was not recognized.")}}function F(e,t){if("string"!=typeof t)throw new Error("noUiSlider: 'behaviour' must be a string containing options.");var n=t.indexOf("tap")>=0,r=t.indexOf("drag")>=0,i=t.indexOf("fixed")>=0,o=t.indexOf("snap")>=0,a=t.indexOf("hover")>=0;if(r&&!e.connect)throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");e.events={tap:n||o,drag:r,fixed:i,snap:o,hover:a}}function N(e,t){var n;if(t!==!1)if(t===!0)for(e.tooltips=[],n=0;n<e.handles;n++)e.tooltips.push(!0);else{if(e.tooltips=a(t),e.tooltips.length!==e.handles)throw new Error("noUiSlider: must pass a formatter for all handles.");e.tooltips.forEach(function(e){if("boolean"!=typeof e&&("object"!=typeof e||"function"!=typeof e.to))throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.")})}}function D(e,t){if(e.format=t,"function"==typeof t.to&&"function"==typeof t.from)return!0;throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.")}function L(e,t){if(void 0!==t&&"string"!=typeof t&&t!==!1)throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");e.cssPrefix=t}function U(e,t){if(void 0!==t&&"object"!=typeof t)throw new Error("noUiSlider: 'cssClasses' must be an object.");if("string"==typeof e.cssPrefix){e.cssClasses={};for(var n in t)t.hasOwnProperty(n)&&(e.cssClasses[n]=e.cssPrefix+t[n])}else e.cssClasses=t}function H(e){var t,n={margin:0,limit:0,animate:!0,animationDuration:300,format:B};t={step:{r:!1,t:x},start:{r:!0,t:P},connect:{r:!0,t:T},direction:{r:!0,t:I},snap:{r:!1,t:E},animate:{r:!1,t:O},animationDuration:{r:!1,t:S},range:{r:!0,t:R},orientation:{r:!1,t:k},margin:{r:!1,t:M},limit:{r:!1,t:A},behaviour:{r:!0,t:F},format:{r:!1,t:D},tooltips:{r:!1,t:N},cssPrefix:{r:!1,t:L},cssClasses:{r:!1,t:U}};var r={connect:!1,direction:"ltr",behaviour:"tap",orientation:"horizontal",cssPrefix:"noUi-",cssClasses:{target:"target",base:"base",origin:"origin",handle:"handle",handleLower:"handle-lower",handleUpper:"handle-upper",horizontal:"horizontal",vertical:"vertical",background:"background",connect:"connect",ltr:"ltr",rtl:"rtl",draggable:"draggable",drag:"state-drag",tap:"state-tap",active:"active",stacking:"stacking",tooltip:"tooltip",pips:"pips",pipsHorizontal:"pips-horizontal",pipsVertical:"pips-vertical",marker:"marker",markerHorizontal:"marker-horizontal",markerVertical:"marker-vertical",markerNormal:"marker-normal",markerLarge:"marker-large",markerSub:"marker-sub",value:"value",valueHorizontal:"value-horizontal",valueVertical:"value-vertical",valueNormal:"value-normal",valueLarge:"value-large",valueSub:"value-sub"}};return Object.keys(t).forEach(function(i){if(void 0===e[i]&&void 0===r[i]){if(t[i].r)throw new Error("noUiSlider: '"+i+"' is required.");return!0}t[i].t(n,void 0===e[i]?r[i]:e[i])}),n.pips=e.pips,n.style=n.ort?"top":"left",n}function V(t,r,d){function h(e,t,n){var r=e+t[0],i=e+t[1];return n?(r<0&&(i+=Math.abs(r)),i>100&&(r-=i-100),[o(r),o(i)]):[r,i]}function m(e,t){e.preventDefault();var n,r,i=0===e.type.indexOf("touch"),o=0===e.type.indexOf("mouse"),a=0===e.type.indexOf("pointer"),s=e;if(0===e.type.indexOf("MSPointer")&&(a=!0),i){if(e.touches.length>1)return!1;n=e.changedTouches[0].pageX,r=e.changedTouches[0].pageY}return t=t||f(),(o||a)&&(n=e.clientX+t.x,r=e.clientY+t.y),s.pageOffset=t,s.points=[n,r],s.cursor=o||a,s}function v(e,t){var n=document.createElement("div"),i=document.createElement("div"),o=[r.cssClasses.handleLower,r.cssClasses.handleUpper];return e&&o.reverse(),u(i,r.cssClasses.handle),u(i,o[t]),u(n,r.cssClasses.origin),n.appendChild(i),n}function y(e,t,n){switch(e){case 1:u(t,r.cssClasses.connect),u(n[0],r.cssClasses.background);break;case 3:u(n[1],r.cssClasses.background);case 2:u(n[0],r.cssClasses.connect);case 0:u(t,r.cssClasses.background)}}function g(e,t,n){var r,i=[];for(r=0;r<e;r+=1)i.push(n.appendChild(v(t,r)));return i}function b(e,t,n){u(n,r.cssClasses.target),0===e?u(n,r.cssClasses.ltr):u(n,r.cssClasses.rtl),0===t?u(n,r.cssClasses.horizontal):u(n,r.cssClasses.vertical);var i=document.createElement("div");return u(i,r.cssClasses.base),n.appendChild(i),i}function _(e,t){if(!r.tooltips[t])return!1;var n=document.createElement("div");return n.className=r.cssClasses.tooltip,e.firstChild.appendChild(n)}function w(){r.dir&&r.tooltips.reverse();var e=$.map(_);r.dir&&(e.reverse(),r.tooltips.reverse()),W("update",function(t,n,i){e[n]&&(e[n].innerHTML=r.tooltips[n]===!0?t[n]:r.tooltips[n].to(i[n]))})}function C(e,t,n){if("range"===e||"steps"===e)return Z.xVal;if("count"===e){var r,i=100/(t-1),o=0;for(t=[];(r=o++*i)<=100;)t.push(r);e="positions"}return"positions"===e?t.map(function(e){return Z.fromStepping(n?Z.getStep(e):e)}):"values"===e?n?t.map(function(e){return Z.fromStepping(Z.getStep(Z.toStepping(e)))}):t:void 0}function j(t,n,r){function i(e,t){return(e+t).toFixed(7)/1}var o=Z.direction,a={},s=Z.xVal[0],u=Z.xVal[Z.xVal.length-1],c=!1,l=!1,f=0;return Z.direction=0,r=e(r.slice().sort(function(e,t){return e-t})),r[0]!==s&&(r.unshift(s),c=!0),r[r.length-1]!==u&&(r.push(u),l=!0),r.forEach(function(e,o){var s,u,p,d,h,m,v,y,g,b,_=e,w=r[o+1];if("steps"===n&&(s=Z.xNumSteps[o]),s||(s=w-_),_!==!1&&void 0!==w)for(u=_;u<=w;u=i(u,s)){for(d=Z.toStepping(u),h=d-f,y=h/t,g=Math.round(y),b=h/g,p=1;p<=g;p+=1)m=f+p*b,a[m.toFixed(5)]=["x",0];v=r.indexOf(u)>-1?1:"steps"===n?2:0,!o&&c&&(v=0),u===w&&l||(a[d.toFixed(5)]=[u,v]),f=d}}),Z.direction=o,a}function x(e,t,n){function i(e,t){var n=t===r.cssClasses.value,i=n?p:d,o=n?l:f;return t+" "+i[r.ort]+" "+o[e]}function o(e,t,n){return'class="'+i(n[1],t)+'" style="'+r.style+": "+e+'%"'}function a(e,i){Z.direction&&(e=100-e),i[1]=i[1]&&t?t(i[0],i[1]):i[1],c+="<div "+o(e,r.cssClasses.marker,i)+"></div>",i[1]&&(c+="<div "+o(e,r.cssClasses.value,i)+">"+n.to(i[0])+"</div>")}var s=document.createElement("div"),c="",l=[r.cssClasses.valueNormal,r.cssClasses.valueLarge,r.cssClasses.valueSub],f=[r.cssClasses.markerNormal,r.cssClasses.markerLarge,r.cssClasses.markerSub],p=[r.cssClasses.valueHorizontal,r.cssClasses.valueVertical],d=[r.cssClasses.markerHorizontal,r.cssClasses.markerVertical];return u(s,r.cssClasses.pips),u(s,0===r.ort?r.cssClasses.pipsHorizontal:r.cssClasses.pipsVertical),Object.keys(e).forEach(function(t){a(t,e[t])}),s.innerHTML=c,s}function R(e){var t=e.mode,n=e.density||1,r=e.filter||!1,i=e.values||!1,o=e.stepped||!1,a=C(t,i,o),s=j(n,t,a),u=e.format||{to:Math.round};return J.appendChild(x(s,r,u))}function P(){var e=Q.getBoundingClientRect(),t="offset"+["Width","Height"][r.ort];return 0===r.ort?e.width||Q[t]:e.height||Q[t]}function E(e,t,n){var i;for(i=0;i<r.handles;i++)if(X[i]===-1)return;void 0!==t&&1!==r.handles&&(t=Math.abs(t-r.dir)),Object.keys(te).forEach(function(r){var i=r.split(".")[0];e===i&&te[r].forEach(function(e){e.call(G,a(V()),t,a(O(Array.prototype.slice.call(ee))),n||!1,X)})})}function O(e){return 1===e.length?e[0]:r.dir?e.reverse():e}function S(e,t,n,i){var o=function(t){return!J.hasAttribute("disabled")&&(!l(J,r.cssClasses.tap)&&(t=m(t,i.pageOffset),!(e===Y.start&&void 0!==t.buttons&&t.buttons>1)&&((!i.hover||!t.buttons)&&(t.calcPoint=t.points[r.ort],void n(t,i)))))},a=[];return e.split(" ").forEach(function(e){t.addEventListener(e,o,!1),a.push([e,o])}),a}function T(e,t){if(navigator.appVersion.indexOf("MSIE 9")===-1&&0===e.buttons&&0!==t.buttonsProperty)return k(e,t);var n,r,i=t.handles||$,o=!1,a=100*(e.calcPoint-t.start)/t.baseSize,s=i[0]===$[0]?0:1;if(n=h(a,t.positions,i.length>1),o=D(i[0],n[s],1===i.length),i.length>1){if(o=D(i[1],n[s?0:1],!1)||o)for(r=0;r<t.handles.length;r++)E("slide",r)}else o&&E("slide",s)}function k(e,t){var n=Q.querySelector("."+r.cssClasses.active),i=t.handles[0]===$[0]?0:1;null!==n&&c(n,r.cssClasses.active),e.cursor&&(document.body.style.cursor="",document.body.removeEventListener("selectstart",document.body.noUiListener));var o=document.documentElement;o.noUiListeners.forEach(function(e){o.removeEventListener(e[0],e[1])}),c(J,r.cssClasses.drag),E("set",i),E("change",i),void 0!==t.handleNumber&&E("end",t.handleNumber)}function M(e,t){"mouseout"===e.type&&"HTML"===e.target.nodeName&&null===e.relatedTarget&&k(e,t)}function A(e,t){var n=document.documentElement;if(1===t.handles.length){if(t.handles[0].hasAttribute("disabled"))return!1;u(t.handles[0].children[0],r.cssClasses.active)}e.preventDefault(),e.stopPropagation();var i=S(Y.move,n,T,{start:e.calcPoint,baseSize:P(),pageOffset:e.pageOffset,handles:t.handles,handleNumber:t.handleNumber,buttonsProperty:e.buttons,positions:[X[0],X[$.length-1]]}),o=S(Y.end,n,k,{handles:t.handles,handleNumber:t.handleNumber}),a=S("mouseout",n,M,{handles:t.handles,handleNumber:t.handleNumber});if(n.noUiListeners=i.concat(o,a),e.cursor){document.body.style.cursor=getComputedStyle(e.target).cursor,$.length>1&&u(J,r.cssClasses.drag);var s=function(){return!1};document.body.noUiListener=s,document.body.addEventListener("selectstart",s,!1)}void 0!==t.handleNumber&&E("start",t.handleNumber)}function I(e){var t,o,a=e.calcPoint,s=0;return e.stopPropagation(),$.forEach(function(e){s+=n(e)[r.style]}),t=a<s/2||1===$.length?0:1,$[t].hasAttribute("disabled")&&(t=t?0:1),a-=n(Q)[r.style],o=100*a/P(),r.events.snap||i(J,r.cssClasses.tap,r.animationDuration),!$[t].hasAttribute("disabled")&&(D($[t],o),E("slide",t,!0),E("set",t,!0),E("change",t,!0),void(r.events.snap&&A(e,{handles:[$[t]]})))}function F(e){var t=e.calcPoint-n(Q)[r.style],i=Z.getStep(100*t/P()),o=Z.fromStepping(i);Object.keys(te).forEach(function(e){"hover"===e.split(".")[0]&&te[e].forEach(function(e){e.call(G,o)})})}function N(e){if(e.fixed||$.forEach(function(e,t){S(Y.start,e.children[0],A,{handles:[e],handleNumber:t})}),e.tap&&S(Y.start,Q,I,{handles:$}),e.hover&&S(Y.move,Q,F,{hover:!0}),e.drag){var t=[Q.querySelector("."+r.cssClasses.connect)];u(t[0],r.cssClasses.draggable),e.fixed&&t.push($[t[0]===$[0]?1:0].children[0]),t.forEach(function(e){S(Y.start,e,A,{handles:$})})}}function D(e,t,n){var i=e!==$[0]?1:0,a=X[0]+r.margin,s=X[1]-r.margin,l=X[0]+r.limit,f=X[1]-r.limit;return $.length>1&&(t=i?Math.max(t,a):Math.min(t,s)),n!==!1&&r.limit&&$.length>1&&(t=i?Math.min(t,l):Math.max(t,f)),t=Z.getStep(t),t=o(t),t!==X[i]&&(window.requestAnimationFrame?window.requestAnimationFrame(function(){e.style[r.style]=t+"%"}):e.style[r.style]=t+"%",e.previousSibling||(c(e,r.cssClasses.stacking),t>50&&u(e,r.cssClasses.stacking)),X[i]=t,ee[i]=Z.fromStepping(t),E("update",i),!0)}function L(e,t){var n,i,o;for(r.limit&&(e+=1),n=0;n<e;n+=1)i=n%2,o=t[i],null!==o&&o!==!1&&("number"==typeof o&&(o=String(o)),o=r.format.from(o),(o===!1||isNaN(o)||D($[i],Z.toStepping(o),n===3-r.dir)===!1)&&E("update",i))}function U(e,t){var n,o,s=a(e);for(t=void 0===t||!!t,r.dir&&r.handles>1&&s.reverse(),r.animate&&X[0]!==-1&&i(J,r.cssClasses.tap,r.animationDuration),n=$.length>1?3:1,1===s.length&&(n=1),L(n,s),o=0;o<$.length;o++)null!==s[o]&&t&&E("set",o)}function V(){var e,t=[];for(e=0;e<r.handles;e+=1)t[e]=r.format.to(ee[e]);return O(t)}function q(){for(var e in r.cssClasses)r.cssClasses.hasOwnProperty(e)&&c(J,r.cssClasses[e]);for(;J.firstChild;)J.removeChild(J.firstChild);delete J.noUiSlider}function B(){var e=X.map(function(e,t){var n=Z.getApplicableStep(e),r=s(String(n[2])),i=ee[t],o=100===e?null:n[2],a=Number((i-n[2]).toFixed(r)),u=0===e?null:a>=n[1]?n[2]:n[0]||!1;return[u,o]});return O(e)}function W(e,t){te[e]=te[e]||[],te[e].push(t),"update"===e.split(".")[0]&&$.forEach(function(e,t){E("update",t)})}function K(e){var t=e&&e.split(".")[0],n=t&&e.substring(t.length);Object.keys(te).forEach(function(e){var r=e.split(".")[0],i=e.substring(r.length);t&&t!==r||n&&n!==i||delete te[e]})}function z(e,t){ var n=V(),i=H({start:[0,0],margin:e.margin,limit:e.limit,step:void 0===e.step?r.singleStep:e.step,range:e.range,animate:e.animate,snap:void 0===e.snap?r.snap:e.snap});["margin","limit","range","animate"].forEach(function(t){void 0!==e[t]&&(r[t]=e[t])}),i.spectrum.direction=Z.direction,Z=i.spectrum,X=[-1,-1],U(e.start||n,t)}var Q,$,G,Y=p(),J=t,X=[-1,-1],Z=r.spectrum,ee=[],te={};if(J.noUiSlider)throw new Error("Slider was already initialized.");return Q=b(r.dir,r.ort,J),$=g(r.handles,r.dir,Q),y(r.connect,J,$),r.pips&&R(r.pips),r.tooltips&&w(),G={destroy:q,steps:B,on:W,off:K,get:V,set:U,updateOptions:z,options:d,target:J,pips:R},N(r.events),G}function q(e,t){if(!e.nodeName)throw new Error("noUiSlider.create requires a single element.");var n=H(t,e),r=V(e,n,t);return r.set(n.start),e.noUiSlider=r,r}j.prototype.getMargin=function(e){return 2===this.xPct.length&&h(this.xVal,e)},j.prototype.toStepping=function(e){return e=g(this.xVal,this.xPct,e),this.direction&&(e=100-e),e},j.prototype.fromStepping=function(e){return this.direction&&(e=100-e),b(this.xVal,this.xPct,e)},j.prototype.getStep=function(e){return this.direction&&(e=100-e),e=_(this.xPct,this.xSteps,this.snap,e),this.direction&&(e=100-e),e},j.prototype.getApplicableStep=function(e){var t=y(e,this.xPct),n=100===e?2:1;return[this.xNumSteps[t-2],this.xVal[t-n],this.xNumSteps[t-n]]},j.prototype.convert=function(e){return this.getStep(this.toStepping(e))};var B={to:function(e){return void 0!==e&&e.toFixed(2)},from:Number};return{create:q}})},{}],475:[function(e,t,n){"use strict";var r=Object.prototype.hasOwnProperty,i=Object.prototype.toString,o=Array.prototype.slice,a=e("./isArguments"),s=Object.prototype.propertyIsEnumerable,u=!s.call({toString:null},"toString"),c=s.call(function(){},"prototype"),l=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],f=function(e){var t=e.constructor;return t&&t.prototype===e},p={$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},d=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!p["$"+e]&&r.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{f(window[e])}catch(t){return!0}}catch(t){return!0}return!1}(),h=function(e){if("undefined"==typeof window||!d)return f(e);try{return f(e)}catch(t){return!1}},m=function(e){var t=null!==e&&"object"==typeof e,n="[object Function]"===i.call(e),o=a(e),s=t&&"[object String]"===i.call(e),f=[];if(!t&&!n&&!o)throw new TypeError("Object.keys called on a non-object");var p=c&&n;if(s&&e.length>0&&!r.call(e,0))for(var d=0;d<e.length;++d)f.push(String(d));if(o&&e.length>0)for(var m=0;m<e.length;++m)f.push(String(m));else for(var v in e)p&&"prototype"===v||!r.call(e,v)||f.push(String(v));if(u)for(var y=h(e),g=0;g<l.length;++g)y&&"constructor"===l[g]||!r.call(e,l[g])||f.push(l[g]);return f};m.shim=function(){if(Object.keys){var e=function(){return 2===(Object.keys(arguments)||"").length}(1,2);if(!e){var t=Object.keys;Object.keys=function(e){return t(a(e)?o.call(e):e)}}}else Object.keys=m;return Object.keys||m},t.exports=m},{"./isArguments":476}],476:[function(e,t,n){"use strict";var r=Object.prototype.toString;t.exports=function(e){var t=r.call(e),n="[object Arguments]"===t;return n||(n="[object Array]"!==t&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===r.call(e.callee)),n}},{}],477:[function(e,t,n){function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function o(e){if(f===setTimeout)return setTimeout(e,0);if((f===r||!f)&&setTimeout)return f=setTimeout,setTimeout(e,0);try{return f(e,0)}catch(t){try{return f.call(null,e,0)}catch(t){return f.call(this,e,0)}}}function a(e){if(p===clearTimeout)return clearTimeout(e);if((p===i||!p)&&clearTimeout)return p=clearTimeout,clearTimeout(e);try{return p(e)}catch(t){try{return p.call(null,e)}catch(t){return p.call(this,e)}}}function s(){v&&h&&(v=!1,h.length?m=h.concat(m):y=-1,m.length&&u())}function u(){if(!v){var e=o(s);v=!0;for(var t=m.length;t;){for(h=m,m=[];++y<t;)h&&h[y].run();y=-1,t=m.length}h=null,v=!1,a(e)}}function c(e,t){this.fun=e,this.array=t}function l(){}var f,p,d=t.exports={};!function(){try{f="function"==typeof setTimeout?setTimeout:r}catch(e){f=r}try{p="function"==typeof clearTimeout?clearTimeout:i}catch(e){p=i}}();var h,m=[],v=!1,y=-1;d.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];m.push(new c(e,t)),1!==m.length||v||o(u)},c.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=l,d.addListener=l,d.once=l,d.off=l,d.removeListener=l,d.removeAllListeners=l,d.emit=l,d.binding=function(e){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(e){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},{}],478:[function(e,t,n){"use strict";function r(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var i=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,s){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?r(a(e),function(a){var s=encodeURIComponent(i(a))+n;return o(e[a])?r(e[a],function(e){return s+encodeURIComponent(i(e))}).join(t):s+encodeURIComponent(i(e[a]))}).join(t):s?encodeURIComponent(i(s))+n+encodeURIComponent(i(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},a=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],479:[function(e,t,n){"use strict";t.exports=e("./lib/ReactDOM")},{"./lib/ReactDOM":509}],480:[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:{}};t.exports=r},{}],481:[function(e,t,n){"use strict";var r=e("./ReactDOMComponentTree"),i=e("fbjs/lib/focusNode"),o={focusDOMComponent:function(){i(r.getNodeFromInstance(this))}};t.exports=o},{"./ReactDOMComponentTree":512,"fbjs/lib/focusNode":91}],482:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function i(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function o(e){switch(e){case"topCompositionStart":return P.compositionStart;case"topCompositionEnd":return P.compositionEnd;case"topCompositionUpdate":return P.compositionUpdate}}function a(e,t){return"topKeyDown"===e&&t.keyCode===b}function s(e,t){switch(e){case"topKeyUp":return g.indexOf(t.keyCode)!==-1;case"topKeyDown":return t.keyCode!==b;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 c(e,t,n,r){var i,c;if(_?i=o(e):O?s(e,n)&&(i=P.compositionEnd):a(e,n)&&(i=P.compositionStart),!i)return null;j&&(O||i!==P.compositionStart?i===P.compositionEnd&&O&&(c=O.getData()):O=m.getPooled(r));var l=v.getPooled(i,t,n,r);if(c)l.data=c;else{var f=u(n);null!==f&&(l.data=f)}return d.accumulateTwoPhaseDispatches(l),l}function l(e,t){switch(e){case"topCompositionEnd":return u(t);case"topKeyPress":var n=t.which;return n!==x?null:(E=!0,R);case"topTextInput":var r=t.data;return r===R&&E?null:r;default:return null}}function f(e,t){if(O){if("topCompositionEnd"===e||!_&&s(e,t)){var n=O.getData();return m.release(O),O=null,n}return null}switch(e){case"topPaste":return null;case"topKeyPress":return t.which&&!i(t)?String.fromCharCode(t.which):null;case"topCompositionEnd":return j?null:t.data;default:return null}}function p(e,t,n,r){var i;if(i=C?l(e,n):f(e,n),!i)return null;var o=y.getPooled(P.beforeInput,t,n,r);return o.data=i,d.accumulateTwoPhaseDispatches(o),o}var d=e("./EventPropagators"),h=e("fbjs/lib/ExecutionEnvironment"),m=e("./FallbackCompositionState"),v=e("./SyntheticCompositionEvent"),y=e("./SyntheticInputEvent"),g=[9,13,27,32],b=229,_=h.canUseDOM&&"CompositionEvent"in window,w=null;h.canUseDOM&&"documentMode"in document&&(w=document.documentMode);var C=h.canUseDOM&&"TextEvent"in window&&!w&&!r(),j=h.canUseDOM&&(!_||w&&w>8&&w<=11),x=32,R=String.fromCharCode(x),P={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"]}},E=!1,O=null,S={eventTypes:P,extractEvents:function(e,t,n,r){return[c(e,t,n,r),p(e,t,n,r)]}};t.exports=S},{"./EventPropagators":498,"./FallbackCompositionState":499,"./SyntheticCompositionEvent":563,"./SyntheticInputEvent":567,"fbjs/lib/ExecutionEnvironment":83}],483:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var i={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(i).forEach(function(e){o.forEach(function(t){i[r(t,e)]=i[e]})});var a={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},s={isUnitlessNumber:i,shorthandPropertyExpansions:a};t.exports=s},{}],484:[function(e,t,n){"use strict";var r=e("./CSSProperty"),i=e("fbjs/lib/ExecutionEnvironment"),o=(e("./ReactInstrumentation"),e("fbjs/lib/camelizeStyleName"),e("./dangerousStyleValue")),a=e("fbjs/lib/hyphenateStyleName"),s=e("fbjs/lib/memoizeStringOnly"),u=(e("fbjs/lib/warning"),s(function(e){return a(e)})),c=!1,l="cssFloat";if(i.canUseDOM){var f=document.createElement("div").style;try{f.font=""}catch(p){c=!0}void 0===document.documentElement.style.cssFloat&&(l="styleFloat")}var d={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];null!=i&&(n+=u(r)+":",n+=o(r,i,t)+";")}return n||null},setValueForStyles:function(e,t,n){var i=e.style;for(var a in t)if(t.hasOwnProperty(a)){var s=o(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=l),s)i[a]=s;else{var u=c&&r.shorthandPropertyExpansions[a];if(u)for(var f in u)i[f]="";else i[a]=""}}}};t.exports=d},{"./CSSProperty":483,"./ReactInstrumentation":541,"./dangerousStyleValue":580,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/camelizeStyleName":85,"fbjs/lib/hyphenateStyleName":96,"fbjs/lib/memoizeStringOnly":100,"fbjs/lib/warning":104}],485:[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 i=e("./reactProdInvariant"),o=e("./PooledClass"),a=(e("fbjs/lib/invariant"),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?i("24"):void 0,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}());t.exports=o.addPoolingTo(a)},{"./PooledClass":503,"./reactProdInvariant":599,"fbjs/lib/invariant":97}],486:[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 i(e){var t=j.getPooled(E.change,S,e,x(e));b.accumulateTwoPhaseDispatches(t),C.batchedUpdates(o,t)}function o(e){g.enqueueEvents(e),g.processEventQueue(!1)}function a(e,t){O=e,S=t,O.attachEvent("onchange",i)}function s(){O&&(O.detachEvent("onchange",i),O=null,S=null)}function u(e,t){if("topChange"===e)return t}function c(e,t,n){"topFocus"===e?(s(),a(t,n)):"topBlur"===e&&s()}function l(e,t){O=e,S=t,T=e.value,k=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(O,"value",I),O.attachEvent?O.attachEvent("onpropertychange",p):O.addEventListener("propertychange",p,!1)}function f(){O&&(delete O.value,O.detachEvent?O.detachEvent("onpropertychange",p):O.removeEventListener("propertychange",p,!1),O=null,S=null,T=null,k=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==T&&(T=t,i(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 m(e,t){if(("topSelectionChange"===e||"topKeyUp"===e||"topKeyDown"===e)&&O&&O.value!==T)return T=O.value,S}function v(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=e("./EventPluginHub"),b=e("./EventPropagators"),_=e("fbjs/lib/ExecutionEnvironment"),w=e("./ReactDOMComponentTree"),C=e("./ReactUpdates"),j=e("./SyntheticEvent"),x=e("./getEventTarget"),R=e("./isEventSupported"),P=e("./isTextInputElement"),E={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:["topBlur","topChange","topClick","topFocus","topInput","topKeyDown","topKeyUp","topSelectionChange"]}},O=null,S=null,T=null,k=null,M=!1;_.canUseDOM&&(M=R("change")&&(!document.documentMode||document.documentMode>8));var A=!1;_.canUseDOM&&(A=R("input")&&(!document.documentMode||document.documentMode>11));var I={get:function(){return k.get.call(this)},set:function(e){T=""+e,k.set.call(this,e)}},F={eventTypes:E,extractEvents:function(e,t,n,i){var o,a,s=t?w.getNodeFromInstance(t):window;if(r(s)?M?o=u:a=c:P(s)?A?o=d:(o=m,a=h):v(s)&&(o=y),o){var l=o(e,t);if(l){var f=j.getPooled(E.change,l,n,i);return f.type="change",b.accumulateTwoPhaseDispatches(f),f}}a&&a(e,s,t)}};t.exports=F},{"./EventPluginHub":495,"./EventPropagators":498,"./ReactDOMComponentTree":512,"./ReactUpdates":556,"./SyntheticEvent":565,"./getEventTarget":588,"./isEventSupported":596,"./isTextInputElement":597,"fbjs/lib/ExecutionEnvironment":83}],487:[function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function i(e,t,n){l.insertTreeBefore(e,t,n)}function o(e,t,n){Array.isArray(t)?s(e,t[0],t[1],n):m(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],u(e,t,n),e.removeChild(n)}e.removeChild(t)}function s(e,t,n,r){for(var i=t;;){var o=i.nextSibling;if(m(e,i,r),i===n)break;i=o}}function u(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function c(e,t,n){var r=e.parentNode,i=e.nextSibling;i===t?n&&m(r,document.createTextNode(n),i):n?(h(i,n),u(r,i,t)):u(r,e,t)}var l=e("./DOMLazyTree"),f=e("./Danger"),p=(e("./ReactDOMComponentTree"),e("./ReactInstrumentation"),e("./createMicrosoftUnsafeLocalFunction")),d=e("./setInnerHTML"),h=e("./setTextContent"),m=p(function(e,t,n){e.insertBefore(t,n)}),v=f.dangerouslyReplaceNodeWithMarkup,y={dangerouslyReplaceNodeWithMarkup:v,replaceDelimitedText:c,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var s=t[n];switch(s.type){case"INSERT_MARKUP":i(e,s.content,r(e,s.afterNode));break;case"MOVE_EXISTING":o(e,s.fromNode,r(e,s.afterNode));break;case"SET_MARKUP":d(e,s.content);break;case"TEXT_CONTENT":h(e,s.content);break;case"REMOVE_NODE":a(e,s.fromNode)}}}};t.exports=y},{"./DOMLazyTree":488,"./Danger":492,"./ReactDOMComponentTree":512,"./ReactInstrumentation":541,"./createMicrosoftUnsafeLocalFunction":579,"./setInnerHTML":601,"./setTextContent":602}],488:[function(e,t,n){"use strict";function r(e){if(v){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)y(t,n[r],null);else null!=e.html?f(t,e.html):null!=e.text&&d(t,e.text)}}function i(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function o(e,t){v?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){v?e.html=t:f(e.node,t)}function s(e,t){v?e.text=t:d(e.node,t)}function u(){return this.node.nodeName}function c(e){return{node:e,children:[],html:null,text:null,toString:u}}var l=e("./DOMNamespaces"),f=e("./setInnerHTML"),p=e("./createMicrosoftUnsafeLocalFunction"),d=e("./setTextContent"),h=1,m=11,v="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),y=p(function(e,t,n){t.node.nodeType===m||t.node.nodeType===h&&"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=y,c.replaceChildWithTree=i,c.queueChild=o,c.queueHTML=a,c.queueText=s,t.exports=c},{"./DOMNamespaces":489,"./createMicrosoftUnsafeLocalFunction":579,"./setInnerHTML":601,"./setTextContent":602}],489:[function(e,t,n){"use strict";var r={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};t.exports=r},{}],490:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var i=e("./reactProdInvariant"),o=(e("fbjs/lib/invariant"),{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=o,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var f in n){s.properties.hasOwnProperty(f)?i("48",f):void 0;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?void 0:i("50",f),u.hasOwnProperty(f)){var m=u[f];h.attributeName=m}a.hasOwnProperty(f)&&(h.attributeNamespace=a[f]),c.hasOwnProperty(f)&&(h.propertyName=c[f]),l.hasOwnProperty(f)&&(h.mutationMethod=l[f]),s.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",s={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<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},injection:o};t.exports=s},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],491:[function(e,t,n){"use strict";function r(e){return!!c.hasOwnProperty(e)||!u.hasOwnProperty(e)&&(s.test(e)?(c[e]=!0,!0):(u[e]=!0,!1))}function i(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&t===!1}var o=e("./DOMProperty"),a=(e("./ReactDOMComponentTree"),e("./ReactInstrumentation"),e("./quoteAttributeValueForBrowser")),s=(e("fbjs/lib/warning"),new RegExp("^["+o.ATTRIBUTE_NAME_START_CHAR+"]["+o.ATTRIBUTE_NAME_CHAR+"]*$")),u={},c={},l={createMarkupForID:function(e){return o.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(o.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return o.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(o.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=o.properties.hasOwnProperty(e)?o.properties[e]:null;if(n){if(i(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+a(t)}return o.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=o.properties.hasOwnProperty(t)?o.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else{if(i(r,n))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty)e[r.propertyName]=n;else{var s=r.attributeName,u=r.attributeNamespace;u?e.setAttributeNS(u,s,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(s,""):e.setAttribute(s,""+n)}}}else if(o.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=o.properties.hasOwnProperty(t)?o.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var i=n.propertyName;n.hasBooleanValue?e[i]=!1:e[i]=""}else e.removeAttribute(n.attributeName)}else o.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=l},{"./DOMProperty":490,"./ReactDOMComponentTree":512,"./ReactInstrumentation":541,"./quoteAttributeValueForBrowser":598,"fbjs/lib/warning":104}],492:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=e("./DOMLazyTree"),o=e("fbjs/lib/ExecutionEnvironment"),a=e("fbjs/lib/createNodesFromMarkup"),s=e("fbjs/lib/emptyFunction"),u=(e("fbjs/lib/invariant"),{dangerouslyReplaceNodeWithMarkup:function(e,t){if(o.canUseDOM?void 0:r("56"),t?void 0:r("57"),"HTML"===e.nodeName?r("58"):void 0,"string"==typeof t){var n=a(t,s)[0];e.parentNode.replaceChild(n,e)}else i.replaceChildWithTree(e,t)}});t.exports=u},{"./DOMLazyTree":488,"./reactProdInvariant":599,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/createNodesFromMarkup":88,"fbjs/lib/emptyFunction":89,"fbjs/lib/invariant":97}],493:[function(e,t,n){"use strict";var r=["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"];t.exports=r},{}],494:[function(e,t,n){"use strict";var r=e("./EventPropagators"),i=e("./ReactDOMComponentTree"),o=e("./SyntheticMouseEvent"),a={mouseEnter:{registrationName:"onMouseEnter",dependencies:["topMouseOut","topMouseOver"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["topMouseOut","topMouseOver"]}},s={eventTypes:a,extractEvents:function(e,t,n,s){if("topMouseOver"===e&&(n.relatedTarget||n.fromElement))return null;if("topMouseOut"!==e&&"topMouseOver"!==e)return null;var u;if(s.window===s)u=s;else{var c=s.ownerDocument;u=c?c.defaultView||c.parentWindow:window}var l,f;if("topMouseOut"===e){l=t;var p=n.relatedTarget||n.toElement;f=p?i.getClosestInstanceFromNode(p):null}else l=null,f=t;if(l===f)return null;var d=null==l?u:i.getNodeFromInstance(l),h=null==f?u:i.getNodeFromInstance(f),m=o.getPooled(a.mouseLeave,l,n,s);m.type="mouseleave",m.target=d,m.relatedTarget=h;var v=o.getPooled(a.mouseEnter,f,n,s);return v.type="mouseenter",v.target=h,v.relatedTarget=d,r.accumulateEnterLeaveDispatches(m,v,l,f),[m,v]}};t.exports=s},{"./EventPropagators":498,"./ReactDOMComponentTree":512,"./SyntheticMouseEvent":569}],495:[function(e,t,n){"use strict";function r(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function i(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 o=e("./reactProdInvariant"),a=e("./EventPluginRegistry"),s=e("./EventPluginUtils"),u=e("./ReactErrorUtils"),c=e("./accumulateInto"),l=e("./forEachAccumulated"),f=(e("fbjs/lib/invariant"),{}),p=null,d=function(e,t){e&&(s.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},h=function(e){return d(e,!0)},m=function(e){return d(e,!1)},v=function(e){return"."+e._rootNodeID},y={injection:{injectEventPluginOrder:a.injectEventPluginOrder,injectEventPluginsByName:a.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n?o("94",t,typeof n):void 0;var r=v(e),i=f[t]||(f[t]={});i[r]=n;var s=a.registrationNameModules[t];s&&s.didPutListener&&s.didPutListener(e,t,n)},getListener:function(e,t){var n=f[t];if(i(t,e._currentElement.type,e._currentElement.props))return null;var r=v(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){var i=v(e);delete r[i]}},deleteAllListeners:function(e){var t=v(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 i,o=a.plugins,s=0;s<o.length;s++){var u=o[s];if(u){var l=u.extractEvents(e,t,n,r);l&&(i=c(i,l))}}return i},enqueueEvents:function(e){e&&(p=c(p,e))},processEventQueue:function(e){var t=p;p=null,e?l(t,h):l(t,m),p?o("95"):void 0,u.rethrowCaughtError()},__purge:function(){f={}},__getListenerBank:function(){return f}};t.exports=y},{"./EventPluginRegistry":496,"./EventPluginUtils":497,"./ReactErrorUtils":532,"./accumulateInto":576,"./forEachAccumulated":584,"./reactProdInvariant":599,"fbjs/lib/invariant":97}],496:[function(e,t,n){"use strict";function r(){if(s)for(var e in u){var t=u[e],n=s.indexOf(e);if(n>-1?void 0:a("96",e),!c.plugins[n]){t.extractEvents?void 0:a("97",e),c.plugins[n]=t;var r=t.eventTypes;for(var o in r)i(r[o],t,o)?void 0:a("98",o,e)}}}function i(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)?a("99",n):void 0,c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var i in r)if(r.hasOwnProperty(i)){var s=r[i];o(s,t,n)}return!0}return!!e.registrationName&&(o(e.registrationName,t,n),!0)}function o(e,t,n){c.registrationNameModules[e]?a("100",e):void 0,c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e("./reactProdInvariant"),s=(e("fbjs/lib/invariant"),null),u={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){s?a("101"):void 0,s=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var i=e[n];u.hasOwnProperty(n)&&u[n]===i||(u[n]?a("102",n):void 0,u[n]=i,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 i=c.registrationNameModules[n[r]];if(i)return i}}return null},_resetEventPlugins:function(){s=null;for(var e in u)u.hasOwnProperty(e)&&delete u[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 i in r)r.hasOwnProperty(i)&&delete r[i]}};t.exports=c},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],497:[function(e,t,n){"use strict";function r(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function i(e){return"topMouseMove"===e||"topTouchMove"===e}function o(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var i=e.type||"unknown-event";e.currentTarget=y.getNodeFromInstance(r),t?m.invokeGuardedCallbackWithCatch(i,n,e):m.invokeGuardedCallback(i,n,e),e.currentTarget=null}function s(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var i=0;i<n.length&&!e.isPropagationStopped();i++)a(e,t,n[i],r[i]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function u(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=u(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function l(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)?h("103"):void 0,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=e("./reactProdInvariant"),m=e("./ReactErrorUtils"),v=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),{injectComponentTree:function(e){p=e},injectTreeTraversal:function(e){d=e}}),y={isEndish:r,isMoveish:i,isStartish:o,executeDirectDispatch:l,executeDispatchesInOrder:s,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,i){return d.traverseEnterLeave(e,t,n,r,i)},injection:v};t.exports=y},{"./ReactErrorUtils":532,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104}],498:[function(e,t,n){ "use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function i(e,t,n){var i=r(e,n,t);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.traverseTwoPhase(e._targetInst,i,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?h.getParentInstance(t):null;h.traverseTwoPhase(n,i,e)}}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,i=y(e,r);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchInstances=m(n._dispatchInstances,e))}}function u(e){e&&e.dispatchConfig.registrationName&&s(e._targetInst,null,e)}function c(e){v(e,o)}function l(e){v(e,a)}function f(e,t,n,r){h.traverseEnterLeave(n,r,s,e,t)}function p(e){v(e,u)}var d=e("./EventPluginHub"),h=e("./EventPluginUtils"),m=e("./accumulateInto"),v=e("./forEachAccumulated"),y=(e("fbjs/lib/warning"),d.getListener),g={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:l,accumulateDirectDispatches:p,accumulateEnterLeaveDispatches:f};t.exports=g},{"./EventPluginHub":495,"./EventPluginUtils":497,"./accumulateInto":576,"./forEachAccumulated":584,"fbjs/lib/warning":104}],499:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var i=e("object-assign"),o=e("./PooledClass"),a=e("./getTextContentAccessor");i(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,i=this.getText(),o=i.length;for(e=0;e<r&&n[e]===i[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===i[o-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=i.slice(e,s),this._fallbackText}}),o.addPoolingTo(r),t.exports=r},{"./PooledClass":503,"./getTextContentAccessor":593,"object-assign":606}],500:[function(e,t,n){"use strict";var r=e("./DOMProperty"),i=r.injection.MUST_USE_PROPERTY,o=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_NUMERIC_VALUE,s=r.injection.HAS_POSITIVE_NUMERIC_VALUE,u=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:o,allowTransparency:0,alt:0,as:0,async:o,autoComplete:0,autoPlay:o,capture:o,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:i|o,cite:0,classID:0,className:0,cols:s,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:o,coords:0,crossOrigin:0,data:0,dateTime:0,"default":o,defer:o,dir:0,disabled:o,download:u,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:o,formTarget:0,frameBorder:0,headers:0,height:0,hidden:o,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:o,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:i|o,muted:i|o,name:0,nonce:0,noValidate:o,open:o,optimum:0,pattern:0,placeholder:0,playsInline:o,poster:0,preload:0,profile:0,radioGroup:0,readOnly:o,referrerPolicy:0,rel:0,required:o,reversed:o,role:0,rows:s,rowSpan:a,sandbox:0,scope:0,scoped:o,scrolling:0,seamless:o,selected:i|o,shape:0,size:s,sizes:0,span:s,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:o,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};t.exports=c},{"./DOMProperty":490}],501:[function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"},r=(""+e).replace(t,function(e){return n[e]});return"$"+r}function i(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"},r="."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1);return(""+r).replace(t,function(e){return n[e]})}var o={escape:r,unescape:i};t.exports=o},{}],502:[function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink?s("87"):void 0}function i(e){r(e),null!=e.value||null!=e.onChange?s("88"):void 0}function o(e){r(e),null!=e.checked||null!=e.onChange?s("89"):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=e("./reactProdInvariant"),u=e("react/lib/React"),c=e("./ReactPropTypesSecret"),l=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),{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.PropTypes.func},p={},d={checkPropTypes:function(e,t,n){for(var r in f){if(f.hasOwnProperty(r))var i=f[r](t,r,e,"prop",null,c);if(i instanceof Error&&!(i.message in p)){p[i.message]=!0;a(n)}}},getValue:function(e){return e.valueLink?(i(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(o(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(i(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(o(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};t.exports=d},{"./ReactPropTypesSecret":549,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/React":610}],503:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=(e("fbjs/lib/invariant"),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),o=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 i=r.instancePool.pop();return r.call(i,e,t,n),i}return new r(e,t,n)},s=function(e,t,n,r){var i=this;if(i.instancePool.length){var o=i.instancePool.pop();return i.call(o,e,t,n,r),o}return new i(e,t,n,r)},u=function(e){var t=this;e instanceof t?void 0:r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,l=i,f=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||l,n.poolSize||(n.poolSize=c),n.release=u,n},p={addPoolingTo:f,oneArgumentPooler:i,twoArgumentPooler:o,threeArgumentPooler:a,fourArgumentPooler:s};t.exports=p},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],504:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=d++,f[e[m]]={}),f[e[m]]}var i,o=e("object-assign"),a=e("./EventPluginRegistry"),s=e("./ReactEventEmitterMixin"),u=e("./ViewportMetrics"),c=e("./getVendorPrefixedEventName"),l=e("./isEventSupported"),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"},m="_reactListenersID"+String(Math.random()).slice(2),v=o({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e}},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),o=a.registrationNameDependencies[e],s=0;s<o.length;s++){var u=o[s];i.hasOwnProperty(u)&&i[u]||("topWheel"===u?l("wheel")?v.ReactEventListener.trapBubbledEvent("topWheel","wheel",n):l("mousewheel")?v.ReactEventListener.trapBubbledEvent("topWheel","mousewheel",n):v.ReactEventListener.trapBubbledEvent("topWheel","DOMMouseScroll",n):"topScroll"===u?l("scroll",!0)?v.ReactEventListener.trapCapturedEvent("topScroll","scroll",n):v.ReactEventListener.trapBubbledEvent("topScroll","scroll",v.ReactEventListener.WINDOW_HANDLE):"topFocus"===u||"topBlur"===u?(l("focus",!0)?(v.ReactEventListener.trapCapturedEvent("topFocus","focus",n),v.ReactEventListener.trapCapturedEvent("topBlur","blur",n)):l("focusin")&&(v.ReactEventListener.trapBubbledEvent("topFocus","focusin",n),v.ReactEventListener.trapBubbledEvent("topBlur","focusout",n)),i.topBlur=!0,i.topFocus=!0):h.hasOwnProperty(u)&&v.ReactEventListener.trapBubbledEvent(u,h[u],n),i[u]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},supportsEventPageXY:function(){if(!document.createEvent)return!1;var e=document.createEvent("MouseEvent");return null!=e&&"pageX"in e},ensureScrollValueMonitoring:function(){if(void 0===i&&(i=v.supportsEventPageXY()),!i&&!p){var e=u.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),p=!0}}});t.exports=v},{"./EventPluginRegistry":496,"./ReactEventEmitterMixin":533,"./ViewportMetrics":575,"./getVendorPrefixedEventName":594,"./isEventSupported":596,"object-assign":606}],505:[function(e,t,n){(function(n){"use strict";function r(e,t,n,r){var i=void 0===e[n];null!=t&&i&&(e[n]=o(t,!0))}var i=e("./ReactReconciler"),o=e("./instantiateReactComponent"),a=(e("./KeyEscapeUtils"),e("./shouldUpdateReactComponent")),s=e("./traverseAllChildren");e("fbjs/lib/warning");"undefined"!=typeof n&&n.env,1;var u={instantiateChildren:function(e,t,n,i){if(null==e)return null;var o={};return s(e,r,o),o},updateChildren:function(e,t,n,r,s,u,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,m=t[p];if(null!=d&&a(h,m))i.receiveComponent(d,m,s,l),t[p]=d;else{d&&(r[p]=i.getHostNode(d),i.unmountComponent(d,!1));var v=o(m,!0);t[p]=v;var y=i.mountComponent(v,s,u,c,l,f);n.push(y)}}for(p in e)!e.hasOwnProperty(p)||t&&t.hasOwnProperty(p)||(d=e[p],r[p]=i.getHostNode(d),i.unmountComponent(d,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];i.unmountComponent(r,t)}}};t.exports=u}).call(this,e("_process"))},{"./KeyEscapeUtils":501,"./ReactReconciler":551,"./instantiateReactComponent":595,"./shouldUpdateReactComponent":603,"./traverseAllChildren":604,_process:477,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],506:[function(e,t,n){"use strict";var r=e("./DOMChildrenOperations"),i=e("./ReactDOMIDOperations"),o={processChildrenUpdates:i.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup};t.exports=o},{"./DOMChildrenOperations":487,"./ReactDOMIDOperations":516}],507:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=(e("fbjs/lib/invariant"),!1),o={replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){i?r("104"):void 0,o.replaceNodeWithMarkup=e.replaceNodeWithMarkup,o.processChildrenUpdates=e.processChildrenUpdates,i=!0}}};t.exports=o},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],508:[function(e,t,n){"use strict";function r(e){}function i(e,t){}function o(e){return!(!e.prototype||!e.prototype.isReactComponent)}function a(e){return!(!e.prototype||!e.prototype.isPureReactComponent)}var s=e("./reactProdInvariant"),u=e("object-assign"),c=e("react/lib/React"),l=e("./ReactComponentEnvironment"),f=e("react/lib/ReactCurrentOwner"),p=e("./ReactErrorUtils"),d=e("./ReactInstanceMap"),h=(e("./ReactInstrumentation"),e("./ReactNodeTypes")),m=e("./ReactReconciler"),v=e("fbjs/lib/emptyObject"),y=(e("fbjs/lib/invariant"),e("fbjs/lib/shallowEqual")),g=e("./shouldUpdateReactComponent"),b=(e("fbjs/lib/warning"),{ImpureClass:0,PureClass:1,StatelessFunctional:2});r.prototype.render=function(){var e=d.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return i(e,t),t};var _=1,w={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=_++,this._hostParent=t,this._hostContainerInfo=n;var l,f=this._currentElement.props,p=this._processContext(u),h=this._currentElement.type,m=e.getUpdateQueue(),y=o(h),g=this._constructComponent(y,f,p,m);y||null!=g&&null!=g.render?a(h)?this._compositeType=b.PureClass:this._compositeType=b.ImpureClass:(l=g,i(h,l),null===g||g===!1||c.isValidElement(g)?void 0:s("105",h.displayName||h.name||"Component"),g=new r(h),this._compositeType=b.StatelessFunctional);g.props=f,g.context=p,g.refs=v,g.updater=m,this._instance=g,d.set(g,this);var w=g.state;void 0===w&&(g.state=w=null),"object"!=typeof w||Array.isArray(w)?s("106",this.getName()||"ReactCompositeComponent"):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var C;return C=g.unstable_handleError?this.performInitialMountWithErrorHandling(l,t,n,e,u):this.performInitialMount(l,t,n,e,u),g.componentDidMount&&e.getReactMountReady().enqueue(g.componentDidMount,g),C},_constructComponent:function(e,t,n,r){return this._constructComponentWithoutOwner(e,t,n,r)},_constructComponentWithoutOwner:function(e,t,n,r){var i=this._currentElement.type;return e?new i(t,n,r):i(t,n,r)},performInitialMountWithErrorHandling:function(e,t,n,r,i){var o,a=r.checkpoint();try{o=this.performInitialMount(e,t,n,r,i)}catch(s){r.rollback(a),this._instance.unstable_handleError(s),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),o=this.performInitialMount(e,t,n,r,i)}return o},performInitialMount:function(e,t,n,r,i){var o=this._instance,a=0;o.componentWillMount&&(o.componentWillMount(),this._pendingStateQueue&&(o.state=this._processPendingState(o.props,o.context))),void 0===e&&(e=this._renderValidatedComponent());var s=h.getType(e);this._renderedNodeType=s;var u=this._instantiateReactComponent(e,s!==h.EMPTY);this._renderedComponent=u;var c=m.mountComponent(u,r,t,n,this._processChildContext(i),a);return c},getHostNode:function(){return m.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()";p.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(m.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,d.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return v;var r={};for(var i in n)r[i]=e[i];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?s("107",this.getName()||"ReactCompositeComponent"):void 0;for(var i in t)i in n.childContextTypes?void 0:s("108",this.getName()||"ReactCompositeComponent",i);return u({},e,t)}return e},_checkContextTypes:function(e,t,n){},receiveComponent:function(e,t,n){var r=this._currentElement,i=this._context;this._pendingElement=null,this.updateComponent(t,r,e,i,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement?m.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,i){var o=this._instance;null==o?s("136",this.getName()||"ReactCompositeComponent"):void 0;var a,u=!1;this._context===i?a=o.context:(a=this._processContext(i),u=!0);var c=t.props,l=n.props;t!==n&&(u=!0),u&&o.componentWillReceiveProps&&o.componentWillReceiveProps(l,a);var f=this._processPendingState(l,a),p=!0;this._pendingForceUpdate||(o.shouldComponentUpdate?p=o.shouldComponentUpdate(l,f,a):this._compositeType===b.PureClass&&(p=!y(c,l)||!y(o.state,f))),this._updateBatchNumber=null,p?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,l,f,a,e,i)):(this._currentElement=n,this._context=i,o.props=l,o.state=f,o.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,i=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(i&&1===r.length)return r[0];for(var o=u({},i?r[0]:n.state),a=i?1:0;a<r.length;a++){var s=r[a];u(o,"function"==typeof s?s.call(n,o,e,t):s)}return o},_performComponentUpdate:function(e,t,n,r,i,o){var a,s,u,c=this._instance,l=Boolean(c.componentDidUpdate);l&&(a=c.props,s=c.state,u=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=o,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(i,o),l&&i.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,s,u),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,i=this._renderValidatedComponent(),o=0;if(g(r,i))m.receiveComponent(n,i,e,this._processChildContext(t));else{var a=m.getHostNode(n);m.unmountComponent(n,!1);var s=h.getType(i);this._renderedNodeType=s;var u=this._instantiateReactComponent(i,s!==h.EMPTY);this._renderedComponent=u;var c=m.mountComponent(u,e,this._hostParent,this._hostContainerInfo,this._processChildContext(t),o);this._replaceNodeWithMarkup(a,c,n)}},_replaceNodeWithMarkup:function(e,t,n){l.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e,t=this._instance;return e=t.render()},_renderValidatedComponent:function(){var e;if(this._compositeType!==b.StatelessFunctional){f.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{f.current=null}}else e=this._renderValidatedComponentWithoutOwnerOrContext();return null===e||e===!1||c.isValidElement(e)?void 0:s("109",this.getName()||"ReactCompositeComponent"),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n?s("110"):void 0;var r=t.getPublicInstance(),i=n.refs===v?n.refs={}:n.refs;i[e]=r},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return this._compositeType===b.StatelessFunctional?null:e},_instantiateReactComponent:null};t.exports=w},{"./ReactComponentEnvironment":507,"./ReactErrorUtils":532,"./ReactInstanceMap":540,"./ReactInstrumentation":541,"./ReactNodeTypes":546,"./ReactReconciler":551,"./checkReactTypeSpec":578,"./reactProdInvariant":599,"./shouldUpdateReactComponent":603,"fbjs/lib/emptyObject":90,"fbjs/lib/invariant":97,"fbjs/lib/shallowEqual":103,"fbjs/lib/warning":104,"object-assign":606,"react/lib/React":610,"react/lib/ReactCurrentOwner":615}],509:[function(e,t,n){"use strict";var r=e("./ReactDOMComponentTree"),i=e("./ReactDefaultInjection"),o=e("./ReactMount"),a=e("./ReactReconciler"),s=e("./ReactUpdates"),u=e("./ReactVersion"),c=e("./findDOMNode"),l=e("./getHostComponentFromComposite"),f=e("./renderSubtreeIntoContainer");e("fbjs/lib/warning");i.inject();var p={findDOMNode:c,render:o.render,unmountComponentAtNode:o.unmountComponentAtNode,version:u,unstable_batchedUpdates:s.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:o,Reconciler:a});t.exports=p},{"./ReactDOMComponentTree":512,"./ReactDOMInvalidARIAHook":518,"./ReactDOMNullInputValuePropHook":519,"./ReactDOMUnknownPropertyHook":526,"./ReactDefaultInjection":529,"./ReactInstrumentation":541,"./ReactMount":544,"./ReactReconciler":551,"./ReactUpdates":556,"./ReactVersion":557,"./findDOMNode":582,"./getHostComponentFromComposite":589,"./renderSubtreeIntoContainer":600,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/warning":104}],510:[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 i(e,t){t&&($[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML?m("137",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""):void 0),null!=t.dangerouslySetInnerHTML&&(null!=t.children?m("60"):void 0,"object"==typeof t.dangerouslySetInnerHTML&&q in t.dangerouslySetInnerHTML?void 0:m("61")),null!=t.style&&"object"!=typeof t.style?m("62",r(e)):void 0)}function o(e,t,n,r){if(!(r instanceof A)){var i=e._hostContainerInfo,o=i._node&&i._node.nodeType===W,s=o?i._node:i._ownerDocument;L(t,s),r.getReactMountReady().enqueue(a,{inst:e,registrationName:t,listener:n})}}function a(){var e=this;j.putListener(e.inst,e.registrationName,e.listener)}function s(){var e=this;O.postMountWrapper(e)}function u(){var e=this;k.postMountWrapper(e)}function c(){var e=this;S.postMountWrapper(e)}function l(){var e=this;e._rootNodeID?void 0:m("63");var t=D(e);switch(t?void 0:m("64"),e._tag){case"iframe":case"object":e._wrapperState.listeners=[R.trapBubbledEvent("topLoad","load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in K)K.hasOwnProperty(n)&&e._wrapperState.listeners.push(R.trapBubbledEvent(n,K[n],t));break;case"source":e._wrapperState.listeners=[R.trapBubbledEvent("topError","error",t)];break;case"img":e._wrapperState.listeners=[R.trapBubbledEvent("topError","error",t),R.trapBubbledEvent("topLoad","load",t)];break;case"form":e._wrapperState.listeners=[R.trapBubbledEvent("topReset","reset",t),R.trapBubbledEvent("topSubmit","submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[R.trapBubbledEvent("topInvalid","invalid",t)]}}function f(){T.postUpdateWrapper(this)}function p(e){J.call(Y,e)||(G.test(e)?void 0:m("65",e),Y[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 m=e("./reactProdInvariant"),v=e("object-assign"),y=e("./AutoFocusUtils"),g=e("./CSSPropertyOperations"),b=e("./DOMLazyTree"),_=e("./DOMNamespaces"),w=e("./DOMProperty"),C=e("./DOMPropertyOperations"),j=e("./EventPluginHub"),x=e("./EventPluginRegistry"),R=e("./ReactBrowserEventEmitter"),P=e("./ReactDOMComponentFlags"),E=e("./ReactDOMComponentTree"),O=e("./ReactDOMInput"),S=e("./ReactDOMOption"),T=e("./ReactDOMSelect"),k=e("./ReactDOMTextarea"),M=(e("./ReactInstrumentation"),e("./ReactMultiChild")),A=e("./ReactServerRenderingTransaction"),I=(e("fbjs/lib/emptyFunction"),e("./escapeTextContentForBrowser")),F=(e("fbjs/lib/invariant"),e("./isEventSupported"),e("fbjs/lib/shallowEqual"),e("./validateDOMNesting"),e("fbjs/lib/warning"),P),N=j.deleteListener,D=E.getNodeFromInstance,L=R.listenTo,U=x.registrationNameModules,H={string:!0,number:!0},V="style",q="__html",B={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},W=11,K={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},Q={listing:!0,pre:!0,textarea:!0},$=v({menuitem:!0},z),G=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Y={},J={}.hasOwnProperty,X=1;h.displayName="ReactDOMComponent",h.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=X++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var o=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":O.mountWrapper(this,o,t),o=O.getHostProps(this,o),e.getReactMountReady().enqueue(l,this);break;case"option":S.mountWrapper(this,o,t),o=S.getHostProps(this,o);break;case"select":T.mountWrapper(this,o,t),o=T.getHostProps(this,o),e.getReactMountReady().enqueue(l,this);break;case"textarea":k.mountWrapper(this,o,t),o=k.getHostProps(this,o),e.getReactMountReady().enqueue(l,this)}i(this,o);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 m=h.createElement("div"),v=this._currentElement.type;m.innerHTML="<"+v+"></"+v+">",d=m.removeChild(m.firstChild)}else d=o.is?h.createElement(this._currentElement.type,o.is):h.createElement(this._currentElement.type);else d=h.createElementNS(a,this._currentElement.type);E.precacheNode(this,d),this._flags|=F.hasCachedChildNodes,this._hostParent||C.setAttributeForRoot(d),this._updateDOMProperties(null,o,e);var g=b(d);this._createInitialChildren(e,o,r,g),p=g}else{var w=this._createOpenTagMarkupAndPutListeners(e,o),j=this._createContentMarkup(e,o,r);p=!j&&z[this._tag]?w+"/>":w+">"+j+"</"+this._currentElement.type+">"}switch(this._tag){case"input":e.getReactMountReady().enqueue(s,this),o.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(u,this),o.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"select":o.autoFocus&&e.getReactMountReady().enqueue(y.focusDOMComponent,this);break;case"button":o.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 i=t[r];if(null!=i)if(U.hasOwnProperty(r))i&&o(this,r,i,e);else{r===V&&(i&&(i=this._previousStyleCopy=v({},t.style)),i=g.createMarkupForStyles(i,this));var a=null;null!=this._tag&&d(this._tag,t)?B.hasOwnProperty(r)||(a=C.createMarkupForCustomAttribute(r,i)):a=C.createMarkupForProperty(r,i),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+C.createMarkupForRoot()),n+=" "+C.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",i=t.dangerouslySetInnerHTML;if(null!=i)null!=i.__html&&(r=i.__html);else{var o=H[typeof t.children]?t.children:null,a=null!=o?null:t.children;if(null!=o)r=I(o);else if(null!=a){var s=this.mountChildren(a,e,n);r=s.join("")}}return Q[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var i=t.dangerouslySetInnerHTML;if(null!=i)null!=i.__html&&b.queueHTML(r,i.__html);else{var o=H[typeof t.children]?t.children:null,a=null!=o?null:t.children;if(null!=o)""!==o&&b.queueText(r,o);else if(null!=a)for(var s=this.mountChildren(a,e,n),u=0;u<s.length;u++)b.queueChild(r,s[u])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var o=t.props,a=this._currentElement.props;switch(this._tag){case"input":o=O.getHostProps(this,o),a=O.getHostProps(this,a);break;case"option":o=S.getHostProps(this,o),a=S.getHostProps(this,a);break;case"select":o=T.getHostProps(this,o),a=T.getHostProps(this,a);break;case"textarea":o=k.getHostProps(this,o),a=k.getHostProps(this,a)}switch(i(this,a),this._updateDOMProperties(o,a,e),this._updateDOMChildren(o,a,e,r),this._tag){case"input":O.updateWrapper(this);break;case"textarea":k.updateWrapper(this);break;case"select":e.getReactMountReady().enqueue(f,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===V){var s=this._previousStyleCopy;for(i in s)s.hasOwnProperty(i)&&(a=a||{},a[i]="");this._previousStyleCopy=null}else U.hasOwnProperty(r)?e[r]&&N(this,r):d(this._tag,e)?B.hasOwnProperty(r)||C.deleteValueForAttribute(D(this),r):(w.properties[r]||w.isCustomAttribute(r))&&C.deleteValueForProperty(D(this),r);for(r in t){var u=t[r],c=r===V?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&u!==c&&(null!=u||null!=c))if(r===V)if(u?u=this._previousStyleCopy=v({},u):this._previousStyleCopy=null,c){for(i in c)!c.hasOwnProperty(i)||u&&u.hasOwnProperty(i)||(a=a||{},a[i]="");for(i in u)u.hasOwnProperty(i)&&c[i]!==u[i]&&(a=a||{},a[i]=u[i])}else a=u;else if(U.hasOwnProperty(r))u?o(this,r,u,n):c&&N(this,r);else if(d(this._tag,t))B.hasOwnProperty(r)||C.setValueForAttribute(D(this),r,u);else if(w.properties[r]||w.isCustomAttribute(r)){ var l=D(this);null!=u?C.setValueForProperty(l,r,u):C.deleteValueForProperty(l,r)}}a&&g.setValueForStyles(D(this),a,this)},_updateDOMChildren:function(e,t,n,r){var i=H[typeof e.children]?e.children:null,o=H[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,u=null!=i?null:e.children,c=null!=o?null:t.children,l=null!=i||null!=a,f=null!=o||null!=s;null!=u&&null==c?this.updateChildren(null,n,r):l&&!f&&this.updateTextContent(""),null!=o?i!==o&&this.updateTextContent(""+o):null!=s?a!==s&&this.updateMarkup(""+s):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":m("66",this._tag)}this.unmountChildren(e),E.uncacheNode(this),j.deleteAllListeners(this),this._rootNodeID=0,this._domID=0,this._wrapperState=null},getPublicInstance:function(){return D(this)}},v(h.prototype,h.Mixin,M.Mixin),t.exports=h},{"./AutoFocusUtils":481,"./CSSPropertyOperations":484,"./DOMLazyTree":488,"./DOMNamespaces":489,"./DOMProperty":490,"./DOMPropertyOperations":491,"./EventPluginHub":495,"./EventPluginRegistry":496,"./ReactBrowserEventEmitter":504,"./ReactDOMComponentFlags":511,"./ReactDOMComponentTree":512,"./ReactDOMInput":517,"./ReactDOMOption":520,"./ReactDOMSelect":521,"./ReactDOMTextarea":524,"./ReactInstrumentation":541,"./ReactMultiChild":545,"./ReactServerRenderingTransaction":553,"./escapeTextContentForBrowser":581,"./isEventSupported":596,"./reactProdInvariant":599,"./validateDOMNesting":605,"fbjs/lib/emptyFunction":89,"fbjs/lib/invariant":97,"fbjs/lib/shallowEqual":103,"fbjs/lib/warning":104,"object-assign":606}],511:[function(e,t,n){"use strict";var r={hasCachedChildNodes:1};t.exports=r},{}],512:[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 i(e){for(var t;t=e._renderedComponent;)e=t;return e}function o(e,t){var n=i(e);n._hostNode=t,t[v]=n}function a(e){var t=e._hostNode;t&&(delete t[v],e._hostNode=null)}function s(e,t){if(!(e._flags&m.hasCachedChildNodes)){var n=e._renderedChildren,a=t.firstChild;e:for(var s in n)if(n.hasOwnProperty(s)){var u=n[s],c=i(u)._domID;if(0!==c){for(;null!==a;a=a.nextSibling)if(r(a,c)){o(u,a);continue e}f("32",c)}}e._flags|=m.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&&s(r,e);return n}function c(e){var t=u(e);return null!=t&&t._hostNode===e?t:null}function l(e){if(void 0===e._hostNode?f("33"):void 0,e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent?void 0:f("34"),e=e._hostParent;for(;t.length;e=t.pop())s(e,e._hostNode);return e._hostNode}var f=e("./reactProdInvariant"),p=e("./DOMProperty"),d=e("./ReactDOMComponentFlags"),h=(e("fbjs/lib/invariant"),p.ID_ATTRIBUTE_NAME),m=d,v="__reactInternalInstance$"+Math.random().toString(36).slice(2),y={getClosestInstanceFromNode:u,getInstanceFromNode:c,getNodeFromInstance:l,precacheChildNodes:s,precacheNode:o,uncacheNode:a};t.exports=y},{"./DOMProperty":490,"./ReactDOMComponentFlags":511,"./reactProdInvariant":599,"fbjs/lib/invariant":97}],513:[function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===i?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var i=(e("./validateDOMNesting"),9);t.exports=r},{"./validateDOMNesting":605}],514:[function(e,t,n){"use strict";var r=e("object-assign"),i=e("./DOMLazyTree"),o=e("./ReactDOMComponentTree"),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 s=" react-empty: "+this._domID+" ";if(e.useCreateElement){var u=n._ownerDocument,c=u.createComment(s);return o.precacheNode(this,c),i(c)}return e.renderToStaticMarkup?"":"<!--"+s+"-->"},receiveComponent:function(){},getHostNode:function(){return o.getNodeFromInstance(this)},unmountComponent:function(){o.uncacheNode(this)}}),t.exports=a},{"./DOMLazyTree":488,"./ReactDOMComponentTree":512,"object-assign":606}],515:[function(e,t,n){"use strict";var r={useCreateElement:!0,useFiber:!1};t.exports=r},{}],516:[function(e,t,n){"use strict";var r=e("./DOMChildrenOperations"),i=e("./ReactDOMComponentTree"),o={dangerouslyProcessChildrenUpdates:function(e,t){var n=i.getNodeFromInstance(e);r.processUpdates(n,t)}};t.exports=o},{"./DOMChildrenOperations":487,"./ReactDOMComponentTree":512}],517:[function(e,t,n){"use strict";function r(){this._rootNodeID&&f.updateWrapper(this)}function i(e){var t=this._currentElement.props,n=u.executeOnChange(t,e);l.asap(r,this);var i=t.name;if("radio"===t.type&&null!=i){for(var a=c.getNodeFromInstance(this),s=a;s.parentNode;)s=s.parentNode;for(var f=s.querySelectorAll("input[name="+JSON.stringify(""+i)+'][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?void 0:o("90"),l.asap(r,h)}}}return n}var o=e("./reactProdInvariant"),a=e("object-assign"),s=e("./DOMPropertyOperations"),u=e("./LinkedValueUtils"),c=e("./ReactDOMComponentTree"),l=e("./ReactUpdates"),f=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),{getHostProps:function(e,t){var n=u.getValue(t),r=u.getChecked(t),i=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});return i},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:i.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&s.setValueForProperty(c.getNodeFromInstance(e),"checked",n||!1);var r=c.getNodeFromInstance(e),i=u.getValue(t);if(null!=i){var o=""+i;o!==r.value&&(r.value=o)}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)}});t.exports=f},{"./DOMPropertyOperations":491,"./LinkedValueUtils":502,"./ReactDOMComponentTree":512,"./ReactUpdates":556,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"object-assign":606}],518:[function(e,t,n){"use strict";var r=e("./DOMProperty"),i=(e("react/lib/ReactComponentTreeHook"),e("fbjs/lib/warning"),new RegExp("^(aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$"),{onBeforeMountComponent:function(e,t){},onBeforeUpdateComponent:function(e,t){}});t.exports=i},{"./DOMProperty":490,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],519:[function(e,t,n){"use strict";function r(e,t){null!=t&&("input"!==t.type&&"textarea"!==t.type&&"select"!==t.type||null==t.props||null!==t.props.value||i||(i=!0))}var i=(e("react/lib/ReactComponentTreeHook"),e("fbjs/lib/warning"),!1),o={onBeforeMountComponent:function(e,t){r(e,t)},onBeforeUpdateComponent:function(e,t){r(e,t)}};t.exports=o},{"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],520:[function(e,t,n){"use strict";function r(e){var t="";return o.Children.forEach(e,function(e){null!=e&&("string"==typeof e||"number"==typeof e?t+=e:u||(u=!0))}),t}var i=e("object-assign"),o=e("react/lib/React"),a=e("./ReactDOMComponentTree"),s=e("./ReactDOMSelect"),u=(e("fbjs/lib/warning"),!1),c={mountWrapper:function(e,t,n){var i=null;if(null!=n){var o=n;"optgroup"===o._tag&&(o=o._hostParent),null!=o&&"select"===o._tag&&(i=s.getSelectValueContext(o))}var a=null;if(null!=i){var u;if(u=null!=t.value?t.value+"":r(t.children),a=!1,Array.isArray(i)){for(var c=0;c<i.length;c++)if(""+i[c]===u){a=!0;break}}else a=""+i===u}e._wrapperState={selected:a}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){var n=a.getNodeFromInstance(e);n.setAttribute("value",t.value)}},getHostProps:function(e,t){var n=i({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var o=r(t.children);return o&&(n.children=o),n}};t.exports=c},{"./ReactDOMComponentTree":512,"./ReactDOMSelect":521,"fbjs/lib/warning":104,"object-assign":606,"react/lib/React":610}],521:[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&&i(this,Boolean(e.multiple),t)}}function i(e,t,n){var r,i,o=u.getNodeFromInstance(e).options;if(t){for(r={},i=0;i<n.length;i++)r[""+n[i]]=!0;for(i=0;i<o.length;i++){var a=r.hasOwnProperty(o[i].value);o[i].selected!==a&&(o[i].selected=a)}}else{for(r=""+n,i=0;i<o.length;i++)if(o[i].value===r)return void(o[i].selected=!0);o.length&&(o[0].selected=!0)}}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),c.asap(r,this),n}var a=e("object-assign"),s=e("./LinkedValueUtils"),u=e("./ReactDOMComponentTree"),c=e("./ReactUpdates"),l=(e("fbjs/lib/warning"),!1),f={getHostProps:function(e,t){return a({},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:o.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=s.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,i(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?i(e,Boolean(t.multiple),t.defaultValue):i(e,Boolean(t.multiple),t.multiple?[]:""))}};t.exports=f},{"./LinkedValueUtils":502,"./ReactDOMComponentTree":512,"./ReactUpdates":556,"fbjs/lib/warning":104,"object-assign":606}],522:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function i(e){var t=document.selection,n=t.createRange(),r=n.text.length,i=n.duplicate();i.moveToElementText(e),i.setEndPoint("EndToStart",n);var o=i.text.length,a=o+r;return{start:o,end:a}}function o(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,i=t.anchorOffset,o=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(u){return null}var c=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=c?0:s.toString().length,f=s.cloneRange();f.selectNodeContents(e),f.setEnd(s.startContainer,s.startOffset);var p=r(f.startContainer,f.startOffset,f.endContainer,f.endOffset),d=p?0:f.toString().length,h=d+l,m=document.createRange();m.setStart(n,i),m.setEnd(o,a);var v=m.collapsed;return{start:v?h:d,end:v?d:h}}function a(e,t){var n,r,i=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),i.moveToElementText(e),i.moveStart("character",n),i.setEndPoint("EndToStart",i),i.moveEnd("character",r-n),i.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),r=e[l()].length,i=Math.min(t.start,r),o=void 0===t.end?i:Math.min(t.end,r);if(!n.extend&&i>o){var a=o;o=i,i=a}var s=c(e,i),u=c(e,o);if(s&&u){var f=document.createRange();f.setStart(s.node,s.offset),n.removeAllRanges(),i>o?(n.addRange(f),n.extend(u.node,u.offset)):(f.setEnd(u.node,u.offset),n.addRange(f))}}}var u=e("fbjs/lib/ExecutionEnvironment"),c=e("./getNodeForCharacterOffset"),l=e("./getTextContentAccessor"),f=u.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:f?i:o,setOffsets:f?a:s};t.exports=p},{"./getNodeForCharacterOffset":592,"./getTextContentAccessor":593,"fbjs/lib/ExecutionEnvironment":83}],523:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=e("object-assign"),o=e("./DOMChildrenOperations"),a=e("./DOMLazyTree"),s=e("./ReactDOMComponentTree"),u=e("./escapeTextContentForBrowser"),c=(e("fbjs/lib/invariant"),e("./validateDOMNesting"),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});i(c.prototype,{mountComponent:function(e,t,n,r){var i=n._idCounter++,o=" react-text: "+i+" ",c=" /react-text ";if(this._domID=i,this._hostParent=t,e.useCreateElement){var l=n._ownerDocument,f=l.createComment(o),p=l.createComment(c),d=a(l.createDocumentFragment());return a.queueChild(d,a(f)),this._stringText&&a.queueChild(d,a(l.createTextNode(this._stringText))),a.queueChild(d,a(p)),s.precacheNode(this,f),this._closingComment=p,d}var h=u(this._stringText);return e.renderToStaticMarkup?h:"<!--"+o+"-->"+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.getHostNode();o.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=s.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n?r("67",this._domID):void 0,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,s.uncacheNode(this)}}),t.exports=c},{"./DOMChildrenOperations":487,"./DOMLazyTree":488,"./ReactDOMComponentTree":512,"./escapeTextContentForBrowser":581,"./reactProdInvariant":599,"./validateDOMNesting":605,"fbjs/lib/invariant":97,"object-assign":606}],524:[function(e,t,n){"use strict";function r(){this._rootNodeID&&l.updateWrapper(this)}function i(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);return c.asap(r,this),n}var o=e("./reactProdInvariant"),a=e("object-assign"),s=e("./LinkedValueUtils"),u=e("./ReactDOMComponentTree"),c=e("./ReactUpdates"),l=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),{getHostProps:function(e,t){null!=t.dangerouslySetInnerHTML?o("91"):void 0;var n=a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return n},mountWrapper:function(e,t){var n=s.getValue(t),r=n;if(null==n){var a=t.defaultValue,u=t.children;null!=u&&(null!=a?o("92"):void 0,Array.isArray(u)&&(u.length<=1?void 0:o("93"),u=u[0]),a=""+u),null==a&&(a=""),r=a}e._wrapperState={initialValue:""+r,listeners:null,onChange:i.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=u.getNodeFromInstance(e),r=s.getValue(t);if(null!=r){var i=""+r;i!==n.value&&(n.value=i),null==t.defaultValue&&(n.defaultValue=i)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=u.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}});t.exports=l},{"./LinkedValueUtils":502,"./ReactDOMComponentTree":512,"./ReactUpdates":556,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"object-assign":606}],525:[function(e,t,n){"use strict";function r(e,t){"_hostNode"in e?void 0:u("33"),"_hostNode"in t?void 0:u("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var i=0,o=t;o;o=o._hostParent)i++;for(;n-i>0;)e=e._hostParent,n--;for(;i-n>0;)t=t._hostParent,i--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function i(e,t){"_hostNode"in e?void 0:u("35"),"_hostNode"in t?void 0:u("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function o(e){return"_hostNode"in e?void 0:u("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var i;for(i=r.length;i-- >0;)t(r[i],"captured",n);for(i=0;i<r.length;i++)t(r[i],"bubbled",n)}function s(e,t,n,i,o){for(var a=e&&t?r(e,t):null,s=[];e&&e!==a;)s.push(e),e=e._hostParent;for(var u=[];t&&t!==a;)u.push(t),t=t._hostParent;var c;for(c=0;c<s.length;c++)n(s[c],"bubbled",i);for(c=u.length;c-- >0;)n(u[c],"captured",o)}var u=e("./reactProdInvariant");e("fbjs/lib/invariant");t.exports={isAncestor:i,getLowestCommonAncestor:r,getParentInstance:o,traverseTwoPhase:a,traverseEnterLeave:s}},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],526:[function(e,t,n){"use strict";function r(e,t){null!=t&&"string"==typeof t.type&&(t.type.indexOf("-")>=0||t.props.is||o(e,t))}var i,o=(e("./DOMProperty"),e("./EventPluginRegistry"),e("react/lib/ReactComponentTreeHook"),e("fbjs/lib/warning"),function(e,t){var n=[];for(var r in t.props){var o=i(t.type,r,e);o||n.push(r)}n.map(function(e){return"`"+e+"`"}).join(", ");1===n.length||n.length>1}),a={onBeforeMountComponent:function(e,t){r(e,t)},onBeforeUpdateComponent:function(e,t){r(e,t)}};t.exports=a},{"./DOMProperty":490,"./EventPluginRegistry":496,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],527:[function(e,t,n){"use strict";function r(e,t,n,r,i,o,a,s){try{t.call(n,r,i,o,a,s)}catch(u){C[e]=!0}}function i(e,t,n,i,o,a){for(var s=0;s<w.length;s++){var u=w[s],c=u[e];c&&r(e,c,u,t,n,i,o,a)}}function o(){g.purgeUnmountedComponents(),y.clearHistory()}function a(e){return e.reduce(function(e,t){var n=g.getOwnerID(t),r=g.getParentID(t);return e[t]={displayName:g.getDisplayName(t),text:g.getText(t),updateCount:g.getUpdateCount(t),childIDs:g.getChildIDs(t),ownerID:n||r&&g.getOwnerID(r)||0,parentID:r},e},{})}function s(){var e=O,t=E,n=y.getHistory();if(0===P)return O=0,E=[],void o();if(t.length||n.length){var r=g.getRegisteredIDs();x.push({duration:_()-e,measurements:t||[],operations:n||[],treeSnapshot:a(r)})}o(),O=_(),E=[]}function u(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1]}function c(e,t){0!==P&&(M&&!A&&(A=!0),T=_(),k=0,S=e,M=t)}function l(e,t){0!==P&&(M===t||A||(A=!0),j&&E.push({timerType:t,instanceID:e,duration:_()-T-k}),T=0,k=0,S=null,M=null)}function f(){var e={startTime:T,nestedFlushStartTime:_(),debugID:S,timerType:M};R.push(e),T=0,k=0,S=null,M=null}function p(){var e=R.pop(),t=e.startTime,n=e.nestedFlushStartTime,r=e.debugID,i=e.timerType,o=_()-n;T=t,k+=o,S=r,M=i}function d(e){if(!j||!F)return!1;var t=g.getElement(e);if(null==t||"object"!=typeof t)return!1;var n="string"==typeof t.type;return!n}function h(e,t){if(d(e)){var n=e+"::"+t;I=_(),performance.mark(n)}}function m(e,t){if(d(e)){var n=e+"::"+t,r=g.getDisplayName(e)||"Unknown",i=_();if(i-I>.1){var o=r+" ["+t+"]";performance.measure(o,n)}performance.clearMarks(n),performance.clearMeasures(o)}}var v=e("./ReactInvalidSetStateWarningHook"),y=e("./ReactHostOperationHistoryHook"),g=e("react/lib/ReactComponentTreeHook"),b=e("fbjs/lib/ExecutionEnvironment"),_=e("fbjs/lib/performanceNow"),w=(e("fbjs/lib/warning"),[]),C={},j=!1,x=[],R=[],P=0,E=[],O=0,S=null,T=0,k=0,M=null,A=!1,I=0,F="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.clearMarks&&"function"==typeof performance.measure&&"function"==typeof performance.clearMeasures,N={addHook:function(e){w.push(e)},removeHook:function(e){for(var t=0;t<w.length;t++)w[t]===e&&(w.splice(t,1),t--)},isProfiling:function(){return j},beginProfiling:function(){j||(j=!0,x.length=0,s(),N.addHook(y))},endProfiling:function(){j&&(j=!1,s(),N.removeHook(y))},getFlushHistory:function(){return x},onBeginFlush:function(){P++,s(),f(),i("onBeginFlush")},onEndFlush:function(){s(),P--,p(),i("onEndFlush")},onBeginLifeCycleTimer:function(e,t){u(e),i("onBeginLifeCycleTimer",e,t),h(e,t),c(e,t)},onEndLifeCycleTimer:function(e,t){u(e),l(e,t),m(e,t),i("onEndLifeCycleTimer",e,t)},onBeginProcessingChildContext:function(){i("onBeginProcessingChildContext")},onEndProcessingChildContext:function(){i("onEndProcessingChildContext")},onHostOperation:function(e){u(e.instanceID),i("onHostOperation",e)},onSetState:function(){i("onSetState")},onSetChildren:function(e,t){u(e),t.forEach(u),i("onSetChildren",e,t)},onBeforeMountComponent:function(e,t,n){u(e),u(n,!0),i("onBeforeMountComponent",e,t,n),h(e,"mount")},onMountComponent:function(e){u(e),m(e,"mount"),i("onMountComponent",e)},onBeforeUpdateComponent:function(e,t){u(e),i("onBeforeUpdateComponent",e,t),h(e,"update")},onUpdateComponent:function(e){u(e),m(e,"update"),i("onUpdateComponent",e)},onBeforeUnmountComponent:function(e){u(e),i("onBeforeUnmountComponent",e),h(e,"unmount")},onUnmountComponent:function(e){u(e),m(e,"unmount"),i("onUnmountComponent",e)},onTestEvent:function(){i("onTestEvent")}};N.addDevtool=N.addHook,N.removeDevtool=N.removeHook,N.addHook(v),N.addHook(g);var D=b.canUseDOM&&window.location.href||"";/[?&]react_perf\b/.test(D)&&N.beginProfiling(),t.exports=N},{"./ReactHostOperationHistoryHook":537,"./ReactInvalidSetStateWarningHook":542,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/performanceNow":102,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],528:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var i=e("object-assign"),o=e("./ReactUpdates"),a=e("./Transaction"),s=e("fbjs/lib/emptyFunction"),u={initialize:s,close:function(){p.isBatchingUpdates=!1}},c={initialize:s,close:o.flushBatchedUpdates.bind(o)},l=[c,u];i(r.prototype,a,{getTransactionWrappers:function(){return l}});var f=new r,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,i,o){var a=p.isBatchingUpdates;return p.isBatchingUpdates=!0,a?e(t,n,r,i,o):f.perform(e,null,t,n,r,i,o)}};t.exports=p},{"./ReactUpdates":556,"./Transaction":574,"fbjs/lib/emptyFunction":89,"object-assign":606}],529:[function(e,t,n){"use strict";function r(){j||(j=!0,g.EventEmitter.injectReactEventListener(y),g.EventPluginHub.injectEventPluginOrder(s),g.EventPluginUtils.injectComponentTree(p),g.EventPluginUtils.injectTreeTraversal(h),g.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:C,EnterLeaveEventPlugin:u,ChangeEventPlugin:a,SelectEventPlugin:w,BeforeInputEventPlugin:o}),g.HostComponent.injectGenericComponentClass(f),g.HostComponent.injectTextComponentClass(m),g.DOMProperty.injectDOMPropertyConfig(i),g.DOMProperty.injectDOMPropertyConfig(c),g.DOMProperty.injectDOMPropertyConfig(_),g.EmptyComponent.injectEmptyComponentFactory(function(e){return new d(e)}),g.Updates.injectReconcileTransaction(b),g.Updates.injectBatchingStrategy(v),g.Component.injectEnvironment(l))}var i=e("./ARIADOMPropertyConfig"),o=e("./BeforeInputEventPlugin"),a=e("./ChangeEventPlugin"),s=e("./DefaultEventPluginOrder"),u=e("./EnterLeaveEventPlugin"),c=e("./HTMLDOMPropertyConfig"),l=e("./ReactComponentBrowserEnvironment"),f=e("./ReactDOMComponent"),p=e("./ReactDOMComponentTree"),d=e("./ReactDOMEmptyComponent"),h=e("./ReactDOMTreeTraversal"),m=e("./ReactDOMTextComponent"),v=e("./ReactDefaultBatchingStrategy"),y=e("./ReactEventListener"),g=e("./ReactInjection"),b=e("./ReactReconcileTransaction"),_=e("./SVGDOMPropertyConfig"),w=e("./SelectEventPlugin"),C=e("./SimpleEventPlugin"),j=!1;t.exports={inject:r}},{"./ARIADOMPropertyConfig":480,"./BeforeInputEventPlugin":482,"./ChangeEventPlugin":486,"./DefaultEventPluginOrder":493,"./EnterLeaveEventPlugin":494,"./HTMLDOMPropertyConfig":500,"./ReactComponentBrowserEnvironment":506,"./ReactDOMComponent":510,"./ReactDOMComponentTree":512,"./ReactDOMEmptyComponent":514,"./ReactDOMTextComponent":523,"./ReactDOMTreeTraversal":525,"./ReactDefaultBatchingStrategy":528,"./ReactEventListener":534,"./ReactInjection":538,"./ReactReconcileTransaction":550,"./SVGDOMPropertyConfig":558,"./SelectEventPlugin":559,"./SimpleEventPlugin":560}],530:[function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;t.exports=r},{}],531:[function(e,t,n){"use strict";var r,i={injectEmptyComponentFactory:function(e){r=e}},o={create:function(e){return r(e)}};o.injection=i,t.exports=o},{}],532:[function(e,t,n){"use strict";function r(e,t,n){try{t(n)}catch(r){null===i&&(i=r)}}var i=null,o={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(i){var e=i;throw i=null,e}}};t.exports=o},{}],533:[function(e,t,n){"use strict";function r(e){i.enqueueEvents(e),i.processEventQueue(!1)}var i=e("./EventPluginHub"),o={handleTopLevel:function(e,t,n,o){var a=i.extractEvents(e,t,n,o);r(a)}};t.exports=o},{"./EventPluginHub":495}],534:[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 i(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function o(e){var t=d(e.nativeEvent),n=f.getClosestInstanceFromNode(t),i=n;do e.ancestors.push(i),i=i&&r(i);while(i);for(var o=0;o<e.ancestors.length;o++)n=e.ancestors[o],m._handleTopLevel(e.topLevelType,n,e.nativeEvent,d(e.nativeEvent))}function a(e){var t=h(window);e(t)}var s=e("object-assign"),u=e("fbjs/lib/EventListener"),c=e("fbjs/lib/ExecutionEnvironment"),l=e("./PooledClass"),f=e("./ReactDOMComponentTree"),p=e("./ReactUpdates"),d=e("./getEventTarget"),h=e("fbjs/lib/getUnboundedScrollPosition");s(i.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(i,l.twoArgumentPooler);var m={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){m._handleTopLevel=e},setEnabled:function(e){m._enabled=!!e},isEnabled:function(){return m._enabled},trapBubbledEvent:function(e,t,n){return n?u.listen(n,t,m.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){return n?u.capture(n,t,m.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(m._enabled){var n=i.getPooled(e,t);try{p.batchedUpdates(o,n)}finally{i.release(n)}}}};t.exports=m},{"./PooledClass":503,"./ReactDOMComponentTree":512,"./ReactUpdates":556,"./getEventTarget":588,"fbjs/lib/EventListener":82,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/getUnboundedScrollPosition":94,"object-assign":606}],535:[function(e,t,n){"use strict";var r={logTopLevelRenders:!1};t.exports=r},{}],536:[function(e,t,n){"use strict";function r(e){return s?void 0:a("111",e.type),new s(e)}function i(e){return new u(e)}function o(e){return e instanceof u}var a=e("./reactProdInvariant"),s=(e("fbjs/lib/invariant"),null),u=null,c={injectGenericComponentClass:function(e){s=e},injectTextComponentClass:function(e){u=e}},l={createInternalComponent:r,createInstanceForText:i,isTextComponent:o,injection:c};t.exports=l},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],537:[function(e,t,n){"use strict";var r=[],i={onHostOperation:function(e){r.push(e)},clearHistory:function(){i._preventClearing||(r=[])},getHistory:function(){return r}};t.exports=i},{}],538:[function(e,t,n){"use strict";var r=e("./DOMProperty"),i=e("./EventPluginHub"),o=e("./EventPluginUtils"),a=e("./ReactComponentEnvironment"),s=e("./ReactEmptyComponent"),u=e("./ReactBrowserEventEmitter"),c=e("./ReactHostComponent"),l=e("./ReactUpdates"),f={Component:a.injection,DOMProperty:r.injection,EmptyComponent:s.injection,EventPluginHub:i.injection,EventPluginUtils:o.injection,EventEmitter:u.injection,HostComponent:c.injection,Updates:l.injection};t.exports=f},{"./DOMProperty":490,"./EventPluginHub":495,"./EventPluginUtils":497,"./ReactBrowserEventEmitter":504,"./ReactComponentEnvironment":507,"./ReactEmptyComponent":531,"./ReactHostComponent":536,"./ReactUpdates":556}],539:[function(e,t,n){"use strict";function r(e){return o(document.documentElement,e)}var i=e("./ReactDOMSelection"),o=e("fbjs/lib/containsNode"),a=e("fbjs/lib/focusNode"),s=e("fbjs/lib/getActiveElement"),u={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:u.hasSelectionCapabilities(e)?u.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,i=e.selectionRange;t!==n&&r(n)&&(u.hasSelectionCapabilities(n)&&u.setSelection(n,i),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=i.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 o=e.createTextRange();o.collapse(!0),o.moveStart("character",n),o.moveEnd("character",r-n),o.select()}else i.setOffsets(e,t)}};t.exports=u},{"./ReactDOMSelection":522,"fbjs/lib/containsNode":86,"fbjs/lib/focusNode":91,"fbjs/lib/getActiveElement":92}],540:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],541:[function(e,t,n){"use strict";var r=null;t.exports={debugTool:r}},{"./ReactDebugTool":527}],542:[function(e,t,n){"use strict";var r,i,o=(e("fbjs/lib/warning"),{onBeginProcessingChildContext:function(){r=!0},onEndProcessingChildContext:function(){r=!1},onSetState:function(){i()}});t.exports=o},{"fbjs/lib/warning":104}],543:[function(e,t,n){"use strict";var r=e("./adler32"),i=/\/?>/,o=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return o.test(e)?e:e.replace(i," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=r(e);return i===n}};t.exports=a},{"./adler32":577}],544:[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 i(e){return e?e.nodeType===I?e.documentElement:e.firstChild:null}function o(e){return e.getAttribute&&e.getAttribute(k)||""}function a(e,t,n,r,i){var o;if(w.logTopLevelRenders){var a=e._currentElement.props.child,s=a.type;o="React mount: "+("string"==typeof s?s:s.displayName||s.name),console.time(o)}var u=x.mountComponent(e,n,null,b(e,t),i,0);o&&console.timeEnd(o),e._renderedComponent._topLevelWrapper=e,U._mountImageIntoNode(u,t,e,r,n)}function s(e,t,n,r){var i=P.ReactReconcileTransaction.getPooled(!n&&_.useCreateElement);i.perform(a,null,e,t,i,n,r),P.ReactReconcileTransaction.release(i)}function u(e,t,n){for(x.unmountComponent(e,n),t.nodeType===I&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function c(e){var t=i(e);if(t){var n=g.getInstanceFromNode(t);return!(!n||!n._hostParent)}}function l(e){return!(!e||e.nodeType!==A&&e.nodeType!==I&&e.nodeType!==F)}function f(e){var t=i(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=e("./reactProdInvariant"),h=e("./DOMLazyTree"),m=e("./DOMProperty"),v=e("react/lib/React"),y=e("./ReactBrowserEventEmitter"),g=(e("react/lib/ReactCurrentOwner"),e("./ReactDOMComponentTree")),b=e("./ReactDOMContainerInfo"),_=e("./ReactDOMFeatureFlags"),w=e("./ReactFeatureFlags"),C=e("./ReactInstanceMap"),j=(e("./ReactInstrumentation"),e("./ReactMarkupChecksum")),x=e("./ReactReconciler"),R=e("./ReactUpdateQueue"),P=e("./ReactUpdates"),E=e("fbjs/lib/emptyObject"),O=e("./instantiateReactComponent"),S=(e("fbjs/lib/invariant"),e("./setInnerHTML")),T=e("./shouldUpdateReactComponent"),k=(e("fbjs/lib/warning"),m.ID_ATTRIBUTE_NAME),M=m.ROOT_ATTRIBUTE_NAME,A=1,I=9,F=11,N={},D=1,L=function(){this.rootID=D++};L.prototype.isReactComponent={},L.prototype.render=function(){return this.props.child},L.isReactTopLevelWrapper=!0;var U={TopLevelWrapper:L,_instancesByReactRootID:N,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r,i){return U.scrollMonitor(r,function(){R.enqueueElementInternal(e,t,n),i&&R.enqueueCallbackInternal(e,i)}),e},_renderNewRootComponent:function(e,t,n,r){l(t)?void 0:d("37"),y.ensureScrollValueMonitoring();var i=O(e,!1);P.batchedUpdates(s,i,t,n,r);var o=i._instance.rootID;return N[o]=i,i},renderSubtreeIntoContainer:function(e,t,n,r){return null!=e&&C.has(e)?void 0:d("38"),U._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){R.validateCallback(r,"ReactDOM.render"),v.isValidElement(t)?void 0: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,s=v.createElement(L,{child:t});if(e){var u=C.get(e);a=u._processChildContext(u._context)}else a=E;var l=p(n);if(l){var f=l._currentElement,h=f.props.child;if(T(h,t)){var m=l._renderedComponent.getPublicInstance(),y=r&&function(){r.call(m)};return U._updateRootComponent(l,s,a,n,y),m}U.unmountComponentAtNode(n)}var g=i(n),b=g&&!!o(g),_=c(n),w=b&&!l&&!_,j=U._renderNewRootComponent(s,n,w,a)._renderedComponent.getPublicInstance();return r&&r.call(j),j},render:function(e,t,n){return U._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){l(e)?void 0:d("40");var t=p(e);if(!t){c(e),1===e.nodeType&&e.hasAttribute(M);return!1}return delete N[t._instance.rootID],P.batchedUpdates(u,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,o,a){if(l(t)?void 0:d("41"),o){var s=i(t);if(j.canReuseMarkup(e,s))return void g.precacheNode(n,s);var u=s.getAttribute(j.CHECKSUM_ATTR_NAME);s.removeAttribute(j.CHECKSUM_ATTR_NAME);var c=s.outerHTML;s.setAttribute(j.CHECKSUM_ATTR_NAME,u);var f=e,p=r(f,c),m=" (client) "+f.substring(p-20,p+20)+"\n (server) "+c.substring(p-20,p+20);t.nodeType===I?d("42",m):void 0}if(t.nodeType===I?d("43"):void 0,a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);h.insertTreeBefore(t,e,null)}else S(t,e),g.precacheNode(n,t.firstChild)}};t.exports=U},{"./DOMLazyTree":488,"./DOMProperty":490,"./ReactBrowserEventEmitter":504,"./ReactDOMComponentTree":512,"./ReactDOMContainerInfo":513,"./ReactDOMFeatureFlags":515,"./ReactFeatureFlags":535,"./ReactInstanceMap":540,"./ReactInstrumentation":541,"./ReactMarkupChecksum":543,"./ReactReconciler":551,"./ReactUpdateQueue":555,"./ReactUpdates":556,"./instantiateReactComponent":595,"./reactProdInvariant":599,"./setInnerHTML":601,"./shouldUpdateReactComponent":603,"fbjs/lib/emptyObject":90,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/React":610,"react/lib/ReactCurrentOwner":615}],545:[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 i(e,t,n){return{type:"MOVE_EXISTING",content:null,fromIndex:e._mountIndex,fromNode:p.getHostNode(e),toIndex:n,afterNode:t}}function o(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 s(e){return{type:"TEXT_CONTENT",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function u(e,t){return t&&(e=e||[],e.push(t)),e}function c(e,t){f.processChildrenUpdates(e,t)}var l=e("./reactProdInvariant"),f=e("./ReactComponentEnvironment"),p=(e("./ReactInstanceMap"),e("./ReactInstrumentation"),e("react/lib/ReactCurrentOwner"),e("./ReactReconciler")),d=e("./ReactChildReconciler"),h=(e("fbjs/lib/emptyFunction"),e("./flattenChildren")),m=(e("fbjs/lib/invariant"),{Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return d.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,i,o){var a,s=0;return a=h(t,s),d.updateChildren(e,a,n,r,i,this,this._hostContainerInfo,o,s),a},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var i=[],o=0;for(var a in r)if(r.hasOwnProperty(a)){var s=r[a],u=0,c=p.mountComponent(s,t,this,this._hostContainerInfo,n,u);s._mountIndex=o++,i.push(c)}return i},updateTextContent:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");var r=[s(e)];c(this,r)},updateMarkup:function(e){var t=this._renderedChildren;d.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&l("118");var r=[a(e)];c(this,r)},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,i={},o=[],a=this._reconcilerUpdateChildren(r,e,o,i,t,n);if(a||r){var s,l=null,f=0,d=0,h=0,m=null;for(s in a)if(a.hasOwnProperty(s)){var v=r&&r[s],y=a[s];v===y?(l=u(l,this.moveChild(v,m,f,d)),d=Math.max(v._mountIndex,d),v._mountIndex=f):(v&&(d=Math.max(v._mountIndex,d)),l=u(l,this._mountChildAtIndex(y,o[h],m,f,t,n)),h++),f++,m=p.getHostNode(y)}for(s in i)i.hasOwnProperty(s)&&(l=u(l,this._unmountChild(r[s],i[s])));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 i(e,t,n)},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return o(e,t)},_mountChildAtIndex:function(e,t,n,r,i,o){return e._mountIndex=r,this.createChild(e,n,t)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}});t.exports=m},{"./ReactChildReconciler":505,"./ReactComponentEnvironment":507,"./ReactInstanceMap":540,"./ReactInstrumentation":541,"./ReactReconciler":551,"./flattenChildren":583,"./reactProdInvariant":599,"fbjs/lib/emptyFunction":89,"fbjs/lib/invariant":97,"react/lib/ReactCurrentOwner":615}],546:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=e("react/lib/React"),o=(e("fbjs/lib/invariant"),{HOST:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||e===!1?o.EMPTY:i.isValidElement(e)?"function"==typeof e.type?o.COMPOSITE:o.HOST:void r("26",e)}});t.exports=o},{"./reactProdInvariant":599,"fbjs/lib/invariant":97,"react/lib/React":610}],547:[function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)}var i=e("./reactProdInvariant"),o=(e("fbjs/lib/invariant"),{addComponentAsRefTo:function(e,t,n){r(n)?void 0:i("119"),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(n)?void 0:i("120");var o=n.getPublicInstance();o&&o.refs[t]===e.getPublicInstance()&&n.detachRef(t)}});t.exports=o},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],548:[function(e,t,n){"use strict";var r={};t.exports=r},{}],549:[function(e,t,n){"use strict";var r="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";t.exports=r},{}],550:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null),this.useCreateElement=e}var i=e("object-assign"),o=e("./CallbackQueue"),a=e("./PooledClass"),s=e("./ReactBrowserEventEmitter"),u=e("./ReactInputSelection"),c=(e("./ReactInstrumentation"),e("./Transaction")),l=e("./ReactUpdateQueue"),f={initialize:u.getSelectionInformation,close:u.restoreSelection},p={initialize:function(){var e=s.isEnabled();return s.setEnabled(!1),e},close:function(e){s.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[f,p,d],m={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(){o.release(this.reactMountReady),this.reactMountReady=null}};i(r.prototype,c,m),a.addPoolingTo(r),t.exports=r},{"./CallbackQueue":485,"./PooledClass":503,"./ReactBrowserEventEmitter":504,"./ReactInputSelection":539,"./ReactInstrumentation":541,"./ReactUpdateQueue":555,"./Transaction":574,"object-assign":606}],551:[function(e,t,n){"use strict";function r(){i.attachRefs(this,this._currentElement)}var i=e("./ReactRef"),o=(e("./ReactInstrumentation"),e("fbjs/lib/warning"),{mountComponent:function(e,t,n,i,o,a){var s=e.mountComponent(t,n,i,o,a);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),s},getHostNode:function(e){return e.getHostNode()},unmountComponent:function(e,t){i.detachRefs(e,e._currentElement),e.unmountComponent(t)},receiveComponent:function(e,t,n,o){var a=e._currentElement;if(t!==a||o!==e._context){var s=i.shouldUpdateRefs(a,t);s&&i.detachRefs(e,a),e.receiveComponent(t,n,o),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t,n){e._updateBatchNumber===n&&e.performUpdateIfNecessary(t)}});t.exports=o},{"./ReactInstrumentation":541,"./ReactRef":552,"fbjs/lib/warning":104}],552:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):o.addComponentAsRefTo(t,e,n)}function i(e,t,n){"function"==typeof e?e(null):o.removeComponentAsRefFrom(t,e,n)}var o=e("./ReactOwner"),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 i=null,o=null;return null!==t&&"object"==typeof t&&(i=t.ref,o=t._owner),n!==i||"string"==typeof i&&o!==r},a.detachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&i(n,e,t._owner)}},t.exports=a},{"./ReactOwner":547}],553:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1,this.updateQueue=new s(this)}var i=e("object-assign"),o=e("./PooledClass"),a=e("./Transaction"),s=(e("./ReactInstrumentation"),e("./ReactServerUpdateQueue")),u=[],c={enqueue:function(){}},l={getTransactionWrappers:function(){return u},getReactMountReady:function(){return c},getUpdateQueue:function(){return this.updateQueue},destructor:function(){},checkpoint:function(){},rollback:function(){}};i(r.prototype,a,l),o.addPoolingTo(r),t.exports=r},{"./PooledClass":503,"./ReactInstrumentation":541,"./ReactServerUpdateQueue":554,"./Transaction":574,"object-assign":606}],554:[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 i(e,t){}var o=e("./ReactUpdateQueue"),a=(e("fbjs/lib/warning"),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):i(e,"forceUpdate")},e.prototype.enqueueReplaceState=function(e,t){this.transaction.isInTransaction()?o.enqueueReplaceState(e,t):i(e,"replaceState")},e.prototype.enqueueSetState=function(e,t){this.transaction.isInTransaction()?o.enqueueSetState(e,t):i(e,"setState")},e}());t.exports=a},{"./ReactUpdateQueue":555,"fbjs/lib/warning":104}],555:[function(e,t,n){"use strict";function r(e){u.enqueueUpdate(e)}function i(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 o(e,t){var n=s.get(e);if(!n){return null}return n}var a=e("./reactProdInvariant"),s=(e("react/lib/ReactCurrentOwner"),e("./ReactInstanceMap")),u=(e("./ReactInstrumentation"),e("./ReactUpdates")),c=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),{isMounted:function(e){var t=s.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){c.validateCallback(t,n);var i=o(e);return i?(i._pendingCallbacks?i._pendingCallbacks.push(t):i._pendingCallbacks=[t],void r(i)):null},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e?a("122",t,i(e)):void 0}});t.exports=c},{"./ReactInstanceMap":540,"./ReactInstrumentation":541,"./ReactUpdates":556,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/ReactCurrentOwner":615}],556:[function(e,t,n){"use strict";function r(){E.ReactReconcileTransaction&&w?void 0:l("123")}function i(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=p.getPooled(),this.reconcileTransaction=E.ReactReconcileTransaction.getPooled(!0)}function o(e,t,n,i,o,a){return r(),w.batchedUpdates(e,t,n,i,o,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var t=e.dirtyComponentsLength;t!==y.length?l("124",t,y.length):void 0,y.sort(a),g++;for(var n=0;n<t;n++){var r=y[n],i=r._pendingCallbacks;r._pendingCallbacks=null;var o;if(h.logTopLevelRenders){var s=r;r._currentElement.type.isReactTopLevelWrapper&&(s=r._renderedComponent),o="React update: "+s.getName(),console.time(o)}if(m.performUpdateIfNecessary(r,e.reconcileTransaction,g),o&&console.timeEnd(o),i)for(var u=0;u<i.length;u++)e.callbackQueue.enqueue(i[u],r.getPublicInstance())}}function u(e){return r(),w.isBatchingUpdates?(y.push(e),void(null==e._updateBatchNumber&&(e._updateBatchNumber=g+1))):void w.batchedUpdates(u,e)}function c(e,t){w.isBatchingUpdates?void 0:l("125"),b.enqueue(e,t),_=!0}var l=e("./reactProdInvariant"),f=e("object-assign"),p=e("./CallbackQueue"),d=e("./PooledClass"),h=e("./ReactFeatureFlags"),m=e("./ReactReconciler"),v=e("./Transaction"),y=(e("fbjs/lib/invariant"),[]),g=0,b=p.getPooled(),_=!1,w=null,C={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),R()):y.length=0}},j={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[C,j];f(i.prototype,v,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,p.release(this.callbackQueue),this.callbackQueue=null,E.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return v.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),d.addPoolingTo(i);var R=function(){for(;y.length||_;){if(y.length){var e=i.getPooled();e.perform(s,null,e),i.release(e)}if(_){_=!1;var t=b;b=p.getPooled(),t.notifyAll(),p.release(t)}}},P={injectReconcileTransaction:function(e){e?void 0:l("126"),E.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:l("127"),"function"!=typeof e.batchedUpdates?l("128"):void 0,"boolean"!=typeof e.isBatchingUpdates?l("129"):void 0,w=e}},E={ReactReconcileTransaction:null,batchedUpdates:o,enqueueUpdate:u,flushBatchedUpdates:R,injection:P,asap:c};t.exports=E},{"./CallbackQueue":485,"./PooledClass":503,"./ReactFeatureFlags":535,"./ReactReconciler":551,"./Transaction":574,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"object-assign":606}],557:[function(e,t,n){"use strict";t.exports="15.4.2"},{}],558:[function(e,t,n){"use strict";var r={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},i={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"},o={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(i).forEach(function(e){o.Properties[e]=0,i[e]&&(o.DOMAttributeNames[e]=i[e])}),t.exports=o},{}],559:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function i(e,t){if(g||null==m||m!==l())return null;var n=r(m);if(!y||!p(y,n)){y=n;var i=c.getPooled(h.select,v,e,t);return i.type="select",i.target=m,o.accumulateTwoPhaseDispatches(i),i}return null}var o=e("./EventPropagators"),a=e("fbjs/lib/ExecutionEnvironment"),s=e("./ReactDOMComponentTree"),u=e("./ReactInputSelection"),c=e("./SyntheticEvent"),l=e("fbjs/lib/getActiveElement"),f=e("./isTextInputElement"),p=e("fbjs/lib/shallowEqual"),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"]}},m=null,v=null,y=null,g=!1,b=!1,_={eventTypes:h,extractEvents:function(e,t,n,r){if(!b)return null;var o=t?s.getNodeFromInstance(t):window;switch(e){case"topFocus":(f(o)||"true"===o.contentEditable)&&(m=o,v=t,y=null);break;case"topBlur":m=null,v=null,y=null;break;case"topMouseDown":g=!0;break;case"topContextMenu":case"topMouseUp":return g=!1,i(n,r);case"topSelectionChange":if(d)break;case"topKeyDown":case"topKeyUp":return i(n,r)}return null},didPutListener:function(e,t,n){"onSelect"===t&&(b=!0)}};t.exports=_},{"./EventPropagators":498,"./ReactDOMComponentTree":512,"./ReactInputSelection":539,"./SyntheticEvent":565,"./isTextInputElement":597,"fbjs/lib/ExecutionEnvironment":83,"fbjs/lib/getActiveElement":92,"fbjs/lib/shallowEqual":103}],560:[function(e,t,n){"use strict";function r(e){return"."+e._rootNodeID}function i(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var o=e("./reactProdInvariant"),a=e("fbjs/lib/EventListener"),s=e("./EventPropagators"),u=e("./ReactDOMComponentTree"),c=e("./SyntheticAnimationEvent"),l=e("./SyntheticClipboardEvent"),f=e("./SyntheticEvent"),p=e("./SyntheticFocusEvent"),d=e("./SyntheticKeyboardEvent"),h=e("./SyntheticMouseEvent"),m=e("./SyntheticDragEvent"),v=e("./SyntheticTouchEvent"),y=e("./SyntheticTransitionEvent"),g=e("./SyntheticUIEvent"),b=e("./SyntheticWheelEvent"),_=e("fbjs/lib/emptyFunction"),w=e("./getEventCharCode"),C=(e("fbjs/lib/invariant"),{}),j={};["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,i={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};C[e]=i,j[r]=i});var x={},R={eventTypes:C,extractEvents:function(e,t,n,r){var i=j[e];if(!i)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===w(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=m;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=v;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?void 0:o("86",e);var u=a.getPooled(i,t,n,r);return s.accumulateTwoPhaseDispatches(u),u},didPutListener:function(e,t,n){if("onClick"===t&&!i(e._tag)){var o=r(e),s=u.getNodeFromInstance(e);x[o]||(x[o]=a.listen(s,"click",_))}},willDeleteListener:function(e,t){if("onClick"===t&&!i(e._tag)){var n=r(e);x[n].remove(),delete x[n]}}};t.exports=R},{"./EventPropagators":498,"./ReactDOMComponentTree":512,"./SyntheticAnimationEvent":561,"./SyntheticClipboardEvent":562,"./SyntheticDragEvent":564,"./SyntheticEvent":565,"./SyntheticFocusEvent":566,"./SyntheticKeyboardEvent":568,"./SyntheticMouseEvent":569,"./SyntheticTouchEvent":570,"./SyntheticTransitionEvent":571,"./SyntheticUIEvent":572,"./SyntheticWheelEvent":573,"./getEventCharCode":585,"./reactProdInvariant":599,"fbjs/lib/EventListener":82,"fbjs/lib/emptyFunction":89,"fbjs/lib/invariant":97}],561:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o={animationName:null,elapsedTime:null,pseudoElement:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticEvent":565}],562:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};i.augmentClass(r,o),t.exports=r},{"./SyntheticEvent":565}],563:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o={data:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticEvent":565}],564:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticMouseEvent"),o={dataTransfer:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticMouseEvent":569}],565:[function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var i=this.constructor.Interface;for(var o in i)if(i.hasOwnProperty(o)){var s=i[o];s?this[o]=s(n):"target"===o?this.target=r:this[o]=n[o]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;return u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var i=e("object-assign"),o=e("./PooledClass"),a=e("fbjs/lib/emptyFunction"),s=(e("fbjs/lib/warning"),"function"==typeof Proxy,["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),u={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(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<s.length;n++)this[s[n]]=null}}),r.Interface=u,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;i(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.fourArgumentPooler)},o.addPoolingTo(r,o.fourArgumentPooler),t.exports=r},{"./PooledClass":503,"fbjs/lib/emptyFunction":89,"fbjs/lib/warning":104,"object-assign":606}],566:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticUIEvent"),o={relatedTarget:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticUIEvent":572}],567:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o={data:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticEvent":565}],568:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticUIEvent"),o=e("./getEventCharCode"),a=e("./getEventKey"),s=e("./getEventModifierState"),u={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?o(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?o(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};i.augmentClass(r,u),t.exports=r},{"./SyntheticUIEvent":572,"./getEventCharCode":585,"./getEventKey":586,"./getEventModifierState":587}],569:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),a=e("./getEventModifierState"),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){ return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};i.augmentClass(r,s),t.exports=r},{"./SyntheticUIEvent":572,"./ViewportMetrics":575,"./getEventModifierState":587}],570:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticUIEvent"),o=e("./getEventModifierState"),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:o};i.augmentClass(r,a),t.exports=r},{"./SyntheticUIEvent":572,"./getEventModifierState":587}],571:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o={propertyName:null,elapsedTime:null,pseudoElement:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticEvent":565}],572:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticEvent"),o=e("./getEventTarget"),a={view:function(e){if(e.view)return e.view;var t=o(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}};i.augmentClass(r,a),t.exports=r},{"./SyntheticEvent":565,"./getEventTarget":588}],573:[function(e,t,n){"use strict";function r(e,t,n,r){return i.call(this,e,t,n,r)}var i=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};i.augmentClass(r,o),t.exports=r},{"./SyntheticMouseEvent":569}],574:[function(e,t,n){"use strict";var r=e("./reactProdInvariant"),i=(e("fbjs/lib/invariant"),{}),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,i,o,a,s,u){this.isInTransaction()?r("27"):void 0;var c,l;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=e.call(t,n,i,o,a,s,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(f){}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,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){this.isInTransaction()?void 0:r("28");for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],s=this.wrapperInitData[n];try{o=!0,s!==i&&a.close&&a.close.call(this,s),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(u){}}}this.wrapperInitData.length=0}};t.exports=o},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],575:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],576:[function(e,t,n){"use strict";function r(e,t){return null==t?i("30"):void 0,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 i=e("./reactProdInvariant");e("fbjs/lib/invariant");t.exports=r},{"./reactProdInvariant":599,"fbjs/lib/invariant":97}],577:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0,o=e.length,a=o&-4;r<a;){for(var s=Math.min(r+4096,a);r<s;r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=i,n%=i}for(;r<o;r++)n+=t+=e.charCodeAt(r);return t%=i,n%=i,t|n<<16}var i=65521;t.exports=r},{}],578:[function(e,t,n){(function(n){"use strict";function r(e,t,n,r,u,c){for(var l in e)if(e.hasOwnProperty(l)){var f;try{"function"!=typeof e[l]?i("84",r||"React class",o[n],l):void 0,f=e[l](t,l,r,n,null,a)}catch(p){f=p}if(f instanceof Error&&!(f.message in s)){s[f.message]=!0}}}var i=e("./reactProdInvariant"),o=e("./ReactPropTypeLocationNames"),a=e("./ReactPropTypesSecret");e("fbjs/lib/invariant"),e("fbjs/lib/warning");"undefined"!=typeof n&&n.env,1;var s={};t.exports=r}).call(this,e("_process"))},{"./ReactPropTypeLocationNames":548,"./ReactPropTypesSecret":549,"./reactProdInvariant":599,_process:477,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],579:[function(e,t,n){"use strict";var r=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,i){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,i)})}:e};t.exports=r},{}],580:[function(e,t,n){"use strict";function r(e,t,n){var r=null==t||"boolean"==typeof t||""===t;if(r)return"";var i=isNaN(t);if(i||0===t||o.hasOwnProperty(e)&&o[e])return""+t;if("string"==typeof t){t=t.trim()}return t+"px"}var i=e("./CSSProperty"),o=(e("fbjs/lib/warning"),i.isUnitlessNumber);t.exports=r},{"./CSSProperty":483,"fbjs/lib/warning":104}],581:[function(e,t,n){"use strict";function r(e){var t=""+e,n=o.exec(t);if(!n)return t;var r,i="",a=0,s=0;for(a=n.index;a<t.length;a++){switch(t.charCodeAt(a)){case 34:r="&quot;";break;case 38:r="&amp;";break;case 39:r="&#x27;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}s!==a&&(i+=t.substring(s,a)),s=a+1,i+=r}return s!==a?i+t.substring(s,a):i}function i(e){return"boolean"==typeof e||"number"==typeof e?""+e:r(e)}var o=/["'&<>]/;t.exports=i},{}],582:[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);return t?(t=s(t),t?o.getNodeFromInstance(t):null):void("function"==typeof e.render?i("44"):i("45",Object.keys(e)))}var i=e("./reactProdInvariant"),o=(e("react/lib/ReactCurrentOwner"),e("./ReactDOMComponentTree")),a=e("./ReactInstanceMap"),s=e("./getHostComponentFromComposite");e("fbjs/lib/invariant"),e("fbjs/lib/warning");t.exports=r},{"./ReactDOMComponentTree":512,"./ReactInstanceMap":540,"./getHostComponentFromComposite":589,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/ReactCurrentOwner":615}],583:[function(e,t,n){(function(n){"use strict";function r(e,t,n,r){if(e&&"object"==typeof e){var i=e,o=void 0===i[n];o&&null!=t&&(i[n]=t)}}function i(e,t){if(null==e)return e;var n={};return o(e,r,n),n}var o=(e("./KeyEscapeUtils"),e("./traverseAllChildren"));e("fbjs/lib/warning");"undefined"!=typeof n&&n.env,1,t.exports=i}).call(this,e("_process"))},{"./KeyEscapeUtils":501,"./traverseAllChildren":604,_process:477,"fbjs/lib/warning":104,"react/lib/ReactComponentTreeHook":614}],584:[function(e,t,n){"use strict";function r(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}t.exports=r},{}],585:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],586:[function(e,t,n){"use strict";function r(e){if(e.key){var t=o[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=i(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var i=e("./getEventCharCode"),o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};t.exports=r},{"./getEventCharCode":585}],587:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=o[e];return!!r&&!!n[r]}function i(e){return r}var o={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=i},{}],588:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}t.exports=r},{}],589:[function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===i.COMPOSITE;)e=e._renderedComponent;return t===i.HOST?e._renderedComponent:t===i.EMPTY?null:void 0}var i=e("./ReactNodeTypes");t.exports=r},{"./ReactNodeTypes":546}],590:[function(e,t,n){"use strict";function r(e){var t=e&&(i&&e[i]||e[o]);if("function"==typeof t)return t}var i="function"==typeof Symbol&&Symbol.iterator,o="@@iterator";t.exports=r},{}],591:[function(e,t,n){"use strict";function r(){return i++}var i=1;t.exports=r},{}],592:[function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function i(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function o(e,t){for(var n=r(e),o=0,a=0;n;){if(3===n.nodeType){if(a=o+n.textContent.length,o<=t&&a>=t)return{node:n,offset:t-o};o=a}n=r(i(n))}}t.exports=o},{}],593:[function(e,t,n){"use strict";function r(){return!o&&i.canUseDOM&&(o="textContent"in document.documentElement?"textContent":"innerText"),o}var i=e("fbjs/lib/ExecutionEnvironment"),o=null;t.exports=r},{"fbjs/lib/ExecutionEnvironment":83}],594:[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 i(e){if(s[e])return s[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in u)return s[e]=t[n];return""}var o=e("fbjs/lib/ExecutionEnvironment"),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},u={};o.canUseDOM&&(u=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),t.exports=i},{"fbjs/lib/ExecutionEnvironment":83}],595:[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 i(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e,t){var n;if(null===e||e===!1)n=c.create(o);else if("object"==typeof e){var s=e,u=s.type;if("function"!=typeof u&&"string"!=typeof u){var p="";p+=r(s._owner),a("130",null==u?u:typeof u,p)}"string"==typeof s.type?n=l.createInternalComponent(s):i(s.type)?(n=new s.type(s),n.getHostNode||(n.getHostNode=n.getNativeNode)):n=new f(s)}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=e("./reactProdInvariant"),s=e("object-assign"),u=e("./ReactCompositeComponent"),c=e("./ReactEmptyComponent"),l=e("./ReactHostComponent"),f=(e("./getNextDebugID"),e("fbjs/lib/invariant"),e("fbjs/lib/warning"),function(e){this.construct(e)});s(f.prototype,u,{_instantiateReactComponent:o}),t.exports=o},{"./ReactCompositeComponent":508,"./ReactEmptyComponent":531,"./ReactHostComponent":536,"./getNextDebugID":591,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"object-assign":606}],596:[function(e,t,n){"use strict";function r(e,t){if(!o.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&&i&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var i,o=e("fbjs/lib/ExecutionEnvironment");o.canUseDOM&&(i=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{"fbjs/lib/ExecutionEnvironment":83}],597:[function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!i[e.type]:"textarea"===t}var i={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};t.exports=r},{}],598:[function(e,t,n){"use strict";function r(e){return'"'+i(e)+'"'}var i=e("./escapeTextContentForBrowser");t.exports=r},{"./escapeTextContentForBrowser":581}],599:[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 i=new Error(n);throw i.name="Invariant Violation",i.framesToPop=1,i}t.exports=r},{}],600:[function(e,t,n){"use strict";var r=e("./ReactMount");t.exports=r.renderSubtreeIntoContainer},{"./ReactMount":544}],601:[function(e,t,n){"use strict";var r,i=e("fbjs/lib/ExecutionEnvironment"),o=e("./DOMNamespaces"),a=/^[ \r\n\t\f]/,s=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,u=e("./createMicrosoftUnsafeLocalFunction"),c=u(function(e,t){if(e.namespaceURI!==o.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(i.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]&&s.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}t.exports=c},{"./DOMNamespaces":489,"./createMicrosoftUnsafeLocalFunction":579,"fbjs/lib/ExecutionEnvironment":83}],602:[function(e,t,n){"use strict";var r=e("fbjs/lib/ExecutionEnvironment"),i=e("./escapeTextContentForBrowser"),o=e("./setInnerHTML"),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){return 3===e.nodeType?void(e.nodeValue=t):void o(e,i(t))})),t.exports=a},{"./escapeTextContentForBrowser":581,"./setInnerHTML":601,"fbjs/lib/ExecutionEnvironment":83}],603:[function(e,t,n){"use strict";function r(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var i=typeof e,o=typeof t;return"string"===i||"number"===i?"string"===o||"number"===o:"object"===o&&e.type===t.type&&e.key===t.key}t.exports=r},{}],604:[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 i(e,t,n,o){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===s)return n(o,e,""===t?l+r(e,0):t),1;var d,h,m=0,v=""===t?l:t+f;if(Array.isArray(e))for(var y=0;y<e.length;y++)d=e[y],h=v+r(d,y),m+=i(d,h,n,o);else{var g=u(e);if(g){var b,_=g.call(e);if(g!==e.entries)for(var w=0;!(b=_.next()).done;)d=b.value,h=v+r(d,w++),m+=i(d,h,n,o);else for(;!(b=_.next()).done;){var C=b.value;C&&(d=C[1],h=v+c.escape(C[0])+f+r(d,0),m+=i(d,h,n,o))}}else if("object"===p){var j="",x=String(e);a("31","[object Object]"===x?"object with keys {"+Object.keys(e).join(", ")+"}":x,j)}}return m}function o(e,t,n){return null==e?0:i(e,"",t,n)}var a=e("./reactProdInvariant"),s=(e("react/lib/ReactCurrentOwner"),e("./ReactElementSymbol")),u=e("./getIteratorFn"),c=(e("fbjs/lib/invariant"),e("./KeyEscapeUtils")),l=(e("fbjs/lib/warning"),"."),f=":";t.exports=o},{"./KeyEscapeUtils":501,"./ReactElementSymbol":530,"./getIteratorFn":590,"./reactProdInvariant":599,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"react/lib/ReactCurrentOwner":615}],605:[function(e,t,n){"use strict";var r=(e("object-assign"),e("fbjs/lib/emptyFunction")),i=(e("fbjs/lib/warning"),r);t.exports=i},{"fbjs/lib/emptyFunction":89,"fbjs/lib/warning":104,"object-assign":606}],606:[function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function i(){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 i={};return"abcdefghijklmnopqrst".split("").forEach(function(e){i[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},i)).join("")}catch(o){return!1}}var o=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable;t.exports=i()?Object.assign:function(e,t){for(var n,i,u=r(e),c=1;c<arguments.length;c++){n=Object(arguments[c]);for(var l in n)a.call(n,l)&&(u[l]=n[l]);if(o){i=o(n);for(var f=0;f<i.length;f++)s.call(n,i[f])&&(u[i[f]]=n[i[f]])}}return u}},{}],607:[function(e,t,n){"use strict";function r(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")}function o(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=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}}(),u=function(e,t,n){for(var r=!0;r;){var i=e,o=t,a=n;r=!1,null===i&&(i=Function.prototype);var s=Object.getOwnPropertyDescriptor(i,o);if(void 0!==s){if("value"in s)return s.value;var u=s.get;if(void 0===u)return;return u.call(a)}var c=Object.getPrototypeOf(i);if(null===c)return;e=c,t=o,n=a,r=!0,s=c=void 0}},c=e("react"),l=r(c),f=e("nouislider-algolia-fork"),p=r(f),d=function(e){function t(){i(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),s(t,[{key:"componentDidMount",value:function(){this.props.disabled?this.sliderContainer.setAttribute("disabled",!0):this.sliderContainer.removeAttribute("disabled"),this.createSlider()}},{key:"componentDidUpdate",value:function(){this.props.disabled?this.sliderContainer.setAttribute("disabled",!0):this.sliderContainer.removeAttribute("disabled"),this.slider.destroy(),this.createSlider()}},{key:"componentWillUnmount",value:function(){this.slider.destroy()}},{key:"createSlider",value:function(){var e=this.slider=p["default"].create(this.sliderContainer,a({},this.props));this.props.onUpdate&&e.on("update",this.props.onUpdate),this.props.onChange&&e.on("change",this.props.onChange),this.props.onSlide&&e.on("slide",this.props.onSlide),this.props.onStart&&e.on("start",this.props.onStart),this.props.onEnd&&e.on("end",this.props.onEnd),this.props.onSet&&e.on("set",this.props.onSet)}},{key:"render",value:function(){var e=this;return l["default"].createElement("div",{ref:function(t){e.sliderContainer=t}})}}]),t}(l["default"].Component);d.propTypes={animate:l["default"].PropTypes.bool,behaviour:l["default"].PropTypes.string,connect:l["default"].PropTypes.oneOfType([l["default"].PropTypes.arrayOf(l["default"].PropTypes.bool),l["default"].PropTypes.bool]),cssPrefix:l["default"].PropTypes.string,direction:l["default"].PropTypes.oneOf(["ltr","rtl"]),disabled:l["default"].PropTypes.bool,limit:l["default"].PropTypes.number,margin:l["default"].PropTypes.number,onChange:l["default"].PropTypes.func,onEnd:l["default"].PropTypes.func,onSet:l["default"].PropTypes.func,onSlide:l["default"].PropTypes.func,onStart:l["default"].PropTypes.func,onUpdate:l["default"].PropTypes.func,orientation:l["default"].PropTypes.oneOf(["horizontal","vertical"]),pips:l["default"].PropTypes.object,range:l["default"].PropTypes.object.isRequired,start:l["default"].PropTypes.arrayOf(l["default"].PropTypes.number).isRequired,step:l["default"].PropTypes.number,tooltips:l["default"].PropTypes.oneOfType([l["default"].PropTypes.bool,l["default"].PropTypes.arrayOf(l["default"].PropTypes.shape({to:l["default"].PropTypes.func}))])},t.exports=d},{"nouislider-algolia-fork":474,react:633}],608:[function(e,t,n){arguments[4][501][0].apply(n,arguments)},{dup:501}],609:[function(e,t,n){arguments[4][503][0].apply(n,arguments)},{"./reactProdInvariant":630,dup:503,"fbjs/lib/invariant":97}],610:[function(e,t,n){"use strict";var r=e("object-assign"),i=e("./ReactChildren"),o=e("./ReactComponent"),a=e("./ReactPureComponent"),s=e("./ReactClass"),u=e("./ReactDOMFactories"),c=e("./ReactElement"),l=e("./ReactPropTypes"),f=e("./ReactVersion"),p=e("./onlyChild"),d=(e("fbjs/lib/warning"),c.createElement),h=c.createFactory,m=c.cloneElement,v=r,y={Children:{map:i.map,forEach:i.forEach,count:i.count,toArray:i.toArray,only:p},Component:o,PureComponent:a,createElement:d,cloneElement:m,isValidElement:c.isValidElement,PropTypes:l,createClass:s.createClass,createFactory:h,createMixin:function(e){return e},DOM:u,version:f,__spread:v};t.exports=y},{"./ReactChildren":611,"./ReactClass":612,"./ReactComponent":613,"./ReactDOMFactories":616,"./ReactElement":617,"./ReactElementValidator":619,"./ReactPropTypes":622,"./ReactPureComponent":624,"./ReactVersion":625,"./onlyChild":629,"fbjs/lib/warning":104,"object-assign":632}],611:[function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"$&/")}function i(e,t){this.func=e,this.context=t,this.count=0}function o(e,t,n){var r=e.func,i=e.context;r.call(i,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=i.getPooled(t,n);y(e,o,r),i.release(r)}function s(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function u(e,t,n){var i=e.result,o=e.keyPrefix,a=e.func,s=e.context,u=a.call(s,t,e.count++);Array.isArray(u)?c(u,i,n,v.thatReturnsArgument):null!=u&&(m.isValidElement(u)&&(u=m.cloneAndReplaceKey(u,o+(!u.key||t&&t.key===u.key?"":r(u.key)+"/")+n)),i.push(u))}function c(e,t,n,i,o){var a="";null!=n&&(a=r(n)+"/");var c=s.getPooled(t,a,i,o);y(e,u,c),s.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,v.thatReturnsArgument),t}var h=e("./PooledClass"),m=e("./ReactElement"),v=e("fbjs/lib/emptyFunction"),y=e("./traverseAllChildren"),g=h.twoArgumentPooler,b=h.fourArgumentPooler,_=/\/+/g;i.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(i,g),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(s,b);var w={forEach:a,map:l,mapIntoWithKeyPrefixInternal:c,count:p,toArray:d};t.exports=w},{"./PooledClass":609,"./ReactElement":617,"./traverseAllChildren":631,"fbjs/lib/emptyFunction":89}],612:[function(e,t,n){"use strict";function r(e){return e}function i(e,t){var n=_.hasOwnProperty(t)?_[t]:null;C.hasOwnProperty(t)&&("OVERRIDE_BASE"!==n?p("73",t):void 0),e&&("DEFINE_MANY"!==n&&"DEFINE_MANY_MERGED"!==n?p("74",t):void 0)}function o(e,t){if(t){"function"==typeof t?p("75"):void 0,m.isValidElement(t)?p("76"):void 0;var n=e.prototype,r=n.__reactAutoBindPairs;t.hasOwnProperty(g)&&w.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==g){var a=t[o],s=n.hasOwnProperty(o);if(i(s,o),w.hasOwnProperty(o))w[o](e,a);else{var l=_.hasOwnProperty(o),f="function"==typeof a,d=f&&!l&&!s&&t.autobind!==!1;if(d)r.push(o,a),n[o]=a;else if(s){var h=_[o];!l||"DEFINE_MANY_MERGED"!==h&&"DEFINE_MANY"!==h?p("77",h,o):void 0,"DEFINE_MANY_MERGED"===h?n[o]=u(n[o],a):"DEFINE_MANY"===h&&(n[o]=c(n[o],a))}else n[o]=a}}}else;}function a(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var i=n in w;i?p("78",n):void 0;var o=n in e;o?p("79",n):void 0,e[n]=r}}}function s(e,t){e&&t&&"object"==typeof e&&"object"==typeof t?void 0:p("80");for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]?p("81",n):void 0,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 i={};return s(i,n),s(i,r),i}}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],i=t[n+1];e[r]=l(e,i)}}var p=e("./reactProdInvariant"),d=e("object-assign"),h=e("./ReactComponent"),m=e("./ReactElement"),v=(e("./ReactPropTypeLocationNames"),e("./ReactNoopUpdateQueue")),y=e("fbjs/lib/emptyObject"),g=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),"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"},w={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=d({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=d({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(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(){}},C={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},j=function(){};d(j.prototype,h.prototype,C);var x={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||v,this.state=null;var i=this.getInitialState?this.getInitialState():null;"object"!=typeof i||Array.isArray(i)?p("82",t.displayName||"ReactCompositeComponent"):void 0,this.state=i});t.prototype=new j,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],b.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render?void 0:p("83");for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){b.push(e)}}};t.exports=x},{"./ReactComponent":613,"./ReactElement":617,"./ReactNoopUpdateQueue":620,"./ReactPropTypeLocationNames":621,"./reactProdInvariant":630,"fbjs/lib/emptyObject":90,"fbjs/lib/invariant":97,"fbjs/lib/warning":104,"object-assign":632}],613:[function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||o}var i=e("./reactProdInvariant"),o=e("./ReactNoopUpdateQueue"),a=(e("./canDefineProperty"),e("fbjs/lib/emptyObject"));e("fbjs/lib/invariant"),e("fbjs/lib/warning");r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e?i("85"):void 0,this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};t.exports=r},{"./ReactNoopUpdateQueue":620,"./canDefineProperty":626,"./reactProdInvariant":630,"fbjs/lib/emptyObject":90,"fbjs/lib/invariant":97,"fbjs/lib/warning":104}],614:[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 i=t.call(e);return r.test(i)}catch(o){return!1}}function i(e){var t=c(e);if(t){var n=t.childIDs;l(e),n.forEach(i)}}function o(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 s(e){var t,n=R.getDisplayName(e),r=R.getElement(e),i=R.getOwnerID(e);return i&&(t=R.getDisplayName(i)),o(n,r&&r._source,t)}var u,c,l,f,p,d,h,m=e("./reactProdInvariant"),v=e("./ReactCurrentOwner"),y=(e("fbjs/lib/invariant"),e("fbjs/lib/warning"),"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;u=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 _={},w={},C=function(e){return"."+e},j=function(e){return parseInt(e.substr(1),10)};u=function(e,t){var n=C(e);_[n]=t},c=function(e){var t=C(e);return _[t]},l=function(e){var t=C(e);delete _[t]},f=function(){return Object.keys(_).map(j)},p=function(e){var t=C(e);w[t]=!0},d=function(e){var t=C(e);delete w[t]},h=function(){return Object.keys(w).map(j)}}var x=[],R={onSetChildren:function(e,t){var n=c(e);n?void 0:m("144"),n.childIDs=t;for(var r=0;r<t.length;r++){var i=t[r],o=c(i);o?void 0:m("140"),null==o.childIDs&&"object"==typeof o.element&&null!=o.element?m("141"):void 0,o.isMounted?void 0:m("71"),null==o.parentID&&(o.parentID=e),o.parentID!==e?m("142",i,o.parentID,e):void 0}},onBeforeMountComponent:function(e,t,n){var r={element:t,parentID:n,text:null,childIDs:[],isMounted:!1,updateCount:0};u(e,r)},onBeforeUpdateComponent:function(e,t){var n=c(e);n&&n.isMounted&&(n.element=t)},onMountComponent:function(e){var t=c(e);t?void 0:m("144"),t.isMounted=!0;var n=0===t.parentID;n&&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;var n=0===t.parentID;n&&d(e)}x.push(e)},purgeUnmountedComponents:function(){if(!R._preventPurging){for(var e=0;e<x.length;e++){var t=x[e];i(t)}x.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+=o(n,e._source,r&&r.getName())}var i=v.current,s=i&&i._debugID;return t+=R.getStackAddendumByID(s)},getStackAddendumByID:function(e){for(var t="";e;)t+=s(e),e=R.getParentID(e);return t},getChildIDs:function(e){var t=c(e);return t?t.childIDs:[]},getDisplayName:function(e){var t=R.getElement(e);return t?a(t):null},getElement:function(e){var t=c(e);return t?t.element:null},getOwnerID:function(e){var t=R.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,r=null!=n?n._source:null;return r},getText:function(e){var t=R.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};t.exports=R},{"./ReactCurrentOwner":615,"./reactProdInvariant":630,"fbjs/lib/invariant":97,"fbjs/lib/warning":104 }],615:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],616:[function(e,t,n){"use strict";var r=e("./ReactElement"),i=r.createFactory,o={a:i("a"),abbr:i("abbr"),address:i("address"),area:i("area"),article:i("article"),aside:i("aside"),audio:i("audio"),b:i("b"),base:i("base"),bdi:i("bdi"),bdo:i("bdo"),big:i("big"),blockquote:i("blockquote"),body:i("body"),br:i("br"),button:i("button"),canvas:i("canvas"),caption:i("caption"),cite:i("cite"),code:i("code"),col:i("col"),colgroup:i("colgroup"),data:i("data"),datalist:i("datalist"),dd:i("dd"),del:i("del"),details:i("details"),dfn:i("dfn"),dialog:i("dialog"),div:i("div"),dl:i("dl"),dt:i("dt"),em:i("em"),embed:i("embed"),fieldset:i("fieldset"),figcaption:i("figcaption"),figure:i("figure"),footer:i("footer"),form:i("form"),h1:i("h1"),h2:i("h2"),h3:i("h3"),h4:i("h4"),h5:i("h5"),h6:i("h6"),head:i("head"),header:i("header"),hgroup:i("hgroup"),hr:i("hr"),html:i("html"),i:i("i"),iframe:i("iframe"),img:i("img"),input:i("input"),ins:i("ins"),kbd:i("kbd"),keygen:i("keygen"),label:i("label"),legend:i("legend"),li:i("li"),link:i("link"),main:i("main"),map:i("map"),mark:i("mark"),menu:i("menu"),menuitem:i("menuitem"),meta:i("meta"),meter:i("meter"),nav:i("nav"),noscript:i("noscript"),object:i("object"),ol:i("ol"),optgroup:i("optgroup"),option:i("option"),output:i("output"),p:i("p"),param:i("param"),picture:i("picture"),pre:i("pre"),progress:i("progress"),q:i("q"),rp:i("rp"),rt:i("rt"),ruby:i("ruby"),s:i("s"),samp:i("samp"),script:i("script"),section:i("section"),select:i("select"),small:i("small"),source:i("source"),span:i("span"),strong:i("strong"),style:i("style"),sub:i("sub"),summary:i("summary"),sup:i("sup"),table:i("table"),tbody:i("tbody"),td:i("td"),textarea:i("textarea"),tfoot:i("tfoot"),th:i("th"),thead:i("thead"),time:i("time"),title:i("title"),tr:i("tr"),track:i("track"),u:i("u"),ul:i("ul"),"var":i("var"),video:i("video"),wbr:i("wbr"),circle:i("circle"),clipPath:i("clipPath"),defs:i("defs"),ellipse:i("ellipse"),g:i("g"),image:i("image"),line:i("line"),linearGradient:i("linearGradient"),mask:i("mask"),path:i("path"),pattern:i("pattern"),polygon:i("polygon"),polyline:i("polyline"),radialGradient:i("radialGradient"),rect:i("rect"),stop:i("stop"),svg:i("svg"),text:i("text"),tspan:i("tspan")};t.exports=o},{"./ReactElement":617,"./ReactElementValidator":619}],617:[function(e,t,n){"use strict";function r(e){return void 0!==e.ref}function i(e){return void 0!==e.key}var o=e("object-assign"),a=e("./ReactCurrentOwner"),s=(e("fbjs/lib/warning"),e("./canDefineProperty"),Object.prototype.hasOwnProperty),u=e("./ReactElementSymbol"),c={key:!0,ref:!0,__self:!0,__source:!0},l=function(e,t,n,r,i,o,a){var s={$$typeof:u,type:e,key:t,ref:n,props:a,_owner:o};return s};l.createElement=function(e,t,n){var o,u={},f=null,p=null,d=null,h=null;if(null!=t){r(t)&&(p=t.ref),i(t)&&(f=""+t.key),d=void 0===t.__self?null:t.__self,h=void 0===t.__source?null:t.__source;for(o in t)s.call(t,o)&&!c.hasOwnProperty(o)&&(u[o]=t[o])}var m=arguments.length-2;if(1===m)u.children=n;else if(m>1){for(var v=Array(m),y=0;y<m;y++)v[y]=arguments[y+2];u.children=v}if(e&&e.defaultProps){var g=e.defaultProps;for(o in g)void 0===u[o]&&(u[o]=g[o])}return l(e,f,p,d,h,a.current,u)},l.createFactory=function(e){var t=l.createElement.bind(null,e);return t.type=e,t},l.cloneAndReplaceKey=function(e,t){var n=l(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},l.cloneElement=function(e,t,n){var u,f=o({},e.props),p=e.key,d=e.ref,h=e._self,m=e._source,v=e._owner;if(null!=t){r(t)&&(d=t.ref,v=a.current),i(t)&&(p=""+t.key);var y;e.type&&e.type.defaultProps&&(y=e.type.defaultProps);for(u in t)s.call(t,u)&&!c.hasOwnProperty(u)&&(void 0===t[u]&&void 0!==y?f[u]=y[u]:f[u]=t[u])}var g=arguments.length-2;if(1===g)f.children=n;else if(g>1){for(var b=Array(g),_=0;_<g;_++)b[_]=arguments[_+2];f.children=b}return l(e.type,p,d,h,m,v,f)},l.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===u},t.exports=l},{"./ReactCurrentOwner":615,"./ReactElementSymbol":618,"./canDefineProperty":626,"fbjs/lib/warning":104,"object-assign":632}],618:[function(e,t,n){arguments[4][530][0].apply(n,arguments)},{dup:530}],619:[function(e,t,n){"use strict";function r(){if(u.current){var e=u.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function i(e){var t=r();if(!t){var n="string"==typeof e?e:e.displayName||e.name;n&&(t=" Check the top-level render call using <"+n+">.")}return t}function o(e,t){if(e._store&&!e._store.validated&&null==e.key){e._store.validated=!0;var n=p.uniqueKey||(p.uniqueKey={}),r=i(t);if(!n[r]){n[r]=!0;var o="";e&&e._owner&&e._owner!==u.current&&(o=" It was passed a child from "+e._owner.getName()+".")}}}function a(e,t){if("object"==typeof e)if(Array.isArray(e))for(var n=0;n<e.length;n++){var r=e[n];c.isValidElement(r)&&o(r,t)}else if(c.isValidElement(e))e._store&&(e._store.validated=!0);else if(e){var i=f(e);if(i&&i!==e.entries)for(var a,s=i.call(e);!(a=s.next()).done;)c.isValidElement(a.value)&&o(a.value,t)}}function s(e){var t=e.type;if("function"==typeof t){var n=t.displayName||t.name;t.propTypes&&l(t.propTypes,e.props,"prop",n,e,null),"function"==typeof t.getDefaultProps}}var u=e("./ReactCurrentOwner"),c=(e("./ReactComponentTreeHook"),e("./ReactElement")),l=e("./checkReactTypeSpec"),f=(e("./canDefineProperty"),e("./getIteratorFn")),p=(e("fbjs/lib/warning"),{}),d={createElement:function(e,t,n){var i="string"==typeof e||"function"==typeof e;if(!i&&"function"!=typeof e&&"string"!=typeof e){var o="";(void 0===e||"object"==typeof e&&null!==e&&0===Object.keys(e).length)&&(o+=" You likely forgot to export your component from the file it's defined in."),o+=r()}var u=c.createElement.apply(this,arguments);if(null==u)return u;if(i)for(var l=2;l<arguments.length;l++)a(arguments[l],e);return s(u),u},createFactory:function(e){var t=d.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=c.cloneElement.apply(this,arguments),i=2;i<arguments.length;i++)a(arguments[i],r.type);return s(r),r}};t.exports=d},{"./ReactComponentTreeHook":614,"./ReactCurrentOwner":615,"./ReactElement":617,"./canDefineProperty":626,"./checkReactTypeSpec":627,"./getIteratorFn":628,"fbjs/lib/warning":104}],620:[function(e,t,n){"use strict";function r(e,t){}var i=(e("fbjs/lib/warning"),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}});t.exports=i},{"fbjs/lib/warning":104}],621:[function(e,t,n){arguments[4][548][0].apply(n,arguments)},{dup:548}],622:[function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function i(e){this.message=e,this.stack=""}function o(e){function t(t,n,r,o,a,s,u){o=o||P,s=s||r;if(null==n[r]){var c=C[a];return t?new i(null===n[r]?"The "+c+" `"+s+"` is marked as required "+("in `"+o+"`, but its value is `null`."):"The "+c+" `"+s+"` is marked as required in "+("`"+o+"`, but its value is `undefined`.")):null}return e(n,r,o,a,s)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function a(e){function t(t,n,r,o,a,s){var u=t[n],c=g(u);if(c!==e){var l=C[o],f=b(u);return new i("Invalid "+l+" `"+a+"` of type "+("`"+f+"` supplied to `"+r+"`, expected ")+("`"+e+"`."))}return null}return o(t)}function s(){return o(x.thatReturns(null))}function u(e){function t(t,n,r,o,a){if("function"!=typeof e)return new i("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var s=t[n];if(!Array.isArray(s)){var u=C[o],c=g(s);return new i("Invalid "+u+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected an array."))}for(var l=0;l<s.length;l++){var f=e(s,l,r,o,a+"["+l+"]",j);if(f instanceof Error)return f}return null}return o(t)}function c(){function e(e,t,n,r,o){var a=e[t];if(!w.isValidElement(a)){var s=C[r],u=g(a);return new i("Invalid "+s+" `"+o+"` of type "+("`"+u+"` supplied to `"+n+"`, expected a single ReactElement."))}return null}return o(e)}function l(e){function t(t,n,r,o,a){if(!(t[n]instanceof e)){var s=C[o],u=e.name||P,c=_(t[n]);return new i("Invalid "+s+" `"+a+"` of type "+("`"+c+"` supplied to `"+r+"`, expected ")+("instance of `"+u+"`."))}return null}return o(t)}function f(e){function t(t,n,o,a,s){for(var u=t[n],c=0;c<e.length;c++)if(r(u,e[c]))return null;var l=C[a],f=JSON.stringify(e);return new i("Invalid "+l+" `"+s+"` of value `"+u+"` "+("supplied to `"+o+"`, expected one of "+f+"."))}return Array.isArray(e)?o(t):x.thatReturnsNull}function p(e){function t(t,n,r,o,a){if("function"!=typeof e)return new i("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var s=t[n],u=g(s);if("object"!==u){var c=C[o];return new i("Invalid "+c+" `"+a+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an object."))}for(var l in s)if(s.hasOwnProperty(l)){var f=e(s,l,r,o,a+"."+l,j);if(f instanceof Error)return f}return null}return o(t)}function d(e){function t(t,n,r,o,a){for(var s=0;s<e.length;s++){var u=e[s];if(null==u(t,n,r,o,a,j))return null}var c=C[o];return new i("Invalid "+c+" `"+a+"` supplied to "+("`"+r+"`."))}return Array.isArray(e)?o(t):x.thatReturnsNull}function h(){function e(e,t,n,r,o){if(!v(e[t])){var a=C[r];return new i("Invalid "+a+" `"+o+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return o(e)}function m(e){function t(t,n,r,o,a){var s=t[n],u=g(s);if("object"!==u){var c=C[o];return new i("Invalid "+c+" `"+a+"` of type `"+u+"` "+("supplied to `"+r+"`, expected `object`."))}for(var l in e){var f=e[l];if(f){var p=f(s,l,r,o,a+"."+l,j);if(p)return p}}return null}return o(t)}function v(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(v);if(null===e||w.isValidElement(e))return!0;var t=R(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!v(n.value))return!1}else for(;!(n=r.next()).done;){var i=n.value;if(i&&!v(i[1]))return!1}return!0;default:return!1}}function y(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function g(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":y(t,e)?"symbol":t}function b(e){var t=g(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function _(e){return e.constructor&&e.constructor.name?e.constructor.name:P}var w=e("./ReactElement"),C=e("./ReactPropTypeLocationNames"),j=e("./ReactPropTypesSecret"),x=e("fbjs/lib/emptyFunction"),R=e("./getIteratorFn"),P=(e("fbjs/lib/warning"),"<<anonymous>>"),E={array:a("array"),bool:a("boolean"),func:a("function"),number:a("number"),object:a("object"),string:a("string"),symbol:a("symbol"),any:s(),arrayOf:u,element:c(),instanceOf:l,node:h(),objectOf:p,oneOf:f,oneOfType:d,shape:m};i.prototype=Error.prototype,t.exports=E},{"./ReactElement":617,"./ReactPropTypeLocationNames":621,"./ReactPropTypesSecret":623,"./getIteratorFn":628,"fbjs/lib/emptyFunction":89,"fbjs/lib/warning":104}],623:[function(e,t,n){arguments[4][549][0].apply(n,arguments)},{dup:549}],624:[function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=u,this.updater=n||s}function i(){}var o=e("object-assign"),a=e("./ReactComponent"),s=e("./ReactNoopUpdateQueue"),u=e("fbjs/lib/emptyObject");i.prototype=a.prototype,r.prototype=new i,r.prototype.constructor=r,o(r.prototype,a.prototype),r.prototype.isPureReactComponent=!0,t.exports=r},{"./ReactComponent":613,"./ReactNoopUpdateQueue":620,"fbjs/lib/emptyObject":90,"object-assign":632}],625:[function(e,t,n){arguments[4][557][0].apply(n,arguments)},{dup:557}],626:[function(e,t,n){"use strict";var r=!1;t.exports=r},{}],627:[function(e,t,n){(function(n){"use strict";function r(e,t,n,r,u,c){for(var l in e)if(e.hasOwnProperty(l)){var f;try{"function"!=typeof e[l]?i("84",r||"React class",o[n],l):void 0,f=e[l](t,l,r,n,null,a)}catch(p){f=p}if(f instanceof Error&&!(f.message in s)){s[f.message]=!0}}}var i=e("./reactProdInvariant"),o=e("./ReactPropTypeLocationNames"),a=e("./ReactPropTypesSecret");e("fbjs/lib/invariant"),e("fbjs/lib/warning");"undefined"!=typeof n&&n.env,1;var s={};t.exports=r}).call(this,e("_process"))},{"./ReactComponentTreeHook":614,"./ReactPropTypeLocationNames":621,"./ReactPropTypesSecret":623,"./reactProdInvariant":630,_process:477,"fbjs/lib/invariant":97,"fbjs/lib/warning":104}],628:[function(e,t,n){arguments[4][590][0].apply(n,arguments)},{dup:590}],629:[function(e,t,n){"use strict";function r(e){return o.isValidElement(e)?void 0:i("143"),e}var i=e("./reactProdInvariant"),o=e("./ReactElement");e("fbjs/lib/invariant");t.exports=r},{"./ReactElement":617,"./reactProdInvariant":630,"fbjs/lib/invariant":97}],630:[function(e,t,n){arguments[4][599][0].apply(n,arguments)},{dup:599}],631:[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 i(e,t,n,o){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===s)return n(o,e,""===t?l+r(e,0):t),1;var d,h,m=0,v=""===t?l:t+f;if(Array.isArray(e))for(var y=0;y<e.length;y++)d=e[y],h=v+r(d,y),m+=i(d,h,n,o);else{var g=u(e);if(g){var b,_=g.call(e);if(g!==e.entries)for(var w=0;!(b=_.next()).done;)d=b.value,h=v+r(d,w++),m+=i(d,h,n,o);else for(;!(b=_.next()).done;){var C=b.value;C&&(d=C[1],h=v+c.escape(C[0])+f+r(d,0),m+=i(d,h,n,o))}}else if("object"===p){var j="",x=String(e);a("31","[object Object]"===x?"object with keys {"+Object.keys(e).join(", ")+"}":x,j)}}return m}function o(e,t,n){return null==e?0:i(e,"",t,n)}var a=e("./reactProdInvariant"),s=(e("./ReactCurrentOwner"),e("./ReactElementSymbol")),u=e("./getIteratorFn"),c=(e("fbjs/lib/invariant"),e("./KeyEscapeUtils")),l=(e("fbjs/lib/warning"),"."),f=":";t.exports=o},{"./KeyEscapeUtils":608,"./ReactCurrentOwner":615,"./ReactElementSymbol":618,"./getIteratorFn":628,"./reactProdInvariant":630,"fbjs/lib/invariant":97,"fbjs/lib/warning":104}],632:[function(e,t,n){arguments[4][606][0].apply(n,arguments)},{dup:606}],633:[function(e,t,n){"use strict";t.exports=e("./lib/React")},{"./lib/React":610}],634:[function(e,t,n){"use strict";function r(e){var t=function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return new(i.apply(e,[null].concat(n)))};return t.__proto__=e,t.prototype=e.prototype,t}var i=Function.prototype.bind;t.exports=r},{}],635:[function(e,t,n){arguments[4][110][0].apply(n,arguments)},{dup:110}],636:[function(e,t,n){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],637:[function(e,t,n){(function(t,r){function i(e,t){var r={seen:[],stylize:a};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),m(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),u(r,e,r.depth)}function o(e,t){var n=i.styles[t];return n?"["+i.colors[n][0]+"m"+e+"["+i.colors[n][1]+"m":e}function a(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function u(e,t,r){if(e.customInspect&&t&&P(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return b(i)||(i=u(e,i,r)),i}var o=c(e,t);if(o)return o;var a=Object.keys(t),m=s(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),R(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(t);if(0===a.length){if(P(t)){var v=t.name?": "+t.name:"";return e.stylize("[Function"+v+"]","special")}if(C(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(x(t))return e.stylize(Date.prototype.toString.call(t),"date");if(R(t))return l(t)}var y="",g=!1,_=["{","}"];if(h(t)&&(g=!0,_=["[","]"]),P(t)){var w=t.name?": "+t.name:"";y=" [Function"+w+"]"}if(C(t)&&(y=" "+RegExp.prototype.toString.call(t)),x(t)&&(y=" "+Date.prototype.toUTCString.call(t)),R(t)&&(y=" "+l(t)),0===a.length&&(!g||0==t.length))return _[0]+y+_[1];if(r<0)return C(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var j;return j=g?f(e,t,r,m,a):a.map(function(n){return p(e,t,r,m,n,g)}),e.seen.pop(),d(j,y,_)}function c(e,t){if(w(t))return e.stylize("undefined","undefined");if(b(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return g(t)?e.stylize(""+t,"number"):m(t)?e.stylize(""+t,"boolean"):v(t)?e.stylize("null","null"):void 0}function l(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,n,r,i){for(var o=[],a=0,s=t.length;a<s;++a)k(t,String(a))?o.push(p(e,t,n,r,String(a),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(p(e,t,n,r,i,!0))}),o}function p(e,t,n,r,i,o){var a,s,c;if(c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]},c.get?s=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(s=e.stylize("[Setter]","special")),k(r,i)||(a="["+i+"]"),s||(e.seen.indexOf(c.value)<0?(s=v(n)?u(e,c.value,null):u(e,c.value,n-1),s.indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n"))):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e,t,n){var r=0,i=e.reduce(function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return i>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function h(e){return Array.isArray(e)}function m(e){return"boolean"==typeof e}function v(e){return null===e}function y(e){return null==e}function g(e){return"number"==typeof e}function b(e){return"string"==typeof e}function _(e){return"symbol"==typeof e}function w(e){return void 0===e}function C(e){return j(e)&&"[object RegExp]"===O(e)}function j(e){return"object"==typeof e&&null!==e}function x(e){return j(e)&&"[object Date]"===O(e)}function R(e){return j(e)&&("[object Error]"===O(e)||e instanceof Error)}function P(e){return"function"==typeof e}function E(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function O(e){return Object.prototype.toString.call(e)}function S(e){return e<10?"0"+e.toString(10):e.toString(10)}function T(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),F[e.getMonth()],t].join(" ")}function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var M=/%[sdj%]/g;n.format=function(e){if(!b(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(i(arguments[n]));return t.join(" ")}for(var n=1,r=arguments,o=r.length,a=String(e).replace(M,function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(r[n++]);case"%d":return Number(r[n++]);case"%j":try{return JSON.stringify(r[n++])}catch(t){return"[Circular]"}default:return e}}),s=r[n];n<o;s=r[++n])a+=v(s)||!j(s)?" "+s:" "+i(s);return a},n.deprecate=function(e,i){function o(){if(!a){if(t.throwDeprecation)throw new Error(i);t.traceDeprecation?console.trace(i):console.error(i),a=!0}return e.apply(this,arguments)}if(w(r.process))return function(){return n.deprecate(e,i).apply(this,arguments)};if(t.noDeprecation===!0)return e;var a=!1;return o};var A,I={};n.debuglog=function(e){if(w(A)&&(A=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!I[e])if(new RegExp("\\b"+e+"\\b","i").test(A)){var r=t.pid;I[e]=function(){var t=n.format.apply(n,arguments);console.error("%s %d: %s",e,r,t)}}else I[e]=function(){};return I[e]},n.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},n.isArray=h,n.isBoolean=m,n.isNull=v,n.isNullOrUndefined=y,n.isNumber=g,n.isString=b,n.isSymbol=_,n.isUndefined=w,n.isRegExp=C,n.isObject=j,n.isDate=x,n.isError=R,n.isFunction=P,n.isPrimitive=E,n.isBuffer=e("./support/isBuffer");var F=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",T(),n.format.apply(n,arguments))},n.inherits=e("inherits"),n._extend=function(e,t){if(!t||!j(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":636,_process:477,inherits:635}],638:[function(e,t,n){"use strict";function r(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")}function o(e){return e>=1&&e<=20||"should be between 1 and 20"}function a(){return null!==window.location.pathname.match(/\/search$/)}Object.defineProperty(n,"__esModule",{value:!0});var s=e("./jQuery.js"),u=r(s),c=e("fargs"),l=r(c),f=e("./addCSS.js"),p=(r(f),e("./autocomplete.js")),d=r(p),h=e("./translations.js"),m=r(h),v=e("./instantsearch.js"),y=r(v),g=e("./removeCSS.js"),b=(r(g),{required:!0,type:"Object",children:{applicationId:{type:"string",required:!0},apiKey:{type:"string",required:!0},autocomplete:{type:"Object",value:{},children:{enabled:{type:"boolean",value:!0},inputSelector:{type:"string",value:"#query"},hitsPerPage:{type:"number",value:5,validators:[o]}}},baseUrl:{type:"string",value:"/hc/"},colors:{type:"Object",value:{},children:{primary:{type:"string",value:"#D4D4D4"},secondary:{type:"string",value:"#D4D4D4"}}},indexPrefix:{type:"string",value:"zendesk_"},instantsearch:{type:"Object",value:{},children:{enabled:{type:"boolean",value:!0},paginationSelector:{type:"string",value:".pagination"},selector:{type:"string",value:".search-results"},tagsLimit:{type:"number",value:15}}},instantsearchPage:{type:"function",value:a},poweredBy:{type:"boolean",value:!0},subdomain:{type:"string",required:!0},translations:{type:"Object",value:{}}}}),_=function w(){var e=this;i(this,w);var t=(0,l["default"])().check("algoliasearchZendeskHC").arg("options",b).values(arguments)[0];this.search=(t.instantsearchPage()?y["default"]:d["default"])(t),(0,u["default"])(document).ready(function(){(0,m["default"])(t),e.search.render(t)})};n["default"]=_},{"./addCSS.js":639,"./autocomplete.js":640,"./instantsearch.js":642,"./jQuery.js":643,"./removeCSS.js":644,"./translations.js":646,fargs:65}],639:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t=document.getElementsByTagName("head")[0],n=document.createElement("style");return n.setAttribute("type","text/css"),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e)),t.appendChild(n)}},{}],640:[function(e,t,n){(function(t){"use strict";function r(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")}Object.defineProperty(n,"__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},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}}(),s=e("./jQuery.js"),u=r(s);e("autocomplete.js/index_jquery.js");var c=e("algoliasearch"),l=r(c);e("es6-collections");var f=e("./templates.js"),p=r(f),d=e("./addCSS.js"),h=r(d),m=e("./removeCSS.js"),v=r(m),y=400,g=600,b=function(){function e(t){var n=t.applicationId,r=t.apiKey,o=t.autocomplete,a=o.enabled,s=o.inputSelector,u=t.indexPrefix,c=t.subdomain;i(this,e),a&&(this._temporaryHiding(s),this.client=(0,l["default"])(n,r),this.index=this.client.initIndex(""+u+c+"_articles"))}return a(e,[{key:"render",value:function(e){var n=e.autocomplete,r=n.enabled,i=n.hitsPerPage,o=n.inputSelector,a=e.baseUrl,s=e.colors,c=e.poweredBy,l=e.translations;if(!r)return null;this.$input=(0,u["default"])(o),this.locale=("undefined"!=typeof window?window.I18n:"undefined"!=typeof t?t.I18n:null).locale,this.$input.wrap('<div class="algolia-autocomplete"></div>').after('<div class="aa-dropdown-menu"></div>');var f=(0,u["default"])(".aa-dropdown-menu").outerWidth(),d=(0,u["default"])(".algolia-autocomplete");this.$input.insertAfter(d),d.remove();var m=this._sizeModifier(f),v=this._nbSnippetWords(f),y={hitsPerPage:i,facetFilters:'["locale.locale:'+this.locale+'"]',highlightPreTag:'<span class="aa-article-hit--highlight">',highlightPostTag:"</span>",attributesToSnippet:["body_safe:"+v],snippetEllipsisText:"..."};(0,h["default"])(p["default"].autocomplete.css.render({colors:s})),this.$input.attr("placeholder",l.placeholder_autocomplete).autocomplete({hint:!1,debug:!1,templates:this._templates({colors:s,poweredBy:c,translations:l})},[{source:this._source(y),name:"articles",templates:{suggestion:this._renderSuggestion(m)}}]).on("autocomplete:selected",this._onSelected(a)),this._temporaryHidingCancel()}},{key:"_sizeModifier",value:function(e){return e<y?"xs":e<g?"sm":null}},{key:"_nbSnippetWords",value:function(e){return e<y?0:e<g?10+Math.floor(e/40):10+Math.floor(e/30)}},{key:"_source",value:function(e){var t=this;return function(n,r){t.index.search(o({},e,{query:n})).then(function(e){r(t._reorderedHits(e.hits))})}}},{key:"_reorderedHits",value:function(e){var t=new Map;e.forEach(function(e){var n=e.category.title,r=e.section.title;t.has(n)||(e.isCategoryHeader=!0,t.set(n,new Map)),t.get(n).has(r)||(e.isSectionHeader=!0,t.get(n).set(r,[])),t.get(n).get(r).push(e)});var n=[];return t.forEach(function(e){e.forEach(function(e){e.forEach(function(e){n.push(e)})})}),n}},{key:"_templates",value:function(e){var t=e.colors,n=e.poweredBy,r=e.translations,i={};return n===!0&&(i.footer=p["default"].autocomplete.footer.render({colors:t,translations:r})),i}},{key:"_renderSuggestion",value:function(e){return function(t){return t.sizeModifier=e,p["default"].autocomplete.article.render(t)}}},{key:"_onSelected",value:function(e){var t=this;return function(n,r,i){location.href=""+e+t.locale+"/"+i+"/"+r.id}}},{key:"_temporaryHiding",value:function(e){this._temporaryHidingCSS=(0,h["default"])("\n "+e+" {\n visibility: hidden !important;\n height: 1px !important;\n }\n ")}},{key:"_temporaryHidingCancel",value:function(){(0,v["default"])(this._temporaryHidingCSS),delete this._temporaryHidingCSS}}]),e}();n["default"]=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return new(Function.prototype.bind.apply(b,[null].concat(t)))}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./addCSS.js":639,"./jQuery.js":643,"./removeCSS.js":644,"./templates.js":645,algoliasearch:26,"autocomplete.js/index_jquery.js":44,"es6-collections":62}],641:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var i=e("to-factory"),o=r(i),a=e("./AlgoliasearchZendeskHC.js"),s=r(a);n["default"]=(0,o["default"])(s["default"])},{"./AlgoliasearchZendeskHC.js":638,"to-factory":634}],642:[function(e,t,n){(function(t){"use strict";function r(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")}Object.defineProperty(n,"__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},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}}(),s="undefined"!=typeof window?window.$:"undefined"!=typeof t?t.$:null,u=r(s),c=e("instantsearch.js"),l=r(c),f=e("./templates.js"),p=r(f),d=e("./addCSS.js"),h=r(d),m=e("./removeCSS.js"),v=r(m),y=function(){function e(t){var n=t.applicationId,r=t.apiKey,o=t.autocomplete.inputSelector,a=t.indexPrefix,s=t.instantsearch,u=s.enabled,c=s.paginationSelector,f=s.selector,p=t.subdomain;i(this,e),u&&(this._temporaryHiding({autocompleteSelector:o,instantsearchSelector:f,paginationSelector:c}),this.instantsearch=(0,l["default"])({appId:n,apiKey:r,indexName:""+a+p+"_articles",urlSync:{mapping:{q:"query"}},searchParameters:{attributesToSnippet:["body_safe:60"],snippetEllipsisText:"..."}}))}return a(e,[{key:"render",value:function(e){var n=this,r=e.autocomplete.inputSelector,i=e.baseUrl,a=e.colors,s=e.instantsearch,c=s.enabled,f=s.selector,d=s.paginationSelector,h=s.tagsLimit,m=e.poweredBy,v=e.translations;if(c){var y="undefined"!=typeof window?window.I18n:"undefined"!=typeof t?t.I18n:null;this.$autocompleteInput=(0,u["default"])(r),this._hideAutocomplete(),this.$oldPagination=(0,u["default"])(d),this.$oldPagination.hide(),this.$container=(0,u["default"])(f),this.$container.html(p["default"].instantsearch.layout),this.instantsearch.addWidget({getConfiguration:function(){return{facets:["locale.locale"]}},init:function(e){var t=e.helper;t.toggleRefine("locale.locale",y.locale)}}),this.instantsearch.addWidget(l["default"].widgets.searchBox({container:"#algolia-query",placeholder:v.placeholder_instantsearch,autofocus:!0,poweredBy:m})),this.instantsearch.addWidget(l["default"].widgets.stats({container:"#algolia-stats",templates:{body:p["default"].instantsearch.stats},transformData:function(e){return o({},e,{translations:v})}})),this.instantsearch.addWidget(l["default"].widgets.pagination({container:"#algolia-pagination",cssClasses:{root:"pagination"}})),this.instantsearch.addWidget(l["default"].widgets.hierarchicalMenu({container:"#algolia-categories",attributes:["category.title","section.full_path"],separator:" > ",templates:{header:v.categories}})),this.instantsearch.addWidget(l["default"].widgets.refinementList({container:"#algolia-labels",attributeName:"label_names",operator:"and",templates:{header:v.tags},limit:h})),this.instantsearch.addWidget(l["default"].widgets.hits({container:"#algolia-hits",templates:{empty:p["default"].instantsearch.noResults,item:p["default"].instantsearch.hit},transformData:function(e){return o({},e,{baseUrl:i,colors:a})}})),this.instantsearch.on("render",function(){n._displayTimes()}),this.instantsearch.start(),this._temporaryHidingCancel()}}},{key:"_displayTimes",value:function(){var e=this,n=moment().zone();("undefined"!=typeof window?window.moment:"undefined"!=typeof t?t.moment:null)().lang(I18n.locale,I18n.datetime_translations),(0,u["default"])("time").each(function(){var t=(0,u["default"])(e),r=t.attr("datetime"),i=moment(r).utc().zone(n),o=i.format("YYYY-MM-DD HH:mm");t.attr("title",o),"relative"===t.data("datetime")?t.text(i.fromNow()):"calendar"===t.data("datetime")&&t.text(i.calendar())})}},{key:"_hideAutocomplete",value:function(){for(var e=this.$autocompleteInput.closest("form"),t=e.parent();1===t.children.length;)e=t,t=e.parent();e.hide()}},{key:"_temporaryHiding",value:function(e){var t=e.autocompleteSelector,n=e.instantsearchSelector,r=e.paginationSelector;this._temporaryHidingCSS=(0,h["default"])("\n "+t+", "+n+", "+r+" {\n display: none !important;\n visibility: hidden !important;\n }\n ")}},{key:"_temporaryHidingCancel", value:function(){(0,v["default"])(this._temporaryHidingCSS),delete this._temporaryHidingCSS}}]),e}();n["default"]=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return new(Function.prototype.bind.apply(y,[null].concat(t)))}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./addCSS.js":639,"./removeCSS.js":644,"./templates.js":645,"instantsearch.js":111}],643:[function(e,t,n){(function(e){"use strict";function t(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var r="undefined"!=typeof window?window.$:"undefined"!=typeof e?e.$:null,i=t(r);if(!i["default"])throw new Error("Cannot find required dependency to jQuery.");n["default"]=i["default"]}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],644:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n["default"]=function(e){var t=document.getElementsByTagName("head")[0];t.removeChild(e)}},{}],645:[function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(n,"__esModule",{value:!0});var i=e("hogan.js"),o=r(i);n["default"]={autocomplete:{section:o["default"].compile('<div class="hit-section" style="border-bottom-color: {{colors.secondary}}">\n <div class="title overflow-block-container">\n <span class="overflow-block">\n {{{ _highlightResult.category.title.value }}} > {{{ _highlightResult.title.value }}}\n </span>\n <small class="overflow-block text-muted">({{ nb_articles_text }})</small>\n </div>\n <div class="body">{{{ _highlightResult.body.value }}}</div>\n </div>'),article:o["default"].compile('<div\n class="\n aa-article-hit\n {{# isCategoryHeader }}aa-article-hit__category-first{{/ isCategoryHeader }}\n {{# isSectionHeader }}aa-article-hit__section-first{{/ isSectionHeader }}\n {{# sizeModifier }}aa-article-hit__{{ sizeModifier }}{{/ sizeModifier}}\n "\n >\n <div class="aa-article-hit--category">\n {{ category.title }}\n </div>\n <div class="aa-article-hit--line">\n <div class="aa-article-hit--section">\n <div class="aa-article-hit--section--inside">{{ section.title }}</div>\n </div>\n <div class="aa-article-hit--content">\n <div class="aa-article-hit--title">\n {{{ _highlightResult.title.value }}}\n </div>\n {{# _snippetResult.body_safe.value }}\n <div class="aa-article-hit--body">{{{ _snippetResult.body_safe.value }}}</div>\n {{/ _snippetResult.body_safe.value }}\n </div>\n </div>'),footer:o["default"].compile('<div class="aa-powered-by" style="border-top-color: {{colors.secondary}}">\n {{ translations.search_by }}\n <a\n href="https://www.algolia.com/?utm_source=zendesk_hc&utm_medium=link&utm_campaign=autocomplete"\n class="aa-powered-by-link"\n >\n Algolia\n </a>\n </div>'),css:o["default"].compile("\n .aa-article-hit--highlight {\n color: {{ colors.primary }};\n }\n\n .aa-article-hit--category {\n background-color: {{ colors.primary }};\n }\n\n .aa-article-hit--section, .aa-article-hit--content {\n border-color: {{ colors.secondary }};\n }\n ")},instantsearch:{layout:'\n<div>\n <input type="text" id="algolia-query"/>\n <div id="algolia-stats"></div>\n <div id="algolia-facets">\n <div id="algolia-categories"></div>\n <div id="algolia-labels"></div>\n </div>\n <div id="algolia-hits"></div>\n <div class="clearfix"></div>\n <div id="algolia-pagination"></div>\n</div>\n ',hit:'\n<div class="search-result">\n <a class="search-result-link" href="{{baseUrl}}{{ locale.locale }}/articles/{{ id }}">\n {{{ _highlightResult.title.value }}}\n </a>\n {{#vote_sum}}<span class="search-result-votes">{{ vote_sum }}</span>{{/vote_sum}}\n <div class="search-result-meta">\n <time data-datetime="relative" datetime="{{ created_at_iso }}"></time>\n </div>\n <div class="search-result-body">\n {{{ _snippetResult.body_safe.value }}}\n </div>\n</div>\n ',noResults:'\n<div id="no-results-message">\n <p>We didn\'t find any results for the search <em>"{{ query }}"</em>.</p>\n</div>\n ',stats:'\n{{# hasNoResults }}{{ translations.no_result }}{{/ hasNoResults }}\n{{# hasOneResult }}1 {{ translations.result }}{{/ hasOneResult }}\n{{# hasManyResults }}\n {{# helpers.formatNumber }}{{ nbHits }}{{/ helpers.formatNumber }}\n {{ translations.results }}\n{{/ hasManyResults }}\n<span class="{{ cssClasses.time }}">{{ translations.found_in }} {{ processingTimeMS }}ms</span>\n '}}},{"hogan.js":108}],646:[function(e,t,n){(function(t){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function i(e,t,n,r,i){if(!(0,s["default"])(t[n]))return(0,f["default"])(t[n])&&(0,s["default"])(t[n][e.locale])?void(t[n]=t[n][e.locale]):!(0,c["default"])(i)&&(0,s["default"])(e.translations[i])?void(t[n]=e.translations[i]):void(t[n]=r)}function o(e){var n=e.translations,r="undefined"!=typeof window?window.I18n:"undefined"!=typeof t?t.I18n:null;i(r,n,"article","Article","txt.help_center.views.admin.manage_knowledge_base.table.article"),i(r,n,"articles","Articles","txt.help_center.javascripts.arrange_content.articles"),i(r,n,"categories","Categories","txt.help_center.javascripts.arrange_content.categories"),i(r,n,"sections","Sections","txt.help_center.javascripts.arrange_content.sections"),i(r,n,"tags","Tags"),i(r,n,"search_by","Search by"),i(r,n,"no_result","No result"),i(r,n,"result","Result"),i(r,n,"results","Results"),i(r,n,"found_in","Found in"),i(r,n,"search_by","Search by"),i(r,n,"placeholder_autocomplete","Search in sections and articles"),i(r,n,"placeholder_instantsearch","Search in articles")}Object.defineProperty(n,"__esModule",{value:!0}),n.loadTranslations=o;var a=e("lodash/isString"),s=r(a),u=e("lodash/isUndefined"),c=r(u),l=e("lodash/isPlainObject"),f=r(l);n["default"]=o}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"lodash/isPlainObject":434,"lodash/isString":435,"lodash/isUndefined":438}]},{},[1])(1)}); //# sourceMappingURL=algoliasearch.zendesk-hc.min.js.map
playground/components/Editor.js
apiaryio/attributes-kit
import React from 'react'; import PropTypes from 'prop-types'; import AceEditor from 'react-ace'; import dedent from 'dedent'; import isArray from 'lodash/isArray'; import isObject from 'lodash/isObject'; import isEmpty from 'lodash/isEmpty'; import findIndex from 'lodash/findIndex'; import 'brace/theme/github'; import 'brace/mode/markdown'; import EditorActions from '../actions/editor'; class EditorComponent extends React.Component { static propTypes = { errors: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), }; constructor() { super(); this.state = { msonCode: dedent` # Data Structures ## Welcome Message - message: Hello everyone (string) Message for all the good folks at the [API Blueprint issue #191][1] [1]: https://github.com/apiaryio/api-blueprint/issues/191 - author (Author) ## Author - name: Z - twitter: @zdne - address - company: \`Apiary, INC\` - street: 325 Ninth Street (required) - city: San Francisco - state: CA - zip (number, required) - tags (TagsArray) ## TagsArray (array) - red - green - blue `, }; } componentDidMount() { EditorActions.parse(this.state.msonCode); } onLoad = (aceEditor) => { this.aceEditor = aceEditor; let annotations = []; const session = this.aceEditor.getSession(); if (isArray(this.props.errors)) { annotations = this.props.errors.map(this.generateAnnotation); } else if (isObject(this.props.errors)) { annotations.push(this.generateAnnotation(this.props.errors)); } if (isEmpty(annotations)) { session.clearAnnotations(); } else { session.setAnnotations(annotations); } }; generateAnnotation(error) { let errorRow = 0; if (error.location.length > 0) { const errorLine = this.state.msonCode .substring(error.location[0].index) .split('\n')[0]; const lines = this.state.msonCode.split('\n'); errorRow = findIndex(lines, (line) => line.indexOf(errorLine) > -1 ); } return { type: 'error', text: `${this.props.errors.code} - ${this.props.errors.message}`, row: errorRow, }; } handleChange = (msonCode) => { this.setState({ msonCode }); EditorActions.parse(msonCode); }; render() { return ( <AceEditor onLoad={this.onLoad} heigth="500px" width="100%" theme="github" mode="markdown" onChange={this.handleChange} name="msonEditor" value={this.state.msonCode} tabSize={2} editorProps={{ $blockScrolling: true }} /> ); } } export default EditorComponent;
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
wilsonwp/servidor
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/components/video_detail.js
noframes/react-youtube-search
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return <div>Loading...</div> }; const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe src={url} frameborder="0" className="embed-responsive-item"></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
ajax/libs/jointjs/1.0.0/joint.core.js
froala/cdnjs
/*! JointJS v0.9.10 (2016-06-13) - JavaScript diagramming library This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // For AMD. define(['backbone', 'lodash', 'jquery'], function(Backbone, _, $) { Backbone.$ = $; return factory(root, Backbone, _, $); }); } else if (typeof exports !== 'undefined') { // For Node.js or CommonJS. var Backbone = require('backbone'); var _ = require('lodash'); var $ = Backbone.$ = require('jquery'); module.exports = factory(root, Backbone, _, $); } else { // As a browser global. var Backbone = root.Backbone; var _ = root._; var $ = Backbone.$ = root.jQuery || root.$; root.joint = factory(root, Backbone, _, $); root.g = root.joint.g; root.V = root.Vectorizer = root.joint.V; } }(this, function(root, Backbone, _, $) { // Geometry library. // (c) 2011-2015 client IO var g = (function() { var g = {}; // Declare shorthands to the most used math functions. var math = Math; var abs = math.abs; var cos = math.cos; var sin = math.sin; var sqrt = math.sqrt; var mmin = math.min; var mmax = math.max; var atan = math.atan; var atan2 = math.atan2; var acos = math.acos; var round = math.round; var floor = math.floor; var PI = math.PI; var random = math.random; var bezier = g.bezier = { // Cubic Bezier curve path through points. // Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx). // @param {array} points Array of points through which the smooth line will go. // @return {array} SVG Path commands as an array curveThroughPoints: function(points) { var controlPoints = this.getCurveControlPoints(points); var path = ['M', points[0].x, points[0].y]; for (var i = 0; i < controlPoints[0].length; i++) { path.push('C', controlPoints[0][i].x, controlPoints[0][i].y, controlPoints[1][i].x, controlPoints[1][i].y, points[i + 1].x, points[i + 1].y); } return path; }, // Get open-ended Bezier Spline Control Points. // @param knots Input Knot Bezier spline points (At least two points!). // @param firstControlPoints Output First Control points. Array of knots.length - 1 length. // @param secondControlPoints Output Second Control points. Array of knots.length - 1 length. getCurveControlPoints: function(knots) { var firstControlPoints = []; var secondControlPoints = []; var n = knots.length - 1; var i; // Special case: Bezier curve should be a straight line. if (n == 1) { // 3P1 = 2P0 + P3 firstControlPoints[0] = Point((2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3); // P2 = 2P1 – P0 secondControlPoints[0] = Point(2 * firstControlPoints[0].x - knots[0].x, 2 * firstControlPoints[0].y - knots[0].y); return [firstControlPoints, secondControlPoints]; } // Calculate first Bezier control points. // Right hand side vector. var rhs = []; // Set right hand side X values. for (i = 1; i < n - 1; i++) { rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x; } rhs[0] = knots[0].x + 2 * knots[1].x; rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0; // Get first control points X-values. var x = this.getFirstControlPoints(rhs); // Set right hand side Y values. for (i = 1; i < n - 1; ++i) { rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y; } rhs[0] = knots[0].y + 2 * knots[1].y; rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0; // Get first control points Y-values. var y = this.getFirstControlPoints(rhs); // Fill output arrays. for (i = 0; i < n; i++) { // First control point. firstControlPoints.push(Point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(Point(2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1])); } else { secondControlPoints.push(Point((knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2)); } } return [firstControlPoints, secondControlPoints]; }, // Divide a Bezier curve into two at point defined by value 't' <0,1>. // Using deCasteljau algorithm. http://math.stackexchange.com/a/317867 // @param control points (start, control start, control end, end) // @return a function accepts t and returns 2 curves each defined by 4 control points. getCurveDivider: function(p0, p1, p2, p3) { return function divideCurve(t) { var l = Line(p0, p1).pointAt(t); var m = Line(p1, p2).pointAt(t); var n = Line(p2, p3).pointAt(t); var p = Line(l, m).pointAt(t); var q = Line(m, n).pointAt(t); var r = Line(p, q).pointAt(t); return [{ p0: p0, p1: l, p2: p, p3: r }, { p0: r, p1: q, p2: n, p3: p3 }]; }; }, // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points. // @param rhs Right hand side vector. // @return Solution vector. getFirstControlPoints: function(rhs) { var n = rhs.length; // `x` is a solution vector. var x = []; var tmp = []; var b = 2.0; x[0] = rhs[0] / b; // Decomposition and forward substitution. for (var i = 1; i < n; i++) { tmp[i] = 1 / b; b = (i < n - 1 ? 4.0 : 3.5) - tmp[i]; x[i] = (rhs[i] - x[i - 1]) / b; } for (i = 1; i < n; i++) { // Backsubstitution. x[n - i - 1] -= tmp[n - i] * x[n - i]; } return x; }, // Solves an inversion problem -- Given the (x, y) coordinates of a point which lies on // a parametric curve x = x(t)/w(t), y = y(t)/w(t), find the parameter value t // which corresponds to that point. // @param control points (start, control start, control end, end) // @return a function accepts a point and returns t. getInversionSolver: function(p0, p1, p2, p3) { var pts = arguments; function l(i, j) { // calculates a determinant 3x3 // [p.x p.y 1] // [pi.x pi.y 1] // [pj.x pj.y 1] var pi = pts[i]; var pj = pts[j]; return function(p) { var w = (i % 3 ? 3 : 1) * (j % 3 ? 3 : 1); var lij = p.x * (pi.y - pj.y) + p.y * (pj.x - pi.x) + pi.x * pj.y - pi.y * pj.x; return w * lij; }; } return function solveInversion(p) { var ct = 3 * l(2, 3)(p1); var c1 = l(1, 3)(p0) / ct; var c2 = -l(2, 3)(p0) / ct; var la = c1 * l(3, 1)(p) + c2 * (l(3, 0)(p) + l(2, 1)(p)) + l(2, 0)(p); var lb = c1 * l(3, 0)(p) + c2 * l(2, 0)(p) + l(1, 0)(p); return lb / (lb - la); }; } }; var Ellipse = g.Ellipse = function(c, a, b) { if (!(this instanceof Ellipse)) { return new Ellipse(c, a, b); } if (c instanceof Ellipse) { return new Ellipse(Point(c), c.a, c.b); } c = Point(c); this.x = c.x; this.y = c.y; this.a = a; this.b = b; }; g.Ellipse.fromRect = function(rect) { rect = Rect(rect); return Ellipse(rect.center(), rect.width / 2, rect.height / 2); }; g.Ellipse.prototype = { bbox: function() { return Rect(this.x - this.a, this.y - this.b, 2 * this.a, 2 * this.b); }, clone: function() { return Ellipse(this); }, equals: function(ellipse) { ellipse = Ellipse(ellipse); return ellipse.x === this.x && ellipse.y === this.y && ellipse.a === this.a && ellipse.b === this.b; }, // Find point on me where line from my center to // point p intersects my boundary. // @param {number} angle If angle is specified, intersection with rotated ellipse is computed. intersectionWithLineFromCenterToPoint: function(p, angle) { p = Point(p); if (angle) p.rotate(Point(this.x, this.y), angle); var dx = p.x - this.x; var dy = p.y - this.y; var result; if (dx === 0) { result = this.bbox().pointNearestToPoint(p); if (angle) return result.rotate(Point(this.x, this.y), -angle); return result; } var m = dy / dx; var mSquared = m * m; var aSquared = this.a * this.a; var bSquared = this.b * this.b; var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared))); x = dx < 0 ? -x : x; var y = m * x; result = Point(this.x + x, this.y + y); if (angle) return result.rotate(Point(this.x, this.y), -angle); return result; }, toString: function() { return Point(this.x, this.y).toString() + ' ' + this.a + ' ' + this.b; } }; var Line = g.Line = function(p1, p2) { if (!(this instanceof Line)) { return new Line(p1, p2); } this.start = Point(p1); this.end = Point(p2); }; g.Line.prototype = { // @return the bearing (cardinal direction) of the line. For example N, W, or SE. // @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N. bearing: function() { var lat1 = toRad(this.start.y); var lat2 = toRad(this.end.y); var lon1 = this.start.x; var lon2 = this.end.x; var dLon = toRad(lon2 - lon1); var y = sin(dLon) * cos(lat2); var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon); var brng = toDeg(atan2(y, x)); var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']; var index = brng - 22.5; if (index < 0) index += 360; index = parseInt(index / 45); return bearings[index]; }, clone: function() { return Line(this); }, // @return {point} Point where I'm intersecting l. // @see Squeak Smalltalk, LineSegment>>intersectionWith: intersection: function(l) { var pt1Dir = Point(this.end.x - this.start.x, this.end.y - this.start.y); var pt2Dir = Point(l.end.x - l.start.x, l.end.y - l.start.y); var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x); var deltaPt = Point(l.start.x - this.start.x, l.start.y - this.start.y); var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x); var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x); if (det === 0 || alpha * det < 0 || beta * det < 0) { // No intersection found. return null; } if (det > 0) { if (alpha > det || beta > det) { return null; } } else { if (alpha < det || beta < det) { return null; } } return Point(this.start.x + (alpha * pt1Dir.x / det), this.start.y + (alpha * pt1Dir.y / det)); }, // @return {double} length of the line length: function() { return sqrt(this.squaredLength()); }, // @return {point} my midpoint midpoint: function() { return Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2); }, // @return {point} my point at 't' <0,1> pointAt: function(t) { var x = (1 - t) * this.start.x + t * this.end.x; var y = (1 - t) * this.start.y + t * this.end.y; return Point(x, y); }, // @return {number} the offset of the point `p` from the line. + if the point `p` is on the right side of the line, - if on the left and 0 if on the line. pointOffset: function(p) { // Find the sign of the determinant of vectors (start,end), where p is the query point. return ((this.end.x - this.start.x) * (p.y - this.start.y) - (this.end.y - this.start.y) * (p.x - this.start.x)) / 2; }, // @return {integer} length without sqrt // @note for applications where the exact length is not necessary (e.g. compare only) squaredLength: function() { var x0 = this.start.x; var y0 = this.start.y; var x1 = this.end.x; var y1 = this.end.y; return (x0 -= x1) * x0 + (y0 -= y1) * y0; }, toString: function() { return this.start.toString() + ' ' + this.end.toString(); } }; /* Point is the most basic object consisting of x/y coordinate. Possible instantiations are: * `Point(10, 20)` * `new Point(10, 20)` * `Point('10 20')` * `Point(Point(10, 20))` */ var Point = g.Point = function(x, y) { if (!(this instanceof Point)) { return new Point(x, y); } if (typeof x === 'string') { var xy = x.split(x.indexOf('@') === -1 ? ' ' : '@'); x = parseInt(xy[0], 10); y = parseInt(xy[1], 10); } else if (Object(x) === x) { y = x.y; x = x.x; } this.x = x === undefined ? 0 : x; this.y = y === undefined ? 0 : y; }; // Alternative constructor, from polar coordinates. // @param {number} Distance. // @param {number} Angle in radians. // @param {point} [optional] Origin. g.Point.fromPolar = function(distance, angle, origin) { origin = (origin && Point(origin)) || Point(0, 0); var x = abs(distance * cos(angle)); var y = abs(distance * sin(angle)); var deg = normalizeAngle(toDeg(angle)); if (deg < 90) { y = -y; } else if (deg < 180) { x = -x; y = -y; } else if (deg < 270) { x = -x; } return Point(origin.x + x, origin.y + y); }; // Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`. g.Point.random = function(x1, x2, y1, y2) { return Point(floor(random() * (x2 - x1 + 1) + x1), floor(random() * (y2 - y1 + 1) + y1)); }; g.Point.prototype = { // If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`, // otherwise return point itself. // (see Squeak Smalltalk, Point>>adhereTo:) adhereToRect: function(r) { if (r.containsPoint(this)) { return this; } this.x = mmin(mmax(this.x, r.x), r.x + r.width); this.y = mmin(mmax(this.y, r.y), r.y + r.height); return this; }, // Return the bearing between me and the given point. bearing: function(point) { return Line(this, point).bearing(); }, // Returns change in angle from my previous position (-dx, -dy) to my new position // relative to ref point. changeInAngle: function(dx, dy, ref) { // Revert the translation and measure the change in angle around x-axis. return Point(this).offset(-dx, -dy).theta(ref) - this.theta(ref); }, clone: function() { return Point(this); }, difference: function(p) { return Point(this.x - p.x, this.y - p.y); }, // Returns distance between me and point `p`. distance: function(p) { return Line(this, p).length(); }, equals: function(p) { return this.x === p.x && this.y === p.y; }, magnitude: function() { return sqrt((this.x * this.x) + (this.y * this.y)) || 0.01; }, // Returns a manhattan (taxi-cab) distance between me and point `p`. manhattanDistance: function(p) { return abs(p.x - this.x) + abs(p.y - this.y); }, // Move point on line starting from ref ending at me by // distance distance. move: function(ref, distance) { var theta = toRad(Point(ref).theta(this)); return this.offset(cos(theta) * distance, -sin(theta) * distance); }, // Scales x and y such that the distance between the point and the origin (0,0) is equal to the given length. normalize: function(length) { var scale = (length || 1) / this.magnitude(); return this.scale(scale, scale); }, // Offset me by the specified amount. offset: function(dx, dy) { this.x += dx || 0; this.y += dy || 0; return this; }, // Returns a point that is the reflection of me with // the center of inversion in ref point. reflection: function(ref) { return Point(ref).move(this, this.distance(ref)); }, // Rotate point by angle around origin. rotate: function(origin, angle) { angle = (angle + 360) % 360; this.toPolar(origin); this.y += toRad(angle); var point = Point.fromPolar(this.x, this.y, origin); this.x = point.x; this.y = point.y; return this; }, round: function(precision) { this.x = precision ? this.x.toFixed(precision) : round(this.x); this.y = precision ? this.y.toFixed(precision) : round(this.y); return this; }, // Scale point with origin. scale: function(sx, sy, origin) { origin = (origin && Point(origin)) || Point(0, 0); this.x = origin.x + sx * (this.x - origin.x); this.y = origin.y + sy * (this.y - origin.y); return this; }, snapToGrid: function(gx, gy) { this.x = snapToGrid(this.x, gx); this.y = snapToGrid(this.y, gy || gx); return this; }, // Compute the angle between me and `p` and the x axis. // (cartesian-to-polar coordinates conversion) // Return theta angle in degrees. theta: function(p) { p = Point(p); // Invert the y-axis. var y = -(p.y - this.y); var x = p.x - this.x; // Makes sure that the comparison with zero takes rounding errors into account. var PRECISION = 10; // Note that `atan2` is not defined for `x`, `y` both equal zero. var rad = (y.toFixed(PRECISION) == 0 && x.toFixed(PRECISION) == 0) ? 0 : atan2(y, x); // Correction for III. and IV. quadrant. if (rad < 0) { rad = 2 * PI + rad; } return 180 * rad / PI; }, toJSON: function() { return { x: this.x, y: this.y }; }, // Converts rectangular to polar coordinates. // An origin can be specified, otherwise it's 0@0. toPolar: function(o) { o = (o && Point(o)) || Point(0, 0); var x = this.x; var y = this.y; this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r this.y = toRad(o.theta(Point(x, y))); return this; }, toString: function() { return this.x + '@' + this.y; }, update: function(x, y) { this.x = x || 0; this.y = y || 0; return this; } }; var Rect = g.Rect = function(x, y, w, h) { if (!(this instanceof Rect)) { return new Rect(x, y, w, h); } if ((Object(x) === x)) { y = x.y; w = x.width; h = x.height; x = x.x; } this.x = x === undefined ? 0 : x; this.y = y === undefined ? 0 : y; this.width = w === undefined ? 0 : w; this.height = h === undefined ? 0 : h; }; g.Rect.fromEllipse = function(e) { e = Ellipse(e); return Rect(e.x - e.a, e.y - e.b, 2 * e.a, 2 * e.b); }; g.Rect.prototype = { // Find my bounding box when I'm rotated with the center of rotation in the center of me. // @return r {rectangle} representing a bounding box bbox: function(angle) { var theta = toRad(angle || 0); var st = abs(sin(theta)); var ct = abs(cos(theta)); var w = this.width * ct + this.height * st; var h = this.width * st + this.height * ct; return Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h); }, bottomLeft: function() { return Point(this.x, this.y + this.height); }, bottomMiddle: function() { return Point(this.x + this.width / 2, this.y + this.height); }, center: function() { return Point(this.x + this.width / 2, this.y + this.height / 2); }, clone: function() { return Rect(this); }, // @return {bool} true if point p is insight me containsPoint: function(p) { p = Point(p); return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height; }, // @return {bool} true if rectangle `r` is inside me. containsRect: function(r) { var r0 = Rect(this).normalize(); var r1 = Rect(r).normalize(); var w0 = r0.width; var h0 = r0.height; var w1 = r1.width; var h1 = r1.height; if (!w0 || !h0 || !w1 || !h1) { // At least one of the dimensions is 0 return false; } var x0 = r0.x; var y0 = r0.y; var x1 = r1.x; var y1 = r1.y; w1 += x1; w0 += x0; h1 += y1; h0 += y0; return x0 <= x1 && w1 <= w0 && y0 <= y1 && h1 <= h0; }, corner: function() { return Point(this.x + this.width, this.y + this.height); }, // @return {boolean} true if rectangles are equal. equals: function(r) { var mr = Rect(this).normalize(); var nr = Rect(r).normalize(); return mr.x === nr.x && mr.y === nr.y && mr.width === nr.width && mr.height === nr.height; }, // @return {rect} if rectangles intersect, {null} if not. intersect: function(r) { var myOrigin = this.origin(); var myCorner = this.corner(); var rOrigin = r.origin(); var rCorner = r.corner(); // No intersection found if (rCorner.x <= myOrigin.x || rCorner.y <= myOrigin.y || rOrigin.x >= myCorner.x || rOrigin.y >= myCorner.y) return null; var x = Math.max(myOrigin.x, rOrigin.x); var y = Math.max(myOrigin.y, rOrigin.y); return Rect(x, y, Math.min(myCorner.x, rCorner.x) - x, Math.min(myCorner.y, rCorner.y) - y); }, // Find point on my boundary where line starting // from my center ending in point p intersects me. // @param {number} angle If angle is specified, intersection with rotated rectangle is computed. intersectionWithLineFromCenterToPoint: function(p, angle) { p = Point(p); var center = Point(this.x + this.width / 2, this.y + this.height / 2); var result; if (angle) p.rotate(center, angle); // (clockwise, starting from the top side) var sides = [ Line(this.origin(), this.topRight()), Line(this.topRight(), this.corner()), Line(this.corner(), this.bottomLeft()), Line(this.bottomLeft(), this.origin()) ]; var connector = Line(center, p); for (var i = sides.length - 1; i >= 0; --i) { var intersection = sides[i].intersection(connector); if (intersection !== null) { result = intersection; break; } } if (result && angle) result.rotate(center, -angle); return result; }, leftMiddle: function() { return Point(this.x , this.y + this.height / 2); }, // Move and expand me. // @param r {rectangle} representing deltas moveAndExpand: function(r) { this.x += r.x || 0; this.y += r.y || 0; this.width += r.width || 0; this.height += r.height || 0; return this; }, // Normalize the rectangle; i.e., make it so that it has a non-negative width and height. // If width < 0 the function swaps the left and right corners, // and it swaps the top and bottom corners if height < 0 // like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized normalize: function() { var newx = this.x; var newy = this.y; var newwidth = this.width; var newheight = this.height; if (this.width < 0) { newx = this.x + this.width; newwidth = -this.width; } if (this.height < 0) { newy = this.y + this.height; newheight = -this.height; } this.x = newx; this.y = newy; this.width = newwidth; this.height = newheight; return this; }, origin: function() { return Point(this.x, this.y); }, // @return {point} a point on my boundary nearest to the given point. // @see Squeak Smalltalk, Rectangle>>pointNearestTo: pointNearestToPoint: function(point) { point = Point(point); if (this.containsPoint(point)) { var side = this.sideNearestToPoint(point); switch (side){ case 'right': return Point(this.x + this.width, point.y); case 'left': return Point(this.x, point.y); case 'bottom': return Point(point.x, this.y + this.height); case 'top': return Point(point.x, this.y); } } return point.adhereToRect(this); }, rightMiddle: function() { return Point(this.x + this.width, this.y + this.height / 2); }, round: function(precision) { this.x = precision ? this.x.toFixed(precision) : round(this.x); this.y = precision ? this.y.toFixed(precision) : round(this.y); this.width = precision ? this.width.toFixed(precision) : round(this.width); this.height = precision ? this.height.toFixed(precision) : round(this.height); return this; }, // Scale rectangle with origin. scale: function(sx, sy, origin) { var origin = this.origin().scale(sx, sy, origin); this.x = origin.x; this.y = origin.y; this.width *= sx; this.height *= sy; return this; }, // @return {string} (left|right|top|bottom) side which is nearest to point // @see Squeak Smalltalk, Rectangle>>sideNearestTo: sideNearestToPoint: function(point) { point = Point(point); var distToLeft = point.x - this.x; var distToRight = (this.x + this.width) - point.x; var distToTop = point.y - this.y; var distToBottom = (this.y + this.height) - point.y; var closest = distToLeft; var side = 'left'; if (distToRight < closest) { closest = distToRight; side = 'right'; } if (distToTop < closest) { closest = distToTop; side = 'top'; } if (distToBottom < closest) { closest = distToBottom; side = 'bottom'; } return side; }, snapToGrid: function(gx, gy) { var origin = this.origin().snapToGrid(gx, gy); var corner = this.corner().snapToGrid(gx, gy); this.x = origin.x; this.y = origin.y; this.width = corner.x - origin.x; this.height = corner.y - origin.y; return this; }, topMiddle: function() { return Point(this.x + this.width / 2, this.y); }, topRight: function() { return Point(this.x + this.width, this.y); }, toJSON: function() { return { x: this.x, y: this.y, width: this.width, height: this.height }; }, toString: function() { return this.origin().toString() + ' ' + this.corner().toString(); }, // @return {rect} representing the union of both rectangles. union: function(rect) { var myOrigin = this.origin(); var myCorner = this.corner(); var rOrigin = rect.origin(); var rCorner = rect.corner(); var originX = Math.min(myOrigin.x, rOrigin.x); var originY = Math.min(myOrigin.y, rOrigin.y); var cornerX = Math.max(myCorner.x, rCorner.x); var cornerY = Math.max(myCorner.y, rCorner.y); return Rect(originX, originY, cornerX - originX, cornerY - originY); } }; var normalizeAngle = g.normalizeAngle = function(angle) { return (angle % 360) + (angle < 0 ? 360 : 0); }; var scale = g.scale = { // Return the `value` from the `domain` interval scaled to the `range` interval. linear: function(domain, range, value) { var domainSpan = domain[1] - domain[0]; var rangeSpan = range[1] - range[0]; return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0; } }; var snapToGrid = g.snapToGrid = function(value, gridSize) { return gridSize * Math.round(value / gridSize); }; var toDeg = g.toDeg = function(rad) { return (180 * rad / PI) % 360; }; var toRad = g.toRad = function(deg, over360) { over360 = over360 || false; deg = over360 ? deg : (deg % 360); return deg * PI / 180; }; // For backwards compatibility: g.ellipse = g.Ellipse; g.line = g.Line; g.point = g.Point; g.rect = g.Rect; return g; })(); // Vectorizer. // ----------- // A tiny library for making your life easier when dealing with SVG. // The only Vectorizer dependency is the Geometry library. // Copyright © 2012 - 2015 client IO (http://client.io) var V; var Vectorizer; V = Vectorizer = (function() { 'use strict'; var hasSvg = typeof window === 'object' && !!( window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1') ); // SVG support is required. if (!hasSvg) { // Return a function that throws an error when it is used. return function() { throw new Error('SVG is required to use Vectorizer.'); }; } // XML namespaces. var ns = { xmlns: 'http://www.w3.org/2000/svg', xml: 'http://www.w3.org/XML/1998/namespace', xlink: 'http://www.w3.org/1999/xlink' }; var SVGversion = '1.1'; var V = function(el, attrs, children) { // This allows using V() without the new keyword. if (!(this instanceof V)) { return V.apply(Object.create(V.prototype), arguments); } if (!el) return; if (V.isV(el)) { el = el.node; } attrs = attrs || {}; if (V.isString(el)) { if (el.toLowerCase() === 'svg') { // Create a new SVG canvas. el = V.createSvgDocument(); } else if (el[0] === '<') { // Create element from an SVG string. // Allows constructs of type: `document.appendChild(V('<rect></rect>').node)`. var svgDoc = V.createSvgDocument(el); // Note that `V()` might also return an array should the SVG string passed as // the first argument contain more than one root element. if (svgDoc.childNodes.length > 1) { // Map child nodes to `V`s. var arrayOfVels = []; var i, len; for (i = 0, len = svgDoc.childNodes.length; i < len; i++) { var childNode = svgDoc.childNodes[i]; arrayOfVels.push(new V(document.importNode(childNode, true))); } return arrayOfVels; } el = document.importNode(svgDoc.firstChild, true); } else { el = document.createElementNS(ns.xmlns, el); } } this.node = el; if (!this.node.id) { this.node.id = V.uniqueId(); } this.setAttributes(attrs); if (children) { this.append(children); } return this; }; /** * @param {SVGGElement} toElem * @returns {SVGMatrix} */ V.prototype.getTransformToElement = function(toElem) { return toElem.getScreenCTM().inverse().multiply(this.node.getScreenCTM()); }; /** * @param {SVGMatrix} matrix * @returns {V, SVGMatrix} Setter / Getter */ V.prototype.transform = function(matrix) { if (V.isUndefined(matrix)) { return (this.node.parentNode) ? this.getTransformToElement(this.node.parentNode) : this.node.getScreenCTM(); } var svgTransform = V.createSVGTransform(matrix); this.node.transform.baseVal.appendItem(svgTransform); return this; }; V.prototype.translate = function(tx, ty, opt) { opt = opt || {}; ty = ty || 0; var transformAttr = this.attr('transform') || ''; var transform = V.parseTransformString(transformAttr); // Is it a getter? if (V.isUndefined(tx)) { return transform.translate; } transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim(); var newTx = opt.absolute ? tx : transform.translate.tx + tx; var newTy = opt.absolute ? ty : transform.translate.ty + ty; var newTranslate = 'translate(' + newTx + ',' + newTy + ')'; // Note that `translate()` is always the first transformation. This is // usually the desired case. this.attr('transform', (newTranslate + ' ' + transformAttr).trim()); return this; }; V.prototype.rotate = function(angle, cx, cy, opt) { opt = opt || {}; var transformAttr = this.attr('transform') || ''; var transform = V.parseTransformString(transformAttr); // Is it a getter? if (V.isUndefined(angle)) { return transform.rotate; } transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim(); angle %= 360; var newAngle = opt.absolute ? angle : transform.rotate.angle + angle; var newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : ''; var newRotate = 'rotate(' + newAngle + newOrigin + ')'; this.attr('transform', (transformAttr + ' ' + newRotate).trim()); return this; }; // Note that `scale` as the only transformation does not combine with previous values. V.prototype.scale = function(sx, sy) { sy = V.isUndefined(sy) ? sx : sy; var transformAttr = this.attr('transform') || ''; var transform = V.parseTransformString(transformAttr); // Is it a getter? if (V.isUndefined(sx)) { return transform.scale; } transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim(); var newScale = 'scale(' + sx + ',' + sy + ')'; this.attr('transform', (transformAttr + ' ' + newScale).trim()); return this; }; // Get SVGRect that contains coordinates and dimension of the real bounding box, // i.e. after transformations are applied. // If `target` is specified, bounding box will be computed relatively to `target` element. V.prototype.bbox = function(withoutTransformations, target) { // If the element is not in the live DOM, it does not have a bounding box defined and // so fall back to 'zero' dimension element. if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 }; var box; try { box = this.node.getBBox(); // We are creating a new object as the standard says that you can't // modify the attributes of a bbox. box = { x: box.x, y: box.y, width: box.width, height: box.height }; } catch (e) { // Fallback for IE. box = { x: this.node.clientLeft, y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight }; } if (withoutTransformations) { return box; } var matrix = this.getTransformToElement(target || this.node.ownerSVGElement); return V.transformRect(box, matrix); }; V.prototype.text = function(content, opt) { // Replace all spaces with the Unicode No-break space (http://www.fileformat.info/info/unicode/char/a0/index.htm). // IE would otherwise collapse all spaces into one. content = V.sanitizeText(content); opt = opt || {}; var lines = content.split('\n'); var tspan; // `alignment-baseline` does not work in Firefox. // Setting `dominant-baseline` on the `<text>` element doesn't work in IE9. // In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`) // in the top left corner we translate the `<text>` element by `0.8em`. // See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`. // See also `http://apike.ca/prog_svg_text_style.html`. var y = this.attr('y'); if (!y) { this.attr('y', '0.8em'); } // An empty text gets rendered into the DOM in webkit-based browsers. // In order to unify this behaviour across all browsers // we rather hide the text element when it's empty. this.attr('display', content ? null : 'none'); // Preserve spaces. In other words, we do not want consecutive spaces to get collapsed to one. this.attr('xml:space', 'preserve'); // Easy way to erase all `<tspan>` children; this.node.textContent = ''; var textNode = this.node; if (opt.textPath) { // Wrap the text in the SVG <textPath> element that points // to a path defined by `opt.textPath` inside the internal `<defs>` element. var defs = this.find('defs'); if (defs.length === 0) { defs = V('defs'); this.append(defs); } // If `opt.textPath` is a plain string, consider it to be directly the // SVG path data for the text to go along (this is a shortcut). // Otherwise if it is an object and contains the `d` property, then this is our path. var d = Object(opt.textPath) === opt.textPath ? opt.textPath.d : opt.textPath; if (d) { var path = V('path', { d: d }); defs.append(path); } var textPath = V('textPath'); // Set attributes on the `<textPath>`. The most important one // is the `xlink:href` that points to our newly created `<path/>` element in `<defs/>`. // Note that we also allow the following construct: // `t.text('my text', { textPath: { 'xlink:href': '#my-other-path' } })`. // In other words, one can completely skip the auto-creation of the path // and use any other arbitrary path that is in the document. if (!opt.textPath['xlink:href'] && path) { textPath.attr('xlink:href', '#' + path.node.id); } if (Object(opt.textPath) === opt.textPath) { textPath.attr(opt.textPath); } this.append(textPath); // Now all the `<tspan>`s will be inside the `<textPath>`. textNode = textPath.node; } var offset = 0; for (var i = 0; i < lines.length; i++) { var line = lines[i]; // Shift all the <tspan> but first by one line (`1em`) var lineHeight = opt.lineHeight || '1em'; if (opt.lineHeight === 'auto') { lineHeight = '1.5em'; } var vLine = V('tspan', { dy: (i == 0 ? '0em' : lineHeight), x: this.attr('x') || 0 }); vLine.addClass('v-line'); if (line) { if (opt.annotations) { // Get the line height based on the biggest font size in the annotations for this line. var maxFontSize = 0; // Find the *compacted* annotations for this line. var lineAnnotations = V.annotateString(lines[i], V.isArray(opt.annotations) ? opt.annotations : [opt.annotations], { offset: -offset, includeAnnotationIndices: opt.includeAnnotationIndices }); for (var j = 0; j < lineAnnotations.length; j++) { var annotation = lineAnnotations[j]; if (V.isObject(annotation)) { var fontSize = parseInt(annotation.attrs['font-size'], 10); if (fontSize && fontSize > maxFontSize) { maxFontSize = fontSize; } tspan = V('tspan', annotation.attrs); if (opt.includeAnnotationIndices) { // If `opt.includeAnnotationIndices` is `true`, // set the list of indices of all the applied annotations // in the `annotations` attribute. This list is a comma // separated list of indices. tspan.attr('annotations', annotation.annotations); } if (annotation.attrs['class']) { tspan.addClass(annotation.attrs['class']); } tspan.node.textContent = annotation.t; } else { tspan = document.createTextNode(annotation || ' '); } vLine.append(tspan); } if (opt.lineHeight === 'auto' && maxFontSize && i !== 0) { vLine.attr('dy', (maxFontSize * 1.2) + 'px'); } } else { vLine.node.textContent = line; } } else { // Make sure the textContent is never empty. If it is, add a dummy // character and make it invisible, making the following lines correctly // relatively positioned. `dy=1em` won't work with empty lines otherwise. vLine.addClass('v-empty-line'); // 'opacity' needs to be specified with fill, stroke. Opacity without specification // is not applied in Firefox vLine.node.style.fillOpacity = 0; vLine.node.style.strokeOpacity = 0; vLine.node.textContent = '-'; } V(textNode).append(vLine); offset += line.length + 1; // + 1 = newline character. } return this; }; /** * @public * @param {string} name * @returns {Vectorizer} */ V.prototype.removeAttr = function(name) { var qualifiedName = V.qualifyAttr(name); var el = this.node; if (qualifiedName.ns) { if (el.hasAttributeNS(qualifiedName.ns, qualifiedName.local)) { el.removeAttributeNS(qualifiedName.ns, qualifiedName.local); } } else if (el.hasAttribute(name)) { el.removeAttribute(name); } return this; }; V.prototype.attr = function(name, value) { if (V.isUndefined(name)) { // Return all attributes. var attributes = this.node.attributes; var attrs = {}; for (var i = 0; i < attributes.length; i++) { attrs[attributes[i].nodeName] = attributes[i].nodeValue; } return attrs; } if (V.isString(name) && V.isUndefined(value)) { return this.node.getAttribute(name); } if (typeof name === 'object') { for (var attrName in name) { if (name.hasOwnProperty(attrName)) { this.setAttribute(attrName, name[attrName]); } } } else { this.setAttribute(name, value); } return this; }; V.prototype.remove = function() { if (this.node.parentNode) { this.node.parentNode.removeChild(this.node); } return this; }; V.prototype.empty = function() { while (this.node.firstChild) { this.node.removeChild(this.node.firstChild); } return this; }; V.prototype.setAttributes = function(attrs) { for (var key in attrs) { if (attrs.hasOwnProperty(key)) { this.setAttribute(key, attrs[key]); } } return this; }; V.prototype.append = function(els) { if (!V.isArray(els)) { els = [els]; } for (var i = 0, len = els.length; i < len; i++) { this.node.appendChild(V.toNode(els[i])); } return this; }; V.prototype.prepend = function(els) { var child = this.node.firstChild; return child ? V(child).before(els) : this.append(els); }; V.prototype.before = function(els) { var node = this.node; var parent = node.parentNode; if (parent) { if (!V.isArray(els)) { els = [els]; } for (var i = 0, len = els.length; i < len; i++) { parent.insertBefore(V.toNode(els[i]), node); } } return this; }; V.prototype.svg = function() { return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement); }; V.prototype.defs = function() { var defs = this.svg().node.getElementsByTagName('defs'); return (defs && defs.length) ? V(defs[0]) : undefined; }; V.prototype.clone = function() { var clone = V(this.node.cloneNode(true/* deep */)); // Note that clone inherits also ID. Therefore, we need to change it here. clone.node.id = V.uniqueId(); return clone; }; V.prototype.findOne = function(selector) { var found = this.node.querySelector(selector); return found ? V(found) : undefined; }; V.prototype.find = function(selector) { var vels = []; var nodes = this.node.querySelectorAll(selector); if (nodes) { // Map DOM elements to `V`s. for (var i = 0; i < nodes.length; i++) { vels.push(V(nodes[i])); } } return vels; }; // Find an index of an element inside its container. V.prototype.index = function() { var index = 0; var node = this.node.previousSibling; while (node) { // nodeType 1 for ELEMENT_NODE if (node.nodeType === 1) index++; node = node.previousSibling; } return index; }; V.prototype.findParentByClass = function(className, terminator) { var ownerSVGElement = this.node.ownerSVGElement; var node = this.node.parentNode; while (node && node !== terminator && node !== ownerSVGElement) { var vel = V(node); if (vel.hasClass(className)) { return vel; } node = node.parentNode; } return null; }; // Convert global point into the coordinate space of this element. V.prototype.toLocalPoint = function(x, y) { var svg = this.svg().node; var p = svg.createSVGPoint(); p.x = x; p.y = y; try { var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse()); var globalToLocalMatrix = this.getTransformToElement(svg).inverse(); } catch (e) { // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`) // We have to make do with the original coordianates. return p; } return globalPoint.matrixTransform(globalToLocalMatrix); }; V.prototype.translateCenterToPoint = function(p) { var bbox = this.bbox(); var center = g.rect(bbox).center(); this.translate(p.x - center.x, p.y - center.y); }; // Efficiently auto-orient an element. This basically implements the orient=auto attribute // of markers. The easiest way of understanding on what this does is to imagine the element is an // arrowhead. Calling this method on the arrowhead makes it point to the `position` point while // being auto-oriented (properly rotated) towards the `reference` point. // `target` is the element relative to which the transformations are applied. Usually a viewport. V.prototype.translateAndAutoOrient = function(position, reference, target) { // Clean-up previously set transformations except the scale. If we didn't clean up the // previous transformations then they'd add up with the old ones. Scale is an exception as // it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the // element is scaled by the factor 2, not 8. var s = this.scale(); this.attr('transform', ''); this.scale(s.sx, s.sy); var svg = this.svg().node; var bbox = this.bbox(false, target); // 1. Translate to origin. var translateToOrigin = svg.createSVGTransform(); translateToOrigin.setTranslate(-bbox.x - bbox.width / 2, -bbox.y - bbox.height / 2); // 2. Rotate around origin. var rotateAroundOrigin = svg.createSVGTransform(); var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference); rotateAroundOrigin.setRotate(angle, 0, 0); // 3. Translate to the `position` + the offset (half my width) towards the `reference` point. var translateFinal = svg.createSVGTransform(); var finalPosition = g.point(position).move(reference, bbox.width / 2); translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y)); // 4. Apply transformations. var ctm = this.getTransformToElement(target); var transform = svg.createSVGTransform(); transform.setMatrix( translateFinal.matrix.multiply( rotateAroundOrigin.matrix.multiply( translateToOrigin.matrix.multiply( ctm))) ); // Instead of directly setting the `matrix()` transform on the element, first, decompose // the matrix into separate transforms. This allows us to use normal Vectorizer methods // as they don't work on matrices. An example of this is to retrieve a scale of an element. // this.node.transform.baseVal.initialize(transform); var decomposition = V.decomposeMatrix(transform.matrix); this.translate(decomposition.translateX, decomposition.translateY); this.rotate(decomposition.rotation); // Note that scale has been already applied, hence the following line stays commented. (it's here just for reference). //this.scale(decomposition.scaleX, decomposition.scaleY); return this; }; V.prototype.animateAlongPath = function(attrs, path) { var animateMotion = V('animateMotion', attrs); var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id }); animateMotion.append(mpath); this.append(animateMotion); try { animateMotion.node.beginElement(); } catch (e) { // Fallback for IE 9. // Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present if (document.documentElement.getAttribute('smiling') === 'fake') { // Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`) var animation = animateMotion.node; animation.animators = []; var animationID = animation.getAttribute('id'); if (animationID) id2anim[animationID] = animation; var targets = getTargets(animation); for (var i = 0, len = targets.length; i < len; i++) { var target = targets[i]; var animator = new Animator(animation, target, i); animators.push(animator); animation.animators[i] = animator; animator.register(); } } } }; V.prototype.hasClass = function(className) { return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class')); }; V.prototype.addClass = function(className) { if (!this.hasClass(className)) { var prevClasses = this.node.getAttribute('class') || ''; this.node.setAttribute('class', (prevClasses + ' ' + className).trim()); } return this; }; V.prototype.removeClass = function(className) { if (this.hasClass(className)) { var newClasses = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2'); this.node.setAttribute('class', newClasses); } return this; }; V.prototype.toggleClass = function(className, toAdd) { var toRemove = V.isUndefined(toAdd) ? this.hasClass(className) : !toAdd; if (toRemove) { this.removeClass(className); } else { this.addClass(className); } return this; }; // Interpolate path by discrete points. The precision of the sampling // is controlled by `interval`. In other words, `sample()` will generate // a point on the path starting at the beginning of the path going to the end // every `interval` pixels. // The sampler can be very useful for e.g. finding intersection between two // paths (finding the two closest points from two samples). V.prototype.sample = function(interval) { interval = interval || 1; var node = this.node; var length = node.getTotalLength(); var samples = []; var distance = 0; var sample; while (distance < length) { sample = node.getPointAtLength(distance); samples.push({ x: sample.x, y: sample.y, distance: distance }); distance += interval; } return samples; }; V.prototype.convertToPath = function() { var path = V('path'); path.attr(this.attr()); var d = this.convertToPathData(); if (d) { path.attr('d', d); } return path; }; V.prototype.convertToPathData = function() { var tagName = this.node.tagName.toUpperCase(); switch (tagName) { case 'PATH': return this.attr('d'); case 'LINE': return V.convertLineToPathData(this.node); case 'POLYGON': return V.convertPolygonToPathData(this.node); case 'POLYLINE': return V.convertPolylineToPathData(this.node); case 'ELLIPSE': return V.convertEllipseToPathData(this.node); case 'CIRCLE': return V.convertCircleToPathData(this.node); case 'RECT': return V.convertRectToPathData(this.node); } throw new Error(tagName + ' cannot be converted to PATH.'); }; // Find the intersection of a line starting in the center // of the SVG `node` ending in the point `ref`. // `target` is an SVG element to which `node`s transformations are relative to. // In JointJS, `target` is the `paper.viewport` SVG group element. // Note that `ref` point must be in the coordinate system of the `target` for this function to work properly. // Returns a point in the `target` coordinte system (the same system as `ref` is in) if // an intersection is found. Returns `undefined` otherwise. V.prototype.findIntersection = function(ref, target) { var svg = this.svg().node; target = target || svg; var bbox = g.rect(this.bbox(false, target)); var center = bbox.center(); if (!bbox.intersectionWithLineFromCenterToPoint(ref)) return undefined; var spot; var tagName = this.node.localName.toUpperCase(); // Little speed up optimalization for `<rect>` element. We do not do conversion // to path element and sampling but directly calculate the intersection through // a transformed geometrical rectangle. if (tagName === 'RECT') { var gRect = g.rect( parseFloat(this.attr('x') || 0), parseFloat(this.attr('y') || 0), parseFloat(this.attr('width')), parseFloat(this.attr('height')) ); // Get the rect transformation matrix with regards to the SVG document. var rectMatrix = this.getTransformToElement(target); // Decompose the matrix to find the rotation angle. var rectMatrixComponents = V.decomposeMatrix(rectMatrix); // Now we want to rotate the rectangle back so that we // can use `intersectionWithLineFromCenterToPoint()` passing the angle as the second argument. var resetRotation = svg.createSVGTransform(); resetRotation.setRotate(-rectMatrixComponents.rotation, center.x, center.y); var rect = V.transformRect(gRect, resetRotation.matrix.multiply(rectMatrix)); spot = g.rect(rect).intersectionWithLineFromCenterToPoint(ref, rectMatrixComponents.rotation); } else if (tagName === 'PATH' || tagName === 'POLYGON' || tagName === 'POLYLINE' || tagName === 'CIRCLE' || tagName === 'ELLIPSE') { var pathNode = (tagName === 'PATH') ? this : this.convertToPath(); var samples = pathNode.sample(); var minDistance = Infinity; var closestSamples = []; var i, sample, gp, centerDistance, refDistance, distance; for (i = 0; i < samples.length; i++) { sample = samples[i]; // Convert the sample point in the local coordinate system to the global coordinate system. gp = V.createSVGPoint(sample.x, sample.y); gp = gp.matrixTransform(this.getTransformToElement(target)); sample = g.point(gp); centerDistance = sample.distance(center); // Penalize a higher distance to the reference point by 10%. // This gives better results. This is due to // inaccuracies introduced by rounding errors and getPointAtLength() returns. refDistance = sample.distance(ref) * 1.1; distance = centerDistance + refDistance; if (distance < minDistance) { minDistance = distance; closestSamples = [{ sample: sample, refDistance: refDistance }]; } else if (distance < minDistance + 1) { closestSamples.push({ sample: sample, refDistance: refDistance }); } } closestSamples.sort(function(a, b) { return a.refDistance - b.refDistance; }); if (closestSamples[0]) { spot = closestSamples[0].sample; } } return spot; }; /** * @private * @param {string} name * @param {string} value * @returns {Vectorizer} */ V.prototype.setAttribute = function(name, value) { var el = this.node; if (value === null) { this.removeAttr(name); return this; } var qualifiedName = V.qualifyAttr(name); if (qualifiedName.ns) { // Attribute names can be namespaced. E.g. `image` elements // have a `xlink:href` attribute to set the source of the image. el.setAttributeNS(qualifiedName.ns, name, value); } else if (name === 'id') { el.id = value; } else { el.setAttribute(name, value); } return this; }; // Create an SVG document element. // If `content` is passed, it will be used as the SVG content of the `<svg>` root element. V.createSvgDocument = function(content) { var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + (content || '') + '</svg>'; var xml = V.parseXML(svg, { async: false }); return xml.documentElement; }; V.idCounter = 0; // A function returning a unique identifier for this client session with every call. V.uniqueId = function() { var id = ++V.idCounter + ''; return 'v-' + id; }; // Replace all spaces with the Unicode No-break space (http://www.fileformat.info/info/unicode/char/a0/index.htm). // IE would otherwise collapse all spaces into one. This is used in the text() method but it is // also exposed so that the programmer can use it in case he needs to. This is useful e.g. in tests // when you want to compare the actual DOM text content without having to add the unicode character in // the place of all spaces. V.sanitizeText = function(text) { return (text || '').replace(/ /g, '\u00A0'); }; V.isUndefined = function(value) { return typeof value === 'undefined'; }; V.isString = function(value) { return typeof value === 'string'; }; V.isObject = function(value) { return value && (typeof value === 'object'); }; V.isArray = Array.isArray; V.parseXML = function(data, opt) { opt = opt || {}; var xml; try { var parser = new DOMParser(); if (!V.isUndefined(opt.async)) { parser.async = opt.async; } xml = parser.parseFromString(data, 'text/xml'); } catch (error) { xml = undefined; } if (!xml || xml.getElementsByTagName('parsererror').length) { throw new Error('Invalid XML: ' + data); } return xml; }; /** * @param {string} name * @returns {{ns: string|null, local: string}} namespace and attribute name */ V.qualifyAttr = function(name) { if (name.indexOf(':') !== -1) { var combinedKey = name.split(':'); return { ns: ns[combinedKey[0]], local: combinedKey[1] }; } return { ns: null, local: name }; }; V.parseTransformString = function(transform) { var translate, rotate, scale; if (transform) { var separator = /[ ,]+/; var translateMatch = transform.match(/translate\((.*)\)/); if (translateMatch) { translate = translateMatch[1].split(separator); } var rotateMatch = transform.match(/rotate\((.*)\)/); if (rotateMatch) { rotate = rotateMatch[1].split(separator); } var scaleMatch = transform.match(/scale\((.*)\)/); if (scaleMatch) { scale = scaleMatch[1].split(separator); } } var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1; return { translate: { tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0, ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0 }, rotate: { angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0, cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined, cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined }, scale: { sx: sx, sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx } }; }; V.deltaTransformPoint = function(matrix, point) { var dx = point.x * matrix.a + point.y * matrix.c + 0; var dy = point.x * matrix.b + point.y * matrix.d + 0; return { x: dx, y: dy }; }; V.decomposeMatrix = function(matrix) { // @see https://gist.github.com/2052247 // calculate delta transform point var px = V.deltaTransformPoint(matrix, { x: 0, y: 1 }); var py = V.deltaTransformPoint(matrix, { x: 1, y: 0 }); // calculate skew var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90); var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x)); return { translateX: matrix.e, translateY: matrix.f, scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b), scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d), skewX: skewX, skewY: skewY, rotation: skewX // rotation is the same as skew x }; }; V.isV = function(object) { return object instanceof V; }; // For backwards compatibility: V.isVElement = V.isV; var svgDocument = V('svg').node; V.createSVGMatrix = function(matrix) { var svgMatrix = svgDocument.createSVGMatrix(); for (var component in matrix) { svgMatrix[component] = matrix[component]; } return svgMatrix; }; V.createSVGTransform = function(matrix) { if (!V.isUndefined(matrix)) { if (!(matrix instanceof SVGMatrix)) { matrix = V.createSVGMatrix(matrix); } return svgDocument.createSVGTransformFromMatrix(matrix); } return svgDocument.createSVGTransform(); }; V.createSVGPoint = function(x, y) { var p = svgDocument.createSVGPoint(); p.x = x; p.y = y; return p; }; V.transformRect = function(r, matrix) { var p = svgDocument.createSVGPoint(); p.x = r.x; p.y = r.y; var corner1 = p.matrixTransform(matrix); p.x = r.x + r.width; p.y = r.y; var corner2 = p.matrixTransform(matrix); p.x = r.x + r.width; p.y = r.y + r.height; var corner3 = p.matrixTransform(matrix); p.x = r.x; p.y = r.y + r.height; var corner4 = p.matrixTransform(matrix); var minX = Math.min(corner1.x, corner2.x, corner3.x, corner4.x); var maxX = Math.max(corner1.x, corner2.x, corner3.x, corner4.x); var minY = Math.min(corner1.y, corner2.y, corner3.y, corner4.y); var maxY = Math.max(corner1.y, corner2.y, corner3.y, corner4.y); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }; V.transformPoint = function(p, matrix) { return V.createSVGPoint(p.x, p.y).matrixTransform(matrix); }; // Convert a style represented as string (e.g. `'fill="blue"; stroke="red"'`) to // an object (`{ fill: 'blue', stroke: 'red' }`). V.styleToObject = function(styleString) { var ret = {}; var styles = styleString.split(';'); for (var i = 0; i < styles.length; i++) { var style = styles[i]; var pair = style.split('='); ret[pair[0].trim()] = pair[1].trim(); } return ret; }; // Inspired by d3.js https://github.com/mbostock/d3/blob/master/src/svg/arc.js V.createSlicePathData = function(innerRadius, outerRadius, startAngle, endAngle) { var svgArcMax = 2 * Math.PI - 1e-6; var r0 = innerRadius; var r1 = outerRadius; var a0 = startAngle; var a1 = endAngle; var da = (a1 < a0 && (da = a0, a0 = a1, a1 = da), a1 - a0); var df = da < Math.PI ? '0' : '1'; var c0 = Math.cos(a0); var s0 = Math.sin(a0); var c1 = Math.cos(a1); var s1 = Math.sin(a1); return (da >= svgArcMax) ? (r0 ? 'M0,' + r1 + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + (-r1) + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + r1 + 'M0,' + r0 + 'A' + r0 + ',' + r0 + ' 0 1,0 0,' + (-r0) + 'A' + r0 + ',' + r0 + ' 0 1,0 0,' + r0 + 'Z' : 'M0,' + r1 + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + (-r1) + 'A' + r1 + ',' + r1 + ' 0 1,1 0,' + r1 + 'Z') : (r0 ? 'M' + r1 * c0 + ',' + r1 * s0 + 'A' + r1 + ',' + r1 + ' 0 ' + df + ',1 ' + r1 * c1 + ',' + r1 * s1 + 'L' + r0 * c1 + ',' + r0 * s1 + 'A' + r0 + ',' + r0 + ' 0 ' + df + ',0 ' + r0 * c0 + ',' + r0 * s0 + 'Z' : 'M' + r1 * c0 + ',' + r1 * s0 + 'A' + r1 + ',' + r1 + ' 0 ' + df + ',1 ' + r1 * c1 + ',' + r1 * s1 + 'L0,0' + 'Z'); }; // Merge attributes from object `b` with attributes in object `a`. // Note that this modifies the object `a`. // Also important to note that attributes are merged but CSS classes are concatenated. V.mergeAttrs = function(a, b) { for (var attr in b) { if (attr === 'class') { // Concatenate classes. a[attr] = a[attr] ? a[attr] + ' ' + b[attr] : b[attr]; } else if (attr === 'style') { // `style` attribute can be an object. if (V.isObject(a[attr]) && V.isObject(b[attr])) { // `style` stored in `a` is an object. a[attr] = V.mergeAttrs(a[attr], b[attr]); } else if (V.isObject(a[attr])) { // `style` in `a` is an object but it's a string in `b`. // Convert the style represented as a string to an object in `b`. a[attr] = V.mergeAttrs(a[attr], V.styleToObject(b[attr])); } else if (V.isObject(b[attr])) { // `style` in `a` is a string, in `b` it's an object. a[attr] = V.mergeAttrs(V.styleToObject(a[attr]), b[attr]); } else { // Both styles are strings. a[attr] = V.mergeAttrs(V.styleToObject(a[attr]), V.styleToObject(b[attr])); } } else { a[attr] = b[attr]; } } return a; }; V.annotateString = function(t, annotations, opt) { annotations = annotations || []; opt = opt || {}; var offset = opt.offset || 0; var compacted = []; var batch; var ret = []; var item; var prev; for (var i = 0; i < t.length; i++) { item = ret[i] = t[i]; for (var j = 0; j < annotations.length; j++) { var annotation = annotations[j]; var start = annotation.start + offset; var end = annotation.end + offset; if (i >= start && i < end) { // Annotation applies. if (V.isObject(item)) { // There is more than one annotation to be applied => Merge attributes. item.attrs = V.mergeAttrs(V.mergeAttrs({}, item.attrs), annotation.attrs); } else { item = ret[i] = { t: t[i], attrs: annotation.attrs }; } if (opt.includeAnnotationIndices) { (item.annotations || (item.annotations = [])).push(j); } } } prev = ret[i - 1]; if (!prev) { batch = item; } else if (V.isObject(item) && V.isObject(prev)) { // Both previous item and the current one are annotations. If the attributes // didn't change, merge the text. if (JSON.stringify(item.attrs) === JSON.stringify(prev.attrs)) { batch.t += item.t; } else { compacted.push(batch); batch = item; } } else if (V.isObject(item)) { // Previous item was a string, current item is an annotation. compacted.push(batch); batch = item; } else if (V.isObject(prev)) { // Previous item was an annotation, current item is a string. compacted.push(batch); batch = item; } else { // Both previous and current item are strings. batch = (batch || '') + item; } } if (batch) { compacted.push(batch); } return compacted; }; V.findAnnotationsAtIndex = function(annotations, index) { var found = []; if (annotations) { annotations.forEach(function(annotation) { if (annotation.start < index && index <= annotation.end) { found.push(annotation); } }); } return found; }; V.findAnnotationsBetweenIndexes = function(annotations, start, end) { var found = []; if (annotations) { annotations.forEach(function(annotation) { if ((start >= annotation.start && start < annotation.end) || (end > annotation.start && end <= annotation.end) || (annotation.start >= start && annotation.end < end)) { found.push(annotation); } }); } return found; }; // Shift all the text annotations after character `index` by `offset` positions. V.shiftAnnotations = function(annotations, index, offset) { if (annotations) { annotations.forEach(function(annotation) { if (annotation.start < index && annotation.end >= index) { annotation.end += offset; } else if (annotation.start >= index) { annotation.start += offset; annotation.end += offset; } }); } return annotations; }; V.convertLineToPathData = function(line) { line = V(line); var d = [ 'M', line.attr('x1'), line.attr('y1'), 'L', line.attr('x2'), line.attr('y2') ].join(' '); return d; }; V.convertPolygonToPathData = function(polygon) { polygon = V(polygon); var points = V.getPointsFromSvgNode(polygon.node); if (!(points.length > 0)) return null; return V.svgPointsToPath(points); }; V.convertPolylineToPathData = function(polyline) { var points = V.getPointsFromSvgNode(polyline.node); if (!(points.length > 0)) return null; return V.svgPointsToPath(points); }; V.svgPointsToPath = function(points) { var i; for (i = 0; i < points.length; i++) { points[i] = points[i].x + ' ' + points[i].y; } return 'M ' + points.join(' L') + ' Z'; }; V.getPointsFromSvgNode = function(node) { var points = []; var i; for (i = 0; i < node.points.numberOfItems; i++) { points.push(node.points.getItem(i)); } return points; }; V.KAPPA = 0.5522847498307935; V.convertCircleToPathData = function(circle) { circle = V(circle); var cx = parseFloat(circle.attr('cx')) || 0; var cy = parseFloat(circle.attr('cy')) || 0; var r = parseFloat(circle.attr('r')); var cd = r * V.KAPPA; // Control distance. var d = [ 'M', cx, cy - r, // Move to the first point. 'C', cx + cd, cy - r, cx + r, cy - cd, cx + r, cy, // I. Quadrant. 'C', cx + r, cy + cd, cx + cd, cy + r, cx, cy + r, // II. Quadrant. 'C', cx - cd, cy + r, cx - r, cy + cd, cx - r, cy, // III. Quadrant. 'C', cx - r, cy - cd, cx - cd, cy - r, cx, cy - r, // IV. Quadrant. 'Z' ].join(' '); return d; }; V.convertEllipseToPathData = function(ellipse) { ellipse = V(ellipse); var cx = parseFloat(ellipse.attr('cx')) || 0; var cy = parseFloat(ellipse.attr('cy')) || 0; var rx = parseFloat(ellipse.attr('rx')); var ry = parseFloat(ellipse.attr('ry')) || rx; var cdx = rx * V.KAPPA; // Control distance x. var cdy = ry * V.KAPPA; // Control distance y. var d = [ 'M', cx, cy - ry, // Move to the first point. 'C', cx + cdx, cy - ry, cx + rx, cy - cdy, cx + rx, cy, // I. Quadrant. 'C', cx + rx, cy + cdy, cx + cdx, cy + ry, cx, cy + ry, // II. Quadrant. 'C', cx - cdx, cy + ry, cx - rx, cy + cdy, cx - rx, cy, // III. Quadrant. 'C', cx - rx, cy - cdy, cx - cdx, cy - ry, cx, cy - ry, // IV. Quadrant. 'Z' ].join(' '); return d; }; V.convertRectToPathData = function(rect) { rect = V(rect); var x = parseFloat(rect.attr('x')) || 0; var y = parseFloat(rect.attr('y')) || 0; var width = parseFloat(rect.attr('width')) || 0; var height = parseFloat(rect.attr('height')) || 0; var rx = parseFloat(rect.attr('rx')) || 0; var ry = parseFloat(rect.attr('ry')) || 0; var bbox = g.rect(x, y, width, height); var d; if (!rx && !ry) { d = [ 'M', bbox.origin().x, bbox.origin().y, 'H', bbox.corner().x, 'V', bbox.corner().y, 'H', bbox.origin().x, 'V', bbox.origin().y, 'Z' ].join(' '); } else { var r = x + width; var b = y + height; d = [ 'M', x + rx, y, 'L', r - rx, y, 'Q', r, y, r, y + ry, 'L', r, y + height - ry, 'Q', r, b, r - rx, b, 'L', x + rx, b, 'Q', x, b, x, b - rx, 'L', x, y + ry, 'Q', x, y, x + rx, y, 'Z' ].join(' '); } return d; }; // Convert a rectangle to SVG path commands. `r` is an object of the form: // `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`, // where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for // specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle // that has only `rx` and `ry` attributes). V.rectToPath = function(r) { var topRx = r.rx || r['top-rx'] || 0; var bottomRx = r.rx || r['bottom-rx'] || 0; var topRy = r.ry || r['top-ry'] || 0; var bottomRy = r.ry || r['bottom-ry'] || 0; return [ 'M', r.x, r.y + topRy, 'v', r.height - topRy - bottomRy, 'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy, 'h', r.width - 2 * bottomRx, 'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy, 'v', -(r.height - bottomRy - topRy), 'a', topRx, topRy, 0, 0, 0, -topRx, -topRy, 'h', -(r.width - 2 * topRx), 'a', topRx, topRy, 0, 0, 0, -topRx, topRy ].join(' '); }; V.toNode = function(el) { return V.isV(el) ? el.node : (el.nodeName && el || el[0]); }; return V; })(); // JointJS library. // (c) 2011-2015 client IO // Global namespace. var joint = { version: '0.9.10', config: { // The class name prefix config is for advanced use only. // Be aware that if you change the prefix, the JointJS CSS will no longer function properly. classNamePrefix: 'joint-', defaultTheme: 'default' }, // `joint.dia` namespace. dia: {}, // `joint.ui` namespace. ui: {}, // `joint.layout` namespace. layout: {}, // `joint.shapes` namespace. shapes: {}, // `joint.format` namespace. format: {}, // `joint.connectors` namespace. connectors: {}, // `joint.highlighters` namespace. highlighters: {}, // `joint.routers` namespace. routers: {}, // `joint.mvc` namespace. mvc: { views: {} }, setTheme: function(theme, opt) { opt = opt || {}; _.invoke(joint.mvc.views, 'setTheme', theme, opt); // Update the default theme on the view prototype. joint.mvc.View.prototype.defaultTheme = theme; }, // `joint.env` namespace. env: { _results: {}, _tests: { svgforeignobject: function() { return !!document.createElementNS && /SVGForeignObject/.test(({}).toString.call(document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject'))); } }, addTest: function(name, fn) { return joint.env._tests[name] = fn; }, test: function(name) { var fn = joint.env._tests[name]; if (!fn) { throw new Error('Test not defined ("' + name + '"). Use `joint.env.addTest(name, fn) to add a new test.`'); } var result = joint.env._results[name]; if (typeof result !== 'undefined') { return result; } try { result = fn(); } catch (error) { result = false; } // Cache the test result. joint.env._results[name] = result; return result; } }, util: { // Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/. hashCode: function(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); hash = ((hash << 5) - hash) + c; hash = hash & hash; // Convert to 32bit integer } return hash; }, getByPath: function(obj, path, delim) { delim = delim || '/'; var keys = path.split(delim); var key; while (keys.length) { key = keys.shift(); if (Object(obj) === obj && key in obj) { obj = obj[key]; } else { return undefined; } } return obj; }, setByPath: function(obj, path, value, delim) { delim = delim || '/'; var keys = path.split(delim); var diver = obj; var i = 0; if (path.indexOf(delim) > -1) { for (var len = keys.length; i < len - 1; i++) { // diver creates an empty object if there is no nested object under such a key. // This means that one can populate an empty nested object with setByPath(). diver = diver[keys[i]] || (diver[keys[i]] = {}); } diver[keys[len - 1]] = value; } else { obj[path] = value; } return obj; }, unsetByPath: function(obj, path, delim) { delim = delim || '/'; // index of the last delimiter var i = path.lastIndexOf(delim); if (i > -1) { // unsetting a nested attribute var parent = joint.util.getByPath(obj, path.substr(0, i), delim); if (parent) { delete parent[path.slice(i + 1)]; } } else { // unsetting a primitive attribute delete obj[path]; } return obj; }, flattenObject: function(obj, delim, stop) { delim = delim || '/'; var ret = {}; for (var key in obj) { if (!obj.hasOwnProperty(key)) continue; var shouldGoDeeper = typeof obj[key] === 'object'; if (shouldGoDeeper && stop && stop(obj[key])) { shouldGoDeeper = false; } if (shouldGoDeeper) { var flatObject = this.flattenObject(obj[key], delim, stop); for (var flatKey in flatObject) { if (!flatObject.hasOwnProperty(flatKey)) continue; ret[key + delim + flatKey] = flatObject[flatKey]; } } else { ret[key] = obj[key]; } } return ret; }, uuid: function() { // credit: http://stackoverflow.com/posts/2117523/revisions return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16|0; var v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }, // Generate global unique id for obj and store it as a property of the object. guid: function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }, // Copy all the properties to the first argument from the following arguments. // All the properties will be overwritten by the properties from the following // arguments. Inherited properties are ignored. mixin: function() { var target = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var extension = arguments[i]; // Only functions and objects can be mixined. if ((Object(extension) !== extension) && !_.isFunction(extension) && (extension === null || extension === undefined)) { continue; } _.each(extension, function(copy, key) { if (this.mixin.deep && (Object(copy) === copy)) { if (!target[key]) { target[key] = _.isArray(copy) ? [] : {}; } this.mixin(target[key], copy); return; } if (target[key] !== copy) { if (!this.mixin.supplement || !target.hasOwnProperty(key)) { target[key] = copy; } } }, this); } return target; }, // Copy all properties to the first argument from the following // arguments only in case if they don't exists in the first argument. // All the function propererties in the first argument will get // additional property base pointing to the extenders same named // property function's call method. supplement: function() { this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.supplement = false; return ret; }, // Same as `mixin()` but deep version. deepMixin: function() { this.mixin.deep = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = false; return ret; }, // Same as `supplement()` but deep version. deepSupplement: function() { this.mixin.deep = this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = this.mixin.supplement = false; return ret; }, normalizeEvent: function(evt) { var touchEvt = evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches[0]; if (touchEvt) { for (var property in evt) { // copy all the properties from the input event that are not // defined on the touch event (functions included). if (touchEvt[property] === undefined) { touchEvt[property] = evt[property]; } } return touchEvt; } return evt; }, nextFrame: (function() { var raf; if (typeof window !== 'undefined') { raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; } if (!raf) { var lastTime = 0; raf = function(callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } return function(callback, context) { return context ? raf(_.bind(callback, context)) : raf(callback); }; })(), cancelFrame: (function() { var caf; var client = typeof window != 'undefined'; if (client) { caf = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame; } caf = caf || clearTimeout; return client ? _.bind(caf, window) : caf; })(), shapePerimeterConnectionPoint: function(linkView, view, magnet, reference) { var bbox; var spot; if (!magnet) { // There is no magnet, try to make the best guess what is the // wrapping SVG element. This is because we want this "smart" // connection points to work out of the box without the // programmer to put magnet marks to any of the subelements. // For example, we want the functoin to work on basic.Path elements // without any special treatment of such elements. // The code below guesses the wrapping element based on // one simple assumption. The wrapping elemnet is the // first child of the scalable group if such a group exists // or the first child of the rotatable group if not. // This makese sense because usually the wrapping element // is below any other sub element in the shapes. var scalable = view.$('.scalable')[0]; var rotatable = view.$('.rotatable')[0]; if (scalable && scalable.firstChild) { magnet = scalable.firstChild; } else if (rotatable && rotatable.firstChild) { magnet = rotatable.firstChild; } } if (magnet) { spot = V(magnet).findIntersection(reference, linkView.paper.viewport); if (!spot) { bbox = g.rect(V(magnet).bbox(false, linkView.paper.viewport)); } } else { bbox = view.model.getBBox(); spot = bbox.intersectionWithLineFromCenterToPoint(reference); } return spot || bbox.center(); }, breakText: function(text, size, styles, opt) { opt = opt || {}; var width = size.width; var height = size.height; var svgDocument = opt.svgDocument || V('svg').node; var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node; var textSpan = textElement.firstChild; var textNode = document.createTextNode(''); // Prevent flickering textElement.style.opacity = 0; // Prevent FF from throwing an uncaught exception when `getBBox()` // called on element that is not in the render tree (is not measurable). // <tspan>.getComputedTextLength() returns always 0 in this case. // Note that the `textElement` resp. `textSpan` can become hidden // when it's appended to the DOM and a `display: none` CSS stylesheet // rule gets applied. textElement.style.display = 'block'; textSpan.style.display = 'block'; textSpan.appendChild(textNode); svgDocument.appendChild(textElement); if (!opt.svgDocument) { document.body.appendChild(svgDocument); } var words = text.split(' '); var full = []; var lines = []; var p; for (var i = 0, l = 0, len = words.length; i < len; i++) { var word = words[i]; textNode.data = lines[l] ? lines[l] + ' ' + word : word; if (textSpan.getComputedTextLength() <= width) { // the current line fits lines[l] = textNode.data; if (p) { // We were partitioning. Put rest of the word onto next line full[l++] = true; // cancel partitioning p = 0; } } else { if (!lines[l] || p) { var partition = !!p; p = word.length - 1; if (partition || !p) { // word has only one character. if (!p) { if (!lines[l]) { // we won't fit this text within our rect lines = []; break; } // partitioning didn't help on the non-empty line // try again, but this time start with a new line // cancel partitions created words.splice(i, 2, word + words[i + 1]); // adjust word length len--; full[l++] = true; i--; continue; } // move last letter to the beginning of the next word words[i] = word.substring(0, p); words[i + 1] = word.substring(p) + words[i + 1]; } else { // We initiate partitioning // split the long word into two words words.splice(i, 1, word.substring(0, p), word.substring(p)); // adjust words length len++; if (l && !full[l - 1]) { // if the previous line is not full, try to fit max part of // the current word there l--; } } i--; continue; } l++; i--; } // if size.height is defined we have to check whether the height of the entire // text exceeds the rect height if (typeof height !== 'undefined') { // get line height as text height / 0.8 (as text height is approx. 0.8em // and line height is 1em. See vectorizer.text()) var lh = lh || textElement.getBBox().height * 1.25; if (lh * lines.length > height) { // remove overflowing lines lines.splice(Math.floor(height / lh)); break; } } } if (opt.svgDocument) { // svg document was provided, remove the text element only svgDocument.removeChild(textElement); } else { // clean svg document document.body.removeChild(svgDocument); } return lines.join('\n'); }, imageToDataUri: function(url, callback) { if (!url || url.substr(0, 'data:'.length) === 'data:') { // No need to convert to data uri if it is already in data uri. // This not only convenient but desired. For example, // IE throws a security error if data:image/svg+xml is used to render // an image to the canvas and an attempt is made to read out data uri. // Now if our image is already in data uri, there is no need to render it to the canvas // and so we can bypass this error. // Keep the async nature of the function. return setTimeout(function() { callback(null, url); }, 0); } var canvas = document.createElement('canvas'); var img = document.createElement('img'); img.onload = function() { var ctx = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); try { // Guess the type of the image from the url suffix. var suffix = (url.split('.').pop()) || 'png'; // A little correction for JPEGs. There is no image/jpg mime type but image/jpeg. var type = 'image/' + (suffix === 'jpg') ? 'jpeg' : suffix; var dataUri = canvas.toDataURL(type); } catch (e) { if (/\.svg$/.test(url)) { // IE throws a security error if we try to render an SVG into the canvas. // Luckily for us, we don't need canvas at all to convert // SVG to data uri. We can just use AJAX to load the SVG string // and construct the data uri ourselves. var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject('Microsoft.XMLHTTP'); xhr.open('GET', url, false); xhr.send(null); var svg = xhr.responseText; return callback(null, 'data:image/svg+xml,' + encodeURIComponent(svg)); } console.error(img.src, 'fails to convert', e); } callback(null, dataUri); }; img.ononerror = function() { callback(new Error('Failed to load image.')); }; img.src = url; }, getElementBBox: function(el) { var $el = $(el); var offset = $el.offset(); var bbox; if (el.ownerSVGElement) { // Use Vectorizer to get the dimensions of the element if it is an SVG element. bbox = V(el).bbox(); // getBoundingClientRect() used in jQuery.fn.offset() takes into account `stroke-width` // in Firefox only. So clientRect width/height and getBBox width/height in FF don't match. // To unify this across all browsers we add the `stroke-width` (left & top) back to // the calculated offset. var crect = el.getBoundingClientRect(); var strokeWidthX = (crect.width - bbox.width) / 2; var strokeWidthY = (crect.height - bbox.height) / 2; // The `bbox()` returns coordinates relative to the SVG viewport, therefore, use the // ones returned from the `offset()` method that are relative to the document. bbox.x = offset.left + strokeWidthX; bbox.y = offset.top + strokeWidthY; } else { bbox = { x: offset.left, y: offset.top, width: $el.outerWidth(), height: $el.outerHeight() }; } return bbox; }, // Highly inspired by the jquery.sortElements plugin by Padolsey. // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/. sortElements: function(elements, comparator) { var $elements = $(elements); var placements = $elements.map(function() { var sortElement = this; var parentNode = sortElement.parentNode; // Since the element itself will change position, we have // to have some way of storing it's original position in // the DOM. The easiest way is to have a 'flag' node: var nextSibling = parentNode.insertBefore(document.createTextNode(''), sortElement.nextSibling); return function() { if (parentNode === this) { throw new Error('You can\'t sort elements if any one is a descendant of another.'); } // Insert before flag: parentNode.insertBefore(this, nextSibling); // Remove flag: parentNode.removeChild(nextSibling); }; }); return Array.prototype.sort.call($elements, comparator).each(function(i) { placements[i].call(this); }); }, // Sets attributes on the given element and its descendants based on the selector. // `attrs` object: { [SELECTOR1]: { attrs1 }, [SELECTOR2]: { attrs2}, ... } e.g. { 'input': { color : 'red' }} setAttributesBySelector: function(element, attrs) { var $element = $(element); _.each(attrs, function(attrs, selector) { var $elements = $element.find(selector).addBack().filter(selector); // Make a special case for setting classes. // We do not want to overwrite any existing class. if (_.has(attrs, 'class')) { $elements.addClass(attrs['class']); attrs = _.omit(attrs, 'class'); } $elements.attr(attrs); }); }, // Return a new object with all for sides (top, bottom, left and right) in it. // Value of each side is taken from the given argument (either number or object). // Default value for a side is 0. // Examples: // joint.util.normalizeSides(5) --> { top: 5, left: 5, right: 5, bottom: 5 } // joint.util.normalizeSides({ left: 5 }) --> { top: 0, left: 5, right: 0, bottom: 0 } normalizeSides: function(box) { if (Object(box) !== box) { box = box || 0; return { top: box, bottom: box, left: box, right: box }; } return { top: box.top || 0, bottom: box.bottom || 0, left: box.left || 0, right: box.right || 0 }; }, timing: { linear: function(t) { return t; }, quad: function(t) { return t * t; }, cubic: function(t) { return t * t * t; }, inout: function(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t; var t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); }, exponential: function(t) { return Math.pow(2, 10 * (t - 1)); }, bounce: function(t) { for (var a = 0, b = 1; 1; a += b, b /= 2) { if (t >= (7 - 4 * a) / 11) { var q = (11 - 6 * a - 11 * t) / 4; return -q * q + b * b; } } }, reverse: function(f) { return function(t) { return 1 - f(1 - t); }; }, reflect: function(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t))); }; }, clamp: function(f, n, x) { n = n || 0; x = x || 1; return function(t) { var r = f(t); return r < n ? n : r > x ? x : r; }; }, back: function(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; }, elastic: function(x) { if (!x) x = 1.5; return function(t) { return Math.pow(2, 10 * (t - 1)) * Math.cos(20 * Math.PI * x / 3 * t); }; } }, interpolate: { number: function(a, b) { var d = b - a; return function(t) { return a + d * t; }; }, object: function(a, b) { var s = _.keys(a); return function(t) { var i, p; var r = {}; for (i = s.length - 1; i != -1; i--) { p = s[i]; r[p] = a[p] + (b[p] - a[p]) * t; } return r; }; }, hexColor: function(a, b) { var ca = parseInt(a.slice(1), 16); var cb = parseInt(b.slice(1), 16); var ra = ca & 0x0000ff; var rd = (cb & 0x0000ff) - ra; var ga = ca & 0x00ff00; var gd = (cb & 0x00ff00) - ga; var ba = ca & 0xff0000; var bd = (cb & 0xff0000) - ba; return function(t) { var r = (ra + rd * t) & 0x000000ff; var g = (ga + gd * t) & 0x0000ff00; var b = (ba + bd * t) & 0x00ff0000; return '#' + (1 << 24 | r | g | b ).toString(16).slice(1); }; }, unit: function(a, b) { var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/; var ma = r.exec(a); var mb = r.exec(b); var p = mb[1].indexOf('.'); var f = p > 0 ? mb[1].length - p - 1 : 0; a = +ma[1]; var d = +mb[1] - a; var u = ma[2]; return function(t) { return (a + d * t).toFixed(f) + u; }; } }, // SVG filters. filter: { // `color` ... outline color // `width`... outline width // `opacity` ... outline opacity // `margin` ... gap between outline and the element outline: function(args) { var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology in="SourceAlpha" result="morphedOuter" operator="dilate" radius="${outerRadius}" /><feMorphology in="SourceAlpha" result="morphedInner" operator="dilate" radius="${innerRadius}" /><feComposite result="morphedOuterColored" in="colored" in2="morphedOuter" operator="in"/><feComposite operator="xor" in="morphedOuterColored" in2="morphedInner" result="outline"/><feMerge><feMergeNode in="outline"/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; var margin = _.isFinite(args.margin) ? args.margin : 2; var width = _.isFinite(args.width) ? args.width : 1; return joint.util.template(tpl)({ color: args.color || 'blue', opacity: _.isFinite(args.opacity) ? args.opacity : 1, outerRadius: margin + width, innerRadius: margin }); }, // `color` ... color // `width`... width // `blur` ... blur // `opacity` ... opacity highlight: function(args) { var tpl = '<filter><feFlood flood-color="${color}" flood-opacity="${opacity}" result="colored"/><feMorphology result="morphed" in="SourceGraphic" operator="dilate" radius="${width}"/><feComposite result="composed" in="colored" in2="morphed" operator="in"/><feGaussianBlur result="blured" in="composed" stdDeviation="${blur}"/><feBlend in="SourceGraphic" in2="blured" mode="normal"/></filter>'; return joint.util.template(tpl)({ color: args.color || 'red', width: _.isFinite(args.width) ? args.width : 1, blur: _.isFinite(args.blur) ? args.blur : 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1 }); }, // `x` ... horizontal blur // `y` ... vertical blur (optional) blur: function(args) { var x = _.isFinite(args.x) ? args.x : 2; return joint.util.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>')({ stdDeviation: _.isFinite(args.y) ? [x, args.y] : x }); }, // `dx` ... horizontal shift // `dy` ... vertical shift // `blur` ... blur // `color` ... color // `opacity` ... opacity dropShadow: function(args) { var tpl = 'SVGFEDropShadowElement' in window ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>' : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; return joint.util.template(tpl)({ dx: args.dx || 0, dy: args.dy || 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1, color: args.color || 'black', blur: _.isFinite(args.blur) ? args.blur : 4 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged. grayscale: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return joint.util.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>')({ a: 0.2126 + 0.7874 * (1 - amount), b: 0.7152 - 0.7152 * (1 - amount), c: 0.0722 - 0.0722 * (1 - amount), d: 0.2126 - 0.2126 * (1 - amount), e: 0.7152 + 0.2848 * (1 - amount), f: 0.0722 - 0.0722 * (1 - amount), g: 0.2126 - 0.2126 * (1 - amount), h: 0.0722 + 0.9278 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged. sepia: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return joint.util.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>')({ a: 0.393 + 0.607 * (1 - amount), b: 0.769 - 0.769 * (1 - amount), c: 0.189 - 0.189 * (1 - amount), d: 0.349 - 0.349 * (1 - amount), e: 0.686 + 0.314 * (1 - amount), f: 0.168 - 0.168 * (1 - amount), g: 0.272 - 0.272 * (1 - amount), h: 0.534 - 0.534 * (1 - amount), i: 0.131 + 0.869 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged. saturate: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return joint.util.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>')({ amount: 1 - amount }); }, // `angle` ... the number of degrees around the color circle the input samples will be adjusted. hueRotate: function(args) { return joint.util.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>')({ angle: args.angle || 0 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged. invert: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return joint.util.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>')({ amount: amount, amount2: 1 - amount }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. brightness: function(args) { return joint.util.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>')({ amount: _.isFinite(args.amount) ? args.amount : 1 }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. contrast: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return joint.util.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>')({ amount: amount, amount2: .5 - amount / 2 }); } }, format: { // Formatting numbers via the Python Format Specification Mini-language. // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // Heavilly inspired by the D3.js library implementation. number: function(specifier, value, locale) { locale = locale || { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3] }; // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // [[fill]align][sign][symbol][0][width][,][.precision][type] var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var match = re.exec(specifier); var fill = match[1] || ' '; var align = match[2] || '>'; var sign = match[3] || ''; var symbol = match[4] || ''; var zfill = match[5]; var width = +match[6]; var comma = match[7]; var precision = match[8]; var type = match[9]; var scale = 1; var prefix = ''; var suffix = ''; var integer = false; if (precision) precision = +precision.substring(1); if (zfill || fill === '0' && align === '=') { zfill = fill = '0'; align = '='; if (comma) width -= Math.floor((width - 1) / 4); } switch (type) { case 'n': comma = true; type = 'g'; break; case '%': scale = 100; suffix = '%'; type = 'f'; break; case 'p': scale = 100; suffix = '%'; type = 'r'; break; case 'b': case 'o': case 'x': case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase(); case 'c': case 'd': integer = true; precision = 0; break; case 's': scale = -1; type = 'r'; break; } if (symbol === '$') { prefix = locale.currency[0]; suffix = locale.currency[1]; } // If no precision is specified for `'r'`, fallback to general notation. if (type == 'r' && !precision) type = 'g'; // Ensure that the requested precision is in the supported range. if (precision != null) { if (type == 'g') precision = Math.max(1, Math.min(21, precision)); else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision)); } var zcomma = zfill && comma; // Return the empty string for floats formatted as ints. if (integer && (value % 1)) return ''; // Convert negative to positive, and record the sign prefix. var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign; var fullSuffix = suffix; // Apply the scale, computing it from the value's exponent for si format. // Preserve the existing suffix, if any, such as the currency symbol. if (scale < 0) { var unit = this.prefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } // Convert to the desired precision. value = this.convert(type, value, precision); // Break the value into the integer part (before) and decimal part (after). var i = value.lastIndexOf('.'); var before = i < 0 ? value : value.substring(0, i); var after = i < 0 ? '' : locale.decimal + value.substring(i + 1); function formatGroup(value) { var i = value.length; var t = []; var j = 0; var g = locale.grouping[0]; while (i > 0 && g > 0) { t.push(value.substring(i -= g, i + g)); g = locale.grouping[j = (j + 1) % locale.grouping.length]; } return t.reverse().join(locale.thousands); } // If the fill character is not `'0'`, grouping is applied before padding. if (!zfill && comma && locale.grouping) { before = formatGroup(before); } var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length); var padding = length < width ? new Array(length = width - length + 1).join(fill) : ''; // If the fill character is `'0'`, grouping is applied after padding. if (zcomma) before = formatGroup(padding + before); // Apply prefix. negative += prefix; // Rejoin integer and decimal parts. value = before + after; return (align === '<' ? negative + value + padding : align === '>' ? padding + negative + value : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }, // Formatting string via the Python Format string. // See https://docs.python.org/2/library/string.html#format-string-syntax) string: function(formatString, value) { var fieldDelimiterIndex; var fieldDelimiter = '{'; var endPlaceholder = false; var formattedStringArray = []; while ((fieldDelimiterIndex = formatString.indexOf(fieldDelimiter)) !== -1) { var pieceFormatedString, formatSpec, fieldName; pieceFormatedString = formatString.slice(0, fieldDelimiterIndex); if (endPlaceholder) { formatSpec = pieceFormatedString.split(':'); fieldName = formatSpec.shift().split('.'); pieceFormatedString = value; for (var i = 0; i < fieldName.length; i++) pieceFormatedString = pieceFormatedString[fieldName[i]]; if (formatSpec.length) pieceFormatedString = this.number(formatSpec, pieceFormatedString); } formattedStringArray.push(pieceFormatedString); formatString = formatString.slice(fieldDelimiterIndex + 1); fieldDelimiter = (endPlaceholder = !endPlaceholder) ? '}' : '{'; } formattedStringArray.push(formatString); return formattedStringArray.join(''); }, convert: function(type, value, precision) { switch (type) { case 'b': return value.toString(2); case 'c': return String.fromCharCode(value); case 'o': return value.toString(8); case 'x': return value.toString(16); case 'X': return value.toString(16).toUpperCase(); case 'g': return value.toPrecision(precision); case 'e': return value.toExponential(precision); case 'f': return value.toFixed(precision); case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision)))); default: return value + ''; } }, round: function(value, precision) { return precision ? Math.round(value * (precision = Math.pow(10, precision))) / precision : Math.round(value); }, precision: function(value, precision) { return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1); }, prefix: function(value, precision) { var prefixes = _.map(['y', 'z', 'a', 'f', 'p', 'n', 'µ', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], function(d, i) { var k = Math.pow(10, Math.abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; }); var i = 0; if (value) { if (value < 0) value *= -1; if (precision) value = this.round(value, this.precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); } return prefixes[8 + i / 3]; } }, /* Pre-compile the HTML to be used as a template. */ template: function(html) { /* Must support the variation in templating syntax found here: https://lodash.com/docs#template */ var regex = /<%= ([^ ]+) %>|\$\{ ?([^\{\} ]+) ?\}|\{\{([^\{\} ]+)\}\}/g; return function(data) { data = data || {}; return html.replace(regex, function(match) { var args = Array.prototype.slice.call(arguments); var attr = _.find(args.slice(1, 4), function(_attr) { return !!_attr; }); var attrArray = attr.split('.'); var value = data[attrArray.shift()]; while (!_.isUndefined(value) && attrArray.length) { value = value[attrArray.shift()]; } return !_.isUndefined(value) ? value : ''; }); }; }, /** * @param {Element=} el Element, which content is intent to display in full-screen mode, 'document.body' is default. */ toggleFullScreen: function(el) { el = el || document.body; function prefixedResult(el, prop) { var prefixes = ['webkit', 'moz', 'ms', 'o', '']; for (var i = 0; i < prefixes.length; i++) { var prefix = prefixes[i]; var propName = prefix ? (prefix + prop) : (prop.substr(0, 1).toLowerCase() + prop.substr(1)); if (!_.isUndefined(el[propName])) { return _.isFunction(el[propName]) ? el[propName]() : el[propName]; } } } if (prefixedResult(document, 'FullScreen') || prefixedResult(document, 'IsFullScreen')) { prefixedResult(document, 'CancelFullScreen'); } else { prefixedResult(el, 'RequestFullScreen'); } }, addClassNamePrefix: function(className) { if (!className) return className; return _.map(className.toString().split(' '), function(_className) { if (_className.substr(0, joint.config.classNamePrefix.length) !== joint.config.classNamePrefix) { _className = joint.config.classNamePrefix + _className; } return _className; }).join(' '); }, removeClassNamePrefix: function(className) { if (!className) return className; return _.map(className.toString().split(' '), function(_className) { if (_className.substr(0, joint.config.classNamePrefix.length) === joint.config.classNamePrefix) { _className = _className.substr(joint.config.classNamePrefix.length); } return _className; }).join(' '); }, wrapWith: function(object, methods, wrapper) { if (_.isString(wrapper)) { if (!joint.util.wrappers[wrapper]) { throw new Error('Unknown wrapper: "' + wrapper + '"'); } wrapper = joint.util.wrappers[wrapper]; } if (!_.isFunction(wrapper)) { throw new Error('Wrapper must be a function.'); } _.each(methods, function(method) { object[method] = wrapper(object[method]); }); }, wrappers: { /* Prepares a function with the following usage: fn([cell, cell, cell], opt); fn([cell, cell, cell]); fn(cell, cell, cell, opt); fn(cell, cell, cell); */ cells: function(fn) { return function() { var args = Array.prototype.slice.call(arguments); var cells = args.length > 0 && _.first(args) || []; var opt = args.length > 1 && _.last(args) || {}; if (!_.isArray(cells)) { if (opt instanceof joint.dia.Cell) { cells = args; opt = {}; } else { cells = _.initial(args); } } return fn.call(this, cells, opt); }; } } } }; // JointJS library. // (c) 2011-2015 client IO joint.mvc.View = Backbone.View.extend({ options: {}, theme: null, themeClassNamePrefix: joint.util.addClassNamePrefix('theme-'), requireSetThemeOverride: false, defaultTheme: joint.config.defaultTheme, constructor: function(options) { Backbone.View.call(this, options); }, initialize: function(options) { this.requireSetThemeOverride = options && !!options.theme; this.options = _.extend({}, this.options, options); _.bindAll(this, 'setTheme', 'onSetTheme', 'remove', 'onRemove'); joint.mvc.views[this.cid] = this; this.setTheme(this.options.theme || this.defaultTheme); this._ensureElClassName(); this.init(); }, _ensureElClassName: function() { var className = _.result(this, 'className'); var prefixedClassName = joint.util.addClassNamePrefix(className); this.$el.removeClass(className); this.$el.addClass(prefixedClassName); }, init: function() { // Intentionally empty. // This method is meant to be overriden. }, onRender: function() { // Intentionally empty. // This method is meant to be overriden. }, setTheme: function(theme, opt) { opt = opt || {}; // Theme is already set, override is required, and override has not been set. // Don't set the theme. if (this.theme && this.requireSetThemeOverride && !opt.override) return; this.removeThemeClassName(); this.addThemeClassName(theme); this.onSetTheme(this.theme/* oldTheme */, theme/* newTheme */); this.theme = theme; return this; }, addThemeClassName: function(theme) { theme = theme || this.theme; var className = this.themeClassNamePrefix + theme; this.$el.addClass(className); return this; }, removeThemeClassName: function(theme) { theme = theme || this.theme; var className = this.themeClassNamePrefix + theme; this.$el.removeClass(className); return this; }, onSetTheme: function(oldTheme, newTheme) { // Intentionally empty. // This method is meant to be overriden. }, remove: function() { this.onRemove(); joint.mvc.views[this.cid] = null; Backbone.View.prototype.remove.apply(this, arguments); return this; }, onRemove: function() { // Intentionally empty. // This method is meant to be overriden. } }); (function() { joint.mvc.View._extend = joint.mvc.View.extend; joint.mvc.View.extend = function(protoProps, staticProps) { protoProps = protoProps || {}; var render = protoProps.render || this.prototype.render || null; protoProps.render = function() { if (render) { // Call the original render method. render.apply(this, arguments); } // Should always call onRender() method. this.onRender(); // Should always return itself. return this; }; return joint.mvc.View._extend.call(this, protoProps, staticProps); }; })(); // JointJS, the JavaScript diagramming library. // (c) 2011-2015 client IO joint.dia.GraphCells = Backbone.Collection.extend({ cellNamespace: joint.shapes, initialize: function(models, opt) { // Set the optional namespace where all model classes are defined. if (opt.cellNamespace) { this.cellNamespace = opt.cellNamespace; } this.graph = opt.graph; }, model: function(attrs, options) { var collection = options.collection; var namespace = collection.cellNamespace; // Find the model class in the namespace or use the default one. var ModelClass = (attrs.type === 'link') ? joint.dia.Link : joint.util.getByPath(namespace, attrs.type, '.') || joint.dia.Element; var cell = new ModelClass(attrs, options); // Add a reference to the graph. It is necessary to do this here because this is the earliest place // where a new model is created from a plain JS object. For other objects, see `joint.dia.Graph>>_prepareCell()`. cell.graph = collection.graph; return cell; }, // `comparator` makes it easy to sort cells based on their `z` index. comparator: function(model) { return model.get('z') || 0; } }); joint.dia.Graph = Backbone.Model.extend({ _batches: {}, initialize: function(attrs, opt) { opt = opt || {}; // Passing `cellModel` function in the options object to graph allows for // setting models based on attribute objects. This is especially handy // when processing JSON graphs that are in a different than JointJS format. var cells = new joint.dia.GraphCells([], { model: opt.cellModel, cellNamespace: opt.cellNamespace, graph: this }); Backbone.Model.prototype.set.call(this, 'cells', cells); // Make all the events fired in the `cells` collection available. // to the outside world. cells.on('all', this.trigger, this); // Backbone automatically doesn't trigger re-sort if models attributes are changed later when // they're already in the collection. Therefore, we're triggering sort manually here. this.on('change:z', this._sortOnChangeZ, this); this.on('batch:stop', this._onBatchStop, this); // `joint.dia.Graph` keeps an internal data structure (an adjacency list) // for fast graph queries. All changes that affect the structure of the graph // must be reflected in the `al` object. This object provides fast answers to // questions such as "what are the neighbours of this node" or "what // are the sibling links of this link". // Outgoing edges per node. Note that we use a hash-table for the list // of outgoing edges for a faster lookup. // [node ID] -> Object [edge] -> true this._out = {}; // Ingoing edges per node. // [node ID] -> Object [edge] -> true this._in = {}; // `_nodes` is useful for quick lookup of all the elements in the graph, without // having to go through the whole cells array. // [node ID] -> true this._nodes = {}; // `_edges` is useful for quick lookup of all the links in the graph, without // having to go through the whole cells array. // [edge ID] -> true this._edges = {}; cells.on('add', this._restructureOnAdd, this); cells.on('remove', this._restructureOnRemove, this); cells.on('reset', this._restructureOnReset, this); cells.on('change:source', this._restructureOnChangeSource, this); cells.on('change:target', this._restructureOnChangeTarget, this); cells.on('remove', this._removeCell, this); }, _sortOnChangeZ: function() { if (!this.hasActiveBatch('to-front') && !this.hasActiveBatch('to-back')) { this.get('cells').sort(); } }, _onBatchStop: function(data) { var batchName = data && data.batchName; if ((batchName === 'to-front' || batchName === 'to-back') && !this.hasActiveBatch(batchName)) { this.get('cells').sort(); } }, _restructureOnAdd: function(cell) { if (cell.isLink()) { this._edges[cell.id] = true; var source = cell.get('source'); var target = cell.get('target'); if (source.id) { (this._out[source.id] || (this._out[source.id] = {}))[cell.id] = true; } if (target.id) { (this._in[target.id] || (this._in[target.id] = {}))[cell.id] = true; } } else { this._nodes[cell.id] = true; } }, _restructureOnRemove: function(cell) { if (cell.isLink()) { delete this._edges[cell.id]; var source = cell.get('source'); var target = cell.get('target'); if (source.id && this._out[source.id] && this._out[source.id][cell.id]) { delete this._out[source.id][cell.id]; } if (target.id && this._in[target.id] && this._in[target.id][cell.id]) { delete this._in[target.id][cell.id]; } } else { delete this._nodes[cell.id]; } }, _restructureOnReset: function(cells) { // Normalize into an array of cells. The original `cells` is GraphCells Backbone collection. cells = cells.models; this._out = {}; this._in = {}; this._nodes = {}; this._edges = {}; _.each(cells, this._restructureOnAdd, this); }, _restructureOnChangeSource: function(link) { var prevSource = link.previous('source'); if (prevSource.id && this._out[prevSource.id]) { delete this._out[prevSource.id][link.id]; } var source = link.get('source'); if (source.id) { (this._out[source.id] || (this._out[source.id] = {}))[link.id] = true; } }, _restructureOnChangeTarget: function(link) { var prevTarget = link.previous('target'); if (prevTarget.id && this._in[prevTarget.id]) { delete this._in[prevTarget.id][link.id]; } var target = link.get('target'); if (target.id) { (this._in[target.id] || (this._in[target.id] = {}))[link.id] = true; } }, // Return all outbound edges for the node. Return value is an object // of the form: [edge] -> true getOutboundEdges: function(node) { return (this._out && this._out[node]) || {}; }, // Return all inbound edges for the node. Return value is an object // of the form: [edge] -> true getInboundEdges: function(node) { return (this._in && this._in[node]) || {}; }, toJSON: function() { // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections. // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely. var json = Backbone.Model.prototype.toJSON.apply(this, arguments); json.cells = this.get('cells').toJSON(); return json; }, fromJSON: function(json, opt) { if (!json.cells) { throw new Error('Graph JSON must contain cells array.'); } return this.set(json, opt); }, set: function(key, val, opt) { var attrs; // Handle both `key`, value and {key: value} style arguments. if (typeof key === 'object') { attrs = key; opt = val; } else { (attrs = {})[key] = val; } // Make sure that `cells` attribute is handled separately via resetCells(). if (attrs.hasOwnProperty('cells')) { this.resetCells(attrs.cells, opt); attrs = _.omit(attrs, 'cells'); } // The rest of the attributes are applied via original set method. return Backbone.Model.prototype.set.call(this, attrs, opt); }, clear: function(opt) { opt = _.extend({}, opt, { clear: true }); var collection = this.get('cells'); if (collection.length === 0) return this; this.startBatch('clear', opt); // The elements come after the links. var cells = collection.sortBy(function(cell) { return cell.isLink() ? 1 : 2; }); do { // Remove all the cells one by one. // Note that all the links are removed first, so it's // safe to remove the elements without removing the connected // links first. cells.shift().remove(opt); } while (cells.length > 0); this.stopBatch('clear'); return this; }, _prepareCell: function(cell) { var attrs; if (cell instanceof Backbone.Model) { attrs = cell.attributes; cell.graph = this; } else { // In case we're dealing with a plain JS object, we have to set the reference // to the `graph` right after the actual model is created. This happens in the `model()` function // of `joint.dia.GraphCells`. attrs = cell; } if (!_.isString(attrs.type)) { throw new TypeError('dia.Graph: cell type must be a string.'); } return cell; }, maxZIndex: function() { var lastCell = this.get('cells').last(); return lastCell ? (lastCell.get('z') || 0) : 0; }, addCell: function(cell, options) { if (_.isArray(cell)) { return this.addCells(cell, options); } if (cell instanceof Backbone.Model) { if (!cell.has('z')) { cell.set('z', this.maxZIndex() + 1); } } else if (_.isUndefined(cell.z)) { cell.z = this.maxZIndex() + 1; } this.get('cells').add(this._prepareCell(cell), options || {}); return this; }, addCells: function(cells, opt) { if (cells.length) { opt.position = cells.length; this.startBatch('add'); _.each(cells, function(cell) { opt.position--; this.addCell(cell, opt); }, this); this.stopBatch('add'); } return this; }, // When adding a lot of cells, it is much more efficient to // reset the entire cells collection in one go. // Useful for bulk operations and optimizations. resetCells: function(cells, opt) { this.get('cells').reset(_.map(cells, this._prepareCell, this), opt); return this; }, removeCells: function(cells, opt) { if (cells.length) { this.startBatch('remove'); _.invoke(cells, 'remove', opt); this.stopBatch('remove'); } return this; }, _removeCell: function(cell, collection, options) { options = options || {}; if (!options.clear) { // Applications might provide a `disconnectLinks` option set to `true` in order to // disconnect links when a cell is removed rather then removing them. The default // is to remove all the associated links. if (options.disconnectLinks) { this.disconnectLinks(cell, options); } else { this.removeLinks(cell, options); } } // Silently remove the cell from the cells collection. Silently, because // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events // would be triggered on the graph model. this.get('cells').remove(cell, { silent: true }); delete cell.graph; }, // Get a cell by `id`. getCell: function(id) { return this.get('cells').get(id); }, getCells: function() { return this.get('cells').toArray(); }, getElements: function() { return _.map(this._nodes, function(exists, node) { return this.getCell(node); }, this); }, getLinks: function() { return _.map(this._edges, function(exists, edge) { return this.getCell(edge); }, this); }, getFirstCell: function() { return this.get('cells').first(); }, getLastCell: function() { return this.get('cells').last(); }, // Get all inbound and outbound links connected to the cell `model`. getConnectedLinks: function(model, opt) { opt = opt || {}; var inbound = opt.inbound; var outbound = opt.outbound; if (_.isUndefined(inbound) && _.isUndefined(outbound)) { inbound = outbound = true; } // The final array of connected link models. var links = []; // Connected edges. This hash table ([edge] -> true) serves only // for a quick lookup to check if we already added a link. var edges = {}; if (outbound) { _.each(this.getOutboundEdges(model.id), function(exists, edge) { if (!edges[edge]) { links.push(this.getCell(edge)); edges[edge] = true; } }, this); } if (inbound) { _.each(this.getInboundEdges(model.id), function(exists, edge) { // Skip links that were already added. Those must be self-loop links // because they are both inbound and outbond edges of the same element. if (!edges[edge]) { links.push(this.getCell(edge)); edges[edge] = true; } }, this); } // If 'deep' option is 'true', return all the links that are connected to any of the descendent cells // and are not descendents themselves. if (opt.deep) { var embeddedCells = model.getEmbeddedCells({ deep: true }); // In the first round, we collect all the embedded edges so that we can exclude // them from the final result. var embeddedEdges = {}; _.each(embeddedCells, function(cell) { if (cell.isLink()) { embeddedEdges[cell.id] = true; } }); _.each(embeddedCells, function(cell) { if (cell.isLink()) return; if (outbound) { _.each(this.getOutboundEdges(cell.id), function(exists, edge) { if (!edges[edge] && !embeddedEdges[edge]) { links.push(this.getCell(edge)); edges[edge] = true; } }, this); } if (inbound) { _.each(this.getInboundEdges(cell.id), function(exists, edge) { if (!edges[edge] && !embeddedEdges[edge]) { links.push(this.getCell(edge)); edges[edge] = true; } }, this); } }, this); } return links; }, getNeighbors: function(model, opt) { opt = opt || {}; var inbound = opt.inbound; var outbound = opt.outbound; if (_.isUndefined(inbound) && _.isUndefined(outbound)) { inbound = outbound = true; } var neighbors = _.transform(this.getConnectedLinks(model, opt), function(res, link) { var source = link.get('source'); var target = link.get('target'); var loop = link.hasLoop(opt); // Discard if it is a point, or if the neighbor was already added. if (inbound && _.has(source, 'id') && !res[source.id]) { var sourceElement = this.getCell(source.id); if (loop || (sourceElement && sourceElement !== model && (!opt.deep || !sourceElement.isEmbeddedIn(model)))) { res[source.id] = sourceElement; } } // Discard if it is a point, or if the neighbor was already added. if (outbound && _.has(target, 'id') && !res[target.id]) { var targetElement = this.getCell(target.id); if (loop || (targetElement && targetElement !== model && (!opt.deep || !targetElement.isEmbeddedIn(model)))) { res[target.id] = targetElement; } } }, {}, this); return _.values(neighbors); }, getCommonAncestor: function(/* cells */) { var cellsAncestors = _.map(arguments, function(cell) { var ancestors = []; var parentId = cell.get('parent'); while (parentId) { ancestors.push(parentId); parentId = this.getCell(parentId).get('parent'); } return ancestors; }, this); cellsAncestors = _.sortBy(cellsAncestors, 'length'); var commonAncestor = _.find(cellsAncestors.shift(), function(ancestor) { return _.every(cellsAncestors, function(cellAncestors) { return _.contains(cellAncestors, ancestor); }); }); return this.getCell(commonAncestor); }, // Find the whole branch starting at `element`. // If `opt.deep` is `true`, take into account embedded elements too. // If `opt.breadthFirst` is `true`, use the Breadth-first search algorithm, otherwise use Depth-first search. getSuccessors: function(element, opt) { opt = opt || {}; var res = []; // Modify the options so that it includes the `outbound` neighbors only. In other words, search forwards. this.search(element, function(el) { if (el !== element) { res.push(el); } }, _.extend({}, opt, { outbound: true })); return res; }, // Clone `cells` returning an object that maps the original cell ID to the clone. The number // of clones is exactly the same as the `cells.length`. // This function simply clones all the `cells`. However, it also reconstructs // all the `source/target` and `parent/embed` references within the `cells`. // This is the main difference from the `cell.clone()` method. The // `cell.clone()` method works on one single cell only. // For example, for a graph: `A --- L ---> B`, `cloneCells([A, L, B])` // returns `[A2, L2, B2]` resulting to a graph: `A2 --- L2 ---> B2`, i.e. // the source and target of the link `L2` is changed to point to `A2` and `B2`. cloneCells: function(cells) { cells = _.unique(cells); // A map of the form [original cell ID] -> [clone] helping // us to reconstruct references for source/target and parent/embeds. // This is also the returned value. var cloneMap = _.transform(cells, function(map, cell) { map[cell.id] = cell.clone(); }, {}); _.each(cells, function(cell) { var clone = cloneMap[cell.id]; // assert(clone exists) if (clone.isLink()) { var source = clone.get('source'); var target = clone.get('target'); if (source.id && cloneMap[source.id]) { // Source points to an element and the element is among the clones. // => Update the source of the cloned link. clone.prop('source/id', cloneMap[source.id].id); } if (target.id && cloneMap[target.id]) { // Target points to an element and the element is among the clones. // => Update the target of the cloned link. clone.prop('target/id', cloneMap[target.id].id); } } // Find the parent of the original cell var parent = cell.get('parent'); if (parent && cloneMap[parent]) { clone.set('parent', cloneMap[parent].id); } // Find the embeds of the original cell var embeds = _.reduce(cell.get('embeds'), function(newEmbeds, embed) { // Embedded cells that are not being cloned can not be carried // over with other embedded cells. if (cloneMap[embed]) { newEmbeds.push(cloneMap[embed].id); } return newEmbeds; }, []); if (!_.isEmpty(embeds)) { clone.set('embeds', embeds); } }); return cloneMap; }, // Clone the whole subgraph (including all the connected links whose source/target is in the subgraph). // If `opt.deep` is `true`, also take into account all the embedded cells of all the subgraph cells. // Return a map of the form: [original cell ID] -> [clone]. cloneSubgraph: function(cells, opt) { var subgraph = this.getSubgraph(cells, opt); return this.cloneCells(subgraph); }, // Return `cells` and all the connected links that connect cells in the `cells` array. // If `opt.deep` is `true`, return all the cells including all their embedded cells // and all the links that connect any of the returned cells. // For example, for a single shallow element, the result is that very same element. // For two elements connected with a link: `A --- L ---> B`, the result for // `getSubgraph([A, B])` is `[A, L, B]`. The same goes for `getSubgraph([L])`, the result is again `[A, L, B]`. getSubgraph: function(cells, opt) { opt = opt || {}; var subgraph = []; // `cellMap` is used for a quick lookup of existance of a cell in the `cells` array. var cellMap = {}; var elements = []; var links = []; _.each(cells, function(cell) { if (!cellMap[cell.id]) { subgraph.push(cell); cellMap[cell.id] = cell; if (cell.isLink()) { links.push(cell); } else { elements.push(cell); } } if (opt.deep) { var embeds = cell.getEmbeddedCells({ deep: true }); _.each(embeds, function(embed) { if (!cellMap[embed.id]) { subgraph.push(embed); cellMap[embed.id] = embed; if (embed.isLink()) { links.push(embed); } else { elements.push(embed); } } }); } }); _.each(links, function(link) { // For links, return their source & target (if they are elements - not points). var source = link.get('source'); var target = link.get('target'); if (source.id && !cellMap[source.id]) { var sourceElement = this.getCell(source.id); subgraph.push(sourceElement); cellMap[sourceElement.id] = sourceElement; elements.push(sourceElement); } if (target.id && !cellMap[target.id]) { var targetElement = this.getCell(target.id); subgraph.push(this.getCell(target.id)); cellMap[targetElement.id] = targetElement; elements.push(targetElement); } }, this); _.each(elements, function(element) { // For elements, include their connected links if their source/target is in the subgraph; var links = this.getConnectedLinks(element, opt); _.each(links, function(link) { var source = link.get('source'); var target = link.get('target'); if (!cellMap[link.id] && source.id && cellMap[source.id] && target.id && cellMap[target.id]) { subgraph.push(link); cellMap[link.id] = link; } }); }, this); return subgraph; }, // Find all the predecessors of `element`. This is a reverse operation of `getSuccessors()`. // If `opt.deep` is `true`, take into account embedded elements too. // If `opt.breadthFirst` is `true`, use the Breadth-first search algorithm, otherwise use Depth-first search. getPredecessors: function(element, opt) { opt = opt || {}; var res = []; // Modify the options so that it includes the `inbound` neighbors only. In other words, search backwards. this.search(element, function(el) { if (el !== element) { res.push(el); } }, _.extend({}, opt, { inbound: true })); return res; }, // Perform search on the graph. // If `opt.breadthFirst` is `true`, use the Breadth-first Search algorithm, otherwise use Depth-first search. // By setting `opt.inbound` to `true`, you can reverse the direction of the search. // If `opt.deep` is `true`, take into account embedded elements too. // `iteratee` is a function of the form `function(element) {}`. // If `iteratee` explicitely returns `false`, the searching stops. search: function(element, iteratee, opt) { opt = opt || {}; if (opt.breadthFirst) { this.bfs(element, iteratee, opt); } else { this.dfs(element, iteratee, opt); } }, // Breadth-first search. // If `opt.deep` is `true`, take into account embedded elements too. // If `opt.inbound` is `true`, reverse the search direction (it's like reversing all the link directions). // `iteratee` is a function of the form `function(element, distance) {}`. // where `element` is the currently visited element and `distance` is the distance of that element // from the root `element` passed the `bfs()`, i.e. the element we started the search from. // Note that the `distance` is not the shortest or longest distance, it is simply the number of levels // crossed till we visited the `element` for the first time. It is especially useful for tree graphs. // If `iteratee` explicitely returns `false`, the searching stops. bfs: function(element, iteratee, opt) { opt = opt || {}; var visited = {}; var distance = {}; var queue = []; queue.push(element); distance[element.id] = 0; while (queue.length > 0) { var next = queue.shift(); if (!visited[next.id]) { visited[next.id] = true; if (iteratee(next, distance[next.id]) === false) return; _.each(this.getNeighbors(next, opt), function(neighbor) { distance[neighbor.id] = distance[next.id] + 1; queue.push(neighbor); }); } } }, // Depth-first search. // If `opt.deep` is `true`, take into account embedded elements too. // If `opt.inbound` is `true`, reverse the search direction (it's like reversing all the link directions). // `iteratee` is a function of the form `function(element, distance) {}`. // If `iteratee` explicitely returns `false`, the search stops. dfs: function(element, iteratee, opt, _visited, _distance) { opt = opt || {}; var visited = _visited || {}; var distance = _distance || 0; if (iteratee(element, distance) === false) return; visited[element.id] = true; _.each(this.getNeighbors(element, opt), function(neighbor) { if (!visited[neighbor.id]) { this.dfs(neighbor, iteratee, opt, visited, distance + 1); } }, this); }, // Get all the roots of the graph. Time complexity: O(|V|). getSources: function() { var sources = []; _.each(this._nodes, function(exists, node) { if (!this._in[node] || _.isEmpty(this._in[node])) { sources.push(this.getCell(node)); } }, this); return sources; }, // Get all the leafs of the graph. Time complexity: O(|V|). getSinks: function() { var sinks = []; _.each(this._nodes, function(exists, node) { if (!this._out[node] || _.isEmpty(this._out[node])) { sinks.push(this.getCell(node)); } }, this); return sinks; }, // Return `true` if `element` is a root. Time complexity: O(1). isSource: function(element) { return !this._in[element.id] || _.isEmpty(this._in[element.id]); }, // Return `true` if `element` is a leaf. Time complexity: O(1). isSink: function(element) { return !this._out[element.id] || _.isEmpty(this._out[element.id]); }, // Return `true` is `elementB` is a successor of `elementA`. Return `false` otherwise. isSuccessor: function(elementA, elementB) { var isSuccessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isSuccessor = true; return false; } }, { outbound: true }); return isSuccessor; }, // Return `true` is `elementB` is a predecessor of `elementA`. Return `false` otherwise. isPredecessor: function(elementA, elementB) { var isPredecessor = false; this.search(elementA, function(element) { if (element === elementB && element !== elementA) { isPredecessor = true; return false; } }, { inbound: true }); return isPredecessor; }, // Return `true` is `elementB` is a neighbor of `elementA`. Return `false` otherwise. // `opt.deep` controls whether to take into account embedded elements as well. See `getNeighbors()` // for more details. // If `opt.outbound` is set to `true`, return `true` only if `elementB` is a successor neighbor. // Similarly, if `opt.inbound` is set to `true`, return `true` only if `elementB` is a predecessor neighbor. isNeighbor: function(elementA, elementB, opt) { opt = opt || {}; var inbound = opt.inbound; var outbound = opt.outbound; if (_.isUndefined(inbound) && _.isUndefined(outbound)) { inbound = outbound = true; } var isNeighbor = false; _.each(this.getConnectedLinks(elementA, opt), function(link) { var source = link.get('source'); var target = link.get('target'); var loop = link.hasLoop(opt); // Discard if it is a point. if (inbound && _.has(source, 'id') && source.id === elementB.id) { isNeighbor = true; return false; } // Discard if it is a point, or if the neighbor was already added. if (outbound && _.has(target, 'id') && target.id === elementB.id) { isNeighbor = true; return false; } }); return isNeighbor; }, // Disconnect links connected to the cell `model`. disconnectLinks: function(model, options) { _.each(this.getConnectedLinks(model), function(link) { link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0), options); }); }, // Remove links connected to the cell `model` completely. removeLinks: function(model, options) { _.invoke(this.getConnectedLinks(model), 'remove', options); }, // Find all elements at given point findModelsFromPoint: function(p) { return _.filter(this.getElements(), function(el) { return el.getBBox().containsPoint(p); }); }, // Find all elements in given area findModelsInArea: function(rect, opt) { rect = g.rect(rect); opt = _.defaults(opt || {}, { strict: false }); var method = opt.strict ? 'containsRect' : 'intersect'; return _.filter(this.getElements(), function(el) { return rect[method](el.getBBox()); }); }, // Find all elements under the given element. findModelsUnderElement: function(element, opt) { opt = _.defaults(opt || {}, { searchBy: 'bbox' }); var bbox = element.getBBox(); var elements = (opt.searchBy == 'bbox') ? this.findModelsInArea(bbox) : this.findModelsFromPoint(bbox[opt.searchBy]()); // don't account element itself or any of its descendents return _.reject(elements, function(el) { return element.id == el.id || el.isEmbeddedIn(element); }); }, // Return bounding box of all elements. getBBox: function(cells, opt) { return this.getCellsBBox(cells || this.getElements(), opt); }, // Return the bounding box of all cells in array provided. // Links are being ignored. getCellsBBox: function(cells, opt) { return _.reduce(cells, function(memo, cell) { if (cell.isLink()) return memo; if (memo) { return memo.union(cell.getBBox(opt)); } else { return cell.getBBox(opt); } }, null); }, translate: function(dx, dy, opt) { // Don't translate cells that are embedded in any other cell. var cells = _.reject(this.getCells(), function(cell) { return cell.isEmbedded(); }); _.invoke(cells, 'translate', dx, dy, opt); }, resize: function(width, height, opt) { return this.resizeCells(width, height, this.getCells(), opt); }, resizeCells: function(width, height, cells, opt) { // `getBBox` method returns `null` if no elements provided. // i.e. cells can be an array of links var bbox = this.getCellsBBox(cells); if (bbox) { var sx = Math.max(width / bbox.width, 0); var sy = Math.max(height / bbox.height, 0); _.invoke(cells, 'scale', sx, sy, bbox.origin(), opt); } return this; }, startBatch: function(name, data) { data = data || {}; this._batches[name] = (this._batches[name] || 0) + 1; return this.trigger('batch:start', _.extend({}, data, { batchName: name })); }, stopBatch: function(name, data) { data = data || {}; this._batches[name] = (this._batches[name] || 0) - 1; return this.trigger('batch:stop', _.extend({}, data, { batchName: name })); }, hasActiveBatch: function(name) { if (name) { return this._batches[name]; } else { return _.any(this._batches, function(batches) { return batches > 0; }); } } }); joint.util.wrapWith(joint.dia.Graph.prototype, ['resetCells', 'addCells', 'removeCells'], 'cells'); // JointJS. // (c) 2011-2015 client IO // joint.dia.Cell base model. // -------------------------- joint.dia.Cell = Backbone.Model.extend({ // This is the same as Backbone.Model with the only difference that is uses _.merge // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes. constructor: function(attributes, options) { var defaults; var attrs = attributes || {}; this.cid = _.uniqueId('c'); this.attributes = {}; if (options && options.collection) this.collection = options.collection; if (options && options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { //<custom code> // Replaced the call to _.defaults with _.merge. attrs = _.merge({}, defaults, attrs); //</custom code> } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }, translate: function(dx, dy, opt) { throw new Error('Must define a translate() method.'); }, toJSON: function() { var defaultAttrs = this.constructor.prototype.defaults.attrs || {}; var attrs = this.attributes.attrs; var finalAttrs = {}; // Loop through all the attributes and // omit the default attributes as they are implicitly reconstructable by the cell 'type'. _.each(attrs, function(attr, selector) { var defaultAttr = defaultAttrs[selector]; _.each(attr, function(value, name) { // attr is mainly flat though it might have one more level (consider the `style` attribute). // Check if the `value` is object and if yes, go one level deep. if (_.isObject(value) && !_.isArray(value)) { _.each(value, function(value2, name2) { if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) { finalAttrs[selector] = finalAttrs[selector] || {}; (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2; } }); } else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) { // `value` is not an object, default attribute for such a selector does not exist // or it is different than the attribute value set on the model. finalAttrs[selector] = finalAttrs[selector] || {}; finalAttrs[selector][name] = value; } }); }); var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs')); //var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs'))); attributes.attrs = finalAttrs; return attributes; }, initialize: function(options) { if (!options || !options.id) { this.set('id', joint.util.uuid(), { silent: true }); } this._transitionIds = {}; // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes. this.processPorts(); this.on('change:attrs', this.processPorts, this); }, processPorts: function() { // Whenever `attrs` changes, we extract ports from the `attrs` object and store it // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source` // set to that port, we remove those links as well (to follow the same behaviour as // with a removed element). var previousPorts = this.ports; // Collect ports from the `attrs` object. var ports = {}; _.each(this.get('attrs'), function(attrs, selector) { if (attrs && attrs.port) { // `port` can either be directly an `id` or an object containing an `id` (and potentially other data). if (!_.isUndefined(attrs.port.id)) { ports[attrs.port.id] = attrs.port; } else { ports[attrs.port] = { id: attrs.port }; } } }); // Collect ports that have been removed (compared to the previous ports) - if any. // Use hash table for quick lookup. var removedPorts = {}; _.each(previousPorts, function(port, id) { if (!ports[id]) removedPorts[id] = true; }); // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports. if (this.graph && !_.isEmpty(removedPorts)) { var inboundLinks = this.graph.getConnectedLinks(this, { inbound: true }); _.each(inboundLinks, function(link) { if (removedPorts[link.get('target').port]) link.remove(); }); var outboundLinks = this.graph.getConnectedLinks(this, { outbound: true }); _.each(outboundLinks, function(link) { if (removedPorts[link.get('source').port]) link.remove(); }); } // Update the `ports` object. this.ports = ports; }, remove: function(opt) { opt = opt || {}; // Store the graph in a variable because `this.graph` won't' be accessbile after `this.trigger('remove', ...)` down below. var graph = this.graph; if (graph) { graph.startBatch('remove'); } // First, unembed this cell from its parent cell if there is one. var parentCellId = this.get('parent'); if (parentCellId) { var parentCell = graph && graph.getCell(parentCellId); parentCell.unembed(this); } _.invoke(this.getEmbeddedCells(), 'remove', opt); this.trigger('remove', this, this.collection, opt); if (graph) { graph.stopBatch('remove'); } return this; }, toFront: function(opt) { if (this.graph) { opt = opt || {}; var z = (this.graph.getLastCell().get('z') || 0) + 1; this.startBatch('to-front').set('z', z, opt); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.each(cells, function(cell) { cell.set('z', ++z, opt); }); } this.stopBatch('to-front'); } return this; }, toBack: function(opt) { if (this.graph) { opt = opt || {}; var z = (this.graph.getFirstCell().get('z') || 0) - 1; this.startBatch('to-back'); if (opt.deep) { var cells = this.getEmbeddedCells({ deep: true, breadthFirst: true }); _.eachRight(cells, function(cell) { cell.set('z', z--, opt); }); } this.set('z', z, opt).stopBatch('to-back'); } return this; }, embed: function(cell, opt) { if (this === cell || this.isEmbeddedIn(cell)) { throw new Error('Recursive embedding not allowed.'); } else { this.startBatch('embed'); var embeds = _.clone(this.get('embeds') || []); // We keep all element ids after link ids. embeds[cell.isLink() ? 'unshift' : 'push'](cell.id); cell.set('parent', this.id, opt); this.set('embeds', _.uniq(embeds), opt); this.stopBatch('embed'); } return this; }, unembed: function(cell, opt) { this.startBatch('unembed'); cell.unset('parent', opt); this.set('embeds', _.without(this.get('embeds'), cell.id), opt); this.stopBatch('unembed'); return this; }, // Return an array of ancestor cells. // The array is ordered from the parent of the cell // to the most distant ancestor. getAncestors: function() { var ancestors = []; var parentId = this.get('parent'); if (!this.graph) { return ancestors; } while (parentId !== undefined) { var parent = this.graph.getCell(parentId); if (parent !== undefined) { ancestors.push(parent); parentId = parent.get('parent'); } else { break; } } return ancestors; }, getEmbeddedCells: function(opt) { opt = opt || {}; // Cell models can only be retrieved when this element is part of a collection. // There is no way this element knows about other cells otherwise. // This also means that calling e.g. `translate()` on an element with embeds before // adding it to a graph does not translate its embeds. if (this.graph) { var cells; if (opt.deep) { if (opt.breadthFirst) { // breadthFirst algorithm cells = []; var queue = this.getEmbeddedCells(); while (queue.length > 0) { var parent = queue.shift(); cells.push(parent); queue.push.apply(queue, parent.getEmbeddedCells()); } } else { // depthFirst algorithm cells = this.getEmbeddedCells(); _.each(cells, function(cell) { cells.push.apply(cells, cell.getEmbeddedCells(opt)); }); } } else { cells = _.map(this.get('embeds'), this.graph.getCell, this.graph); } return cells; } return []; }, isEmbeddedIn: function(cell, opt) { var cellId = _.isString(cell) ? cell : cell.id; var parentId = this.get('parent'); opt = _.defaults({ deep: true }, opt); // See getEmbeddedCells(). if (this.graph && opt.deep) { while (parentId) { if (parentId === cellId) { return true; } parentId = this.graph.getCell(parentId).get('parent'); } return false; } else { // When this cell is not part of a collection check // at least whether it's a direct child of given cell. return parentId === cellId; } }, // Whether or not the cell is embedded in any other cell. isEmbedded: function() { return !!this.get('parent'); }, // Isolated cloning. Isolated cloning has two versions: shallow and deep (pass `{ deep: true }` in `opt`). // Shallow cloning simply clones the cell and returns a new cell with different ID. // Deep cloning clones the cell and all its embedded cells recursively. clone: function(opt) { opt = opt || {}; if (!opt.deep) { // Shallow cloning. var clone = Backbone.Model.prototype.clone.apply(this, arguments); // We don't want the clone to have the same ID as the original. clone.set('id', joint.util.uuid()); // A shallow cloned element does not carry over the original embeds. clone.unset('embeds'); // And can not be embedded in any cell // as the clone is not part of the graph. clone.unset('parent'); return clone; } else { // Deep cloning. // For a deep clone, simply call `graph.cloneCells()` with the cell and all its embedded cells. return _.values(joint.dia.Graph.prototype.cloneCells.call(null, [this].concat(this.getEmbeddedCells({ deep: true })))); } }, // A convenient way to set nested properties. // This method merges the properties you'd like to set with the ones // stored in the cell and makes sure change events are properly triggered. // You can either set a nested property with one object // or use a property path. // The most simple use case is: // `cell.prop('name/first', 'John')` or // `cell.prop({ name: { first: 'John' } })`. // Nested arrays are supported too: // `cell.prop('series/0/data/0/degree', 50)` or // `cell.prop({ series: [ { data: [ { degree: 50 } ] } ] })`. prop: function(props, value, opt) { var delim = '/'; if (_.isString(props)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. if (arguments.length > 1) { var path = props; var pathArray = path.split('/'); var property = pathArray[0]; // Remove the top-level property from the array of properties. pathArray.shift(); opt = opt || {}; opt.propertyPath = path; opt.propertyValue = value; if (pathArray.length === 0) { // Property is not nested. We can simply use `set()`. return this.set(property, value, opt); } var update = {}; // Initialize the nested object. Subobjects are either arrays or objects. // An empty array is created if the sub-key is an integer. Otherwise, an empty object is created. // Note that this imposes a limitation on object keys one can use with Inspector. // Pure integer keys will cause issues and are therefore not allowed. var initializer = update; var prevProperty = property; _.each(pathArray, function(key) { initializer = initializer[prevProperty] = (_.isFinite(Number(key)) ? [] : {}); prevProperty = key; }); // Fill update with the `value` on `path`. update = joint.util.setByPath(update, path, value, '/'); var baseAttributes = _.merge({}, this.attributes); // if rewrite mode enabled, we replace value referenced by path with // the new one (we don't merge). opt.rewrite && joint.util.unsetByPath(baseAttributes, path, '/'); // Merge update with the model attributes. var attributes = _.merge(baseAttributes, update); // Finally, set the property to the updated attributes. return this.set(property, attributes[property], opt); } else { return joint.util.getByPath(this.attributes, props, delim); } } return this.set(_.merge({}, this.attributes, props), value); }, // A convient way to unset nested properties removeProp: function(path, opt) { // Once a property is removed from the `attrs` attribute // the cellView will recognize a `dirty` flag and rerender itself // in order to remove the attribute from SVG element. opt = opt || {}; opt.dirty = true; var pathArray = path.split('/'); if (pathArray.length === 1) { // A top level property return this.unset(path, opt); } // A nested property var property = pathArray[0]; var nestedPath = pathArray.slice(1).join('/'); var propertyValue = _.merge({}, this.get(property)); joint.util.unsetByPath(propertyValue, nestedPath, '/'); return this.set(property, propertyValue, opt); }, // A convenient way to set nested attributes. attr: function(attrs, value, opt) { var args = Array.prototype.slice.call(arguments); if (_.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. args[0] = 'attrs/' + attrs; } else { args[0] = { 'attrs' : attrs }; } return this.prop.apply(this, args); }, // A convenient way to unset nested attributes removeAttr: function(path, opt) { if (_.isArray(path)) { _.each(path, function(p) { this.removeAttr(p, opt); }, this); return this; } return this.removeProp('attrs/' + path, opt); }, transition: function(path, value, opt, delim) { delim = delim || '/'; var defaults = { duration: 100, delay: 10, timingFunction: joint.util.timing.linear, valueFunction: joint.util.interpolate.number }; opt = _.extend(defaults, opt); var firstFrameTime = 0; var interpolatingFunction; var setter = _.bind(function(runtime) { var id, progress, propertyValue, status; firstFrameTime = firstFrameTime || runtime; runtime -= firstFrameTime; progress = runtime / opt.duration; if (progress < 1) { this._transitionIds[path] = id = joint.util.nextFrame(setter); } else { progress = 1; delete this._transitionIds[path]; } propertyValue = interpolatingFunction(opt.timingFunction(progress)); opt.transitionId = id; this.prop(path, propertyValue, opt); if (!id) this.trigger('transition:end', this, path); }, this); var initiator = _.bind(function(callback) { this.stopTransitions(path); interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value); this._transitionIds[path] = joint.util.nextFrame(callback); this.trigger('transition:start', this, path); }, this); return _.delay(initiator, opt.delay, setter); }, getTransitions: function() { return _.keys(this._transitionIds); }, stopTransitions: function(path, delim) { delim = delim || '/'; var pathArray = path && path.split(delim); _(this._transitionIds).keys().filter(pathArray && function(key) { return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length)); }).each(function(key) { joint.util.cancelFrame(this._transitionIds[key]); delete this._transitionIds[key]; this.trigger('transition:end', this, key); }, this); return this; }, // A shorcut making it easy to create constructs like the following: // `var el = (new joint.shapes.basic.Rect).addTo(graph)`. addTo: function(graph, opt) { graph.addCell(this, opt); return this; }, // A shortcut for an equivalent call: `paper.findViewByModel(cell)` // making it easy to create constructs like the following: // `cell.findView(paper).highlight()` findView: function(paper) { return paper.findViewByModel(this); }, isElement: function() { return false; }, isLink: function() { return false; }, startBatch: function(name, opt) { if (this.graph) { this.graph.startBatch(name, _.extend({}, opt, { cell: this })); } return this; }, stopBatch: function(name, opt) { if (this.graph) { this.graph.stopBatch(name, _.extend({}, opt, { cell: this })); } return this; } }); // joint.dia.CellView base view and controller. // -------------------------------------------- // This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`. joint.dia.CellView = joint.mvc.View.extend({ tagName: 'g', className: function() { var classNames = ['cell']; var type = this.model.get('type'); if (type) { _.each(type.toLowerCase().split('.'), function(value, index, list) { classNames.push('type-' + list.slice(0, index + 1).join('-')); }); } return classNames.join(' '); }, attributes: function() { return { 'model-id': this.model.id }; }, constructor: function(options) { // Make sure a global unique id is assigned to this view. Store this id also to the properties object. // The global unique id makes sure that the same view can be rendered on e.g. different machines and // still be associated to the same object among all those clients. This is necessary for real-time // collaboration mechanism. options.id = options.id || joint.util.guid(this); joint.mvc.View.call(this, options); }, init: function() { _.bindAll(this, 'remove', 'update'); // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree. this.$el.data('view', this); // Add the cell's type to the view's element as a data attribute. this.$el.attr('data-type', this.model.get('type')); this.listenTo(this.model, 'change:attrs', this.onChangeAttrs); }, onChangeAttrs: function(cell, attrs, opt) { if (opt.dirty) { // dirty flag could be set when a model attribute was removed and it needs to be cleared // also from the DOM element. See cell.removeAttr(). return this.render(); } return this.update(cell, attrs, opt); }, // Return `true` if cell link is allowed to perform a certain UI `feature`. // Example: `can('vertexMove')`, `can('labelMove')`. can: function(feature) { var interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this) : this.options.interactive; return (_.isObject(interactive) && interactive[feature] !== false) || (_.isBoolean(interactive) && interactive !== false); }, // Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps // all the nodes of the Cell view. _ensureElement: function() { var el; if (!this.el) { var attrs = _.extend({ id: this.id }, _.result(this, 'attributes')); if (this.className) attrs['class'] = _.result(this, 'className'); el = V(_.result(this, 'tagName'), attrs).node; } else { el = _.result(this, 'el'); } this.setElement(el, false); }, // Utilize an alternative DOM manipulation API by // adding an element reference wrapped in Vectorizer. _setElement: function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; this.vel = V(this.el); }, findBySelector: function(selector) { // These are either descendants of `this.$el` of `this.$el` itself. // `.` is a special selector used to select the wrapping `<g>` element. var $selected = selector === '.' ? this.$el : this.$el.find(selector); return $selected; }, notify: function(eventName) { if (this.paper) { var args = Array.prototype.slice.call(arguments, 1); // Trigger the event on both the element itself and also on the paper. this.trigger.apply(this, [eventName].concat(args)); // Paper event handlers receive the view object as the first argument. this.paper.trigger.apply(this.paper, [eventName, this].concat(args)); } }, getStrokeBBox: function(el) { // Return a bounding box rectangle that takes into account stroke. // Note that this is a naive and ad-hoc implementation that does not // works only in certain cases and should be replaced as soon as browsers will // start supporting the getStrokeBBox() SVG method. // @TODO any better solution is very welcome! var isMagnet = !!el; el = el || this.el; var bbox = V(el).bbox(false, this.paper.viewport); var strokeWidth; if (isMagnet) { strokeWidth = V(el).attr('stroke-width'); } else { strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width'); } strokeWidth = parseFloat(strokeWidth) || 0; return g.rect(bbox).moveAndExpand({ x: -strokeWidth / 2, y: -strokeWidth / 2, width: strokeWidth, height: strokeWidth }); }, getBBox: function() { return g.rect(this.vel.bbox()); }, highlight: function(el, opt) { el = !el ? this.el : this.$(el)[0] || this.el; // set partial flag if the highlighted element is not the entire view. opt = opt || {}; opt.partial = el != this.el; this.notify('cell:highlight', el, opt); return this; }, unhighlight: function(el, opt) { el = !el ? this.el : this.$(el)[0] || this.el; opt = opt || {}; opt.partial = el != this.el; this.notify('cell:unhighlight', el, opt); return this; }, // Find the closest element that has the `magnet` attribute set to `true`. If there was not such // an element found, return the root element of the cell view. findMagnet: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { // If the overall cell has set `magnet === false`, then return `undefined` to // announce there is no magnet found for this cell. // This is especially useful to set on cells that have 'ports'. In this case, // only the ports have set `magnet === true` and the overall element has `magnet === false`. var attrs = this.model.get('attrs') || {}; if (attrs['.'] && attrs['.']['magnet'] === false) { return undefined; } return this.el; } if ($el.attr('magnet')) { return $el[0]; } return this.findMagnet($el.parent()); }, // `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format: // `{ name: <name of the filter>, args: { <arguments>, ... }`. // An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`. applyFilter: function(selector, filter) { var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter)); // If the filter already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(filterId)) { var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {}); if (!filterSVGString) { throw new Error('Non-existing filter ' + filter.name); } var filterElement = V(filterSVGString); // Set the filter area to be 3x the bounding box of the cell // and center the filter around the cell. filterElement.attr({ filterUnits: 'objectBoundingBox', x: -1, y: -1, width: 3, height: 3 }); if (filter.attrs) filterElement.attr(filter.attrs); filterElement.node.id = filterId; V(this.paper.svg).defs().append(filterElement); } $selected.each(function() { V(this).attr('filter', 'url(#' + filterId + ')'); }); }, // `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`. // `gradient` must be in the special JointJS gradient format: // `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`. // An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`. applyGradient: function(selector, attr, gradient) { var $selected = _.isString(selector) ? this.findBySelector(selector) : $(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient)); // If the gradient already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(gradientId)) { var gradientSVGString = [ '<' + gradient.type + '>', _.map(gradient.stops, function(stop) { return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />'; }).join(''), '</' + gradient.type + '>' ].join(''); var gradientElement = V(gradientSVGString); if (gradient.attrs) { gradientElement.attr(gradient.attrs); } gradientElement.node.id = gradientId; V(this.paper.svg).defs().append(gradientElement); } $selected.each(function() { V(this).attr(attr, 'url(#' + gradientId + ')'); }); }, // Construct a unique selector for the `el` element within this view. // `prevSelector` is being collected through the recursive call. // No value for `prevSelector` is expected when using this method. getSelector: function(el, prevSelector) { if (el === this.el) { return prevSelector; } var selector; if (el) { var nthChild = V(el).index() + 1; var selector = el.tagName + ':nth-child(' + nthChild + ')'; if (prevSelector) { selector += ' > ' + prevSelector; } selector = this.getSelector(el.parentNode, selector); } return selector; }, // Interaction. The controller part. // --------------------------------- // Interaction is handled by the paper and delegated to the view in interest. // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid. // If necessary, real coordinates can be obtained from the `evt` event object. // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`, // i.e. `joint.dia.Element` and `joint.dia.Link`. pointerdblclick: function(evt, x, y) { this.notify('cell:pointerdblclick', evt, x, y); }, pointerclick: function(evt, x, y) { this.notify('cell:pointerclick', evt, x, y); }, pointerdown: function(evt, x, y) { if (this.model.graph) { this.model.startBatch('pointer'); this._graph = this.model.graph; } this.notify('cell:pointerdown', evt, x, y); }, pointermove: function(evt, x, y) { this.notify('cell:pointermove', evt, x, y); }, pointerup: function(evt, x, y) { this.notify('cell:pointerup', evt, x, y); if (this._graph) { // we don't want to trigger event on model as model doesn't // need to be member of collection anymore (remove) this._graph.stopBatch('pointer', { cell: this.model }); delete this._graph; } }, mouseover: function(evt) { this.notify('cell:mouseover', evt); }, mouseout: function(evt) { this.notify('cell:mouseout', evt); }, mousewheel: function(evt, x, y, delta) { this.notify('cell:mousewheel', evt, x, y, delta); }, contextmenu: function(evt, x, y) { this.notify('cell:contextmenu', evt, x, y); }, setInteractivity: function(value) { this.options.interactive = value; } }); // JointJS library. // (c) 2011-2015 client IO // joint.dia.Element base model. // ----------------------------- joint.dia.Element = joint.dia.Cell.extend({ defaults: { position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, angle: 0 }, isElement: function() { return true; }, position: function(x, y, opt) { var isSetter = _.isNumber(y); opt = (isSetter ? opt : x) || {}; // option `parentRelative` for setting the position relative to the element's parent. if (opt.parentRelative) { // Getting the parent's position requires the collection. // Cell.get('parent') helds cell id only. if (!this.graph) throw new Error('Element must be part of a graph.'); var parent = this.graph.getCell(this.get('parent')); var parentPosition = parent && !parent.isLink() ? parent.get('position') : { x: 0, y: 0 }; } if (isSetter) { if (opt.parentRelative) { x += parentPosition.x; y += parentPosition.y; } return this.set('position', { x: x, y: y }, opt); } else { // Getter returns a geometry point. var elementPosition = g.point(this.get('position')); return opt.parentRelative ? elementPosition.difference(parentPosition) : elementPosition; } }, translate: function(tx, ty, opt) { tx = tx || 0; ty = ty || 0; if (tx === 0 && ty === 0) { // Like nothing has happened. return this; } opt = opt || {}; // Pass the initiator of the translation. opt.translateBy = opt.translateBy || this.id; var position = this.get('position') || { x: 0, y: 0 }; if (opt.restrictedArea && opt.translateBy === this.id) { // We are restricting the translation for the element itself only. We get // the bounding box of the element including all its embeds. // All embeds have to be translated the exact same way as the element. var bbox = this.getBBox({ deep: true }); var ra = opt.restrictedArea; //- - - - - - - - - - - - -> ra.x + ra.width // - - - -> position.x | // -> bbox.x // ▓▓▓▓▓▓▓ | // ░░░░░░░▓▓▓▓▓▓▓ // ░░░░░░░░░ | // ▓▓▓▓▓▓▓▓░░░░░░░ // ▓▓▓▓▓▓▓▓ | // <-dx-> | restricted area right border // <-width-> | ░ translated element // <- - bbox.width - -> ▓ embedded element var dx = position.x - bbox.x; var dy = position.y - bbox.y; // Find the maximal/minimal coordinates that the element can be translated // while complies the restrictions. var x = Math.max(ra.x + dx, Math.min(ra.x + ra.width + dx - bbox.width, position.x + tx)); var y = Math.max(ra.y + dy, Math.min(ra.y + ra.height + dy - bbox.height, position.y + ty)); // recalculate the translation taking the resctrictions into account. tx = x - position.x; ty = y - position.y; } var translatedPosition = { x: position.x + tx, y: position.y + ty }; // To find out by how much an element was translated in event 'change:position' handlers. opt.tx = tx; opt.ty = ty; if (opt.transition) { if (!_.isObject(opt.transition)) opt.transition = {}; this.transition('position', translatedPosition, _.extend({}, opt.transition, { valueFunction: joint.util.interpolate.object })); } else { this.set('position', translatedPosition, opt); } // Recursively call `translate()` on all the embeds cells. _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt); return this; }, resize: function(width, height, opt) { opt = opt || {}; this.startBatch('resize', opt); if (opt.direction) { var currentSize = this.get('size'); switch (opt.direction) { case 'left': case 'right': // Don't change height when resizing horizontally. height = currentSize.height; break; case 'top': case 'bottom': // Don't change width when resizing vertically. width = currentSize.width; break; } // Get the angle and clamp its value between 0 and 360 degrees. var angle = g.normalizeAngle(this.get('angle') || 0); var quadrant = { 'top-right': 0, 'right': 0, 'top-left': 1, 'top': 1, 'bottom-left': 2, 'left': 2, 'bottom-right': 3, 'bottom': 3 }[opt.direction]; if (opt.absolute) { // We are taking the element's rotation into account quadrant += Math.floor((angle + 45) / 90); quadrant %= 4; } // This is a rectangle in size of the unrotated element. var bbox = this.getBBox(); // Pick the corner point on the element, which meant to stay on its place before and // after the rotation. var fixedPoint = bbox[['bottomLeft', 'corner', 'topRight', 'origin'][quadrant]](); // Find an image of the previous indent point. This is the position, where is the // point actually located on the screen. var imageFixedPoint = g.point(fixedPoint).rotate(bbox.center(), -angle); // Every point on the element rotates around a circle with the centre of rotation // in the middle of the element while the whole element is being rotated. That means // that the distance from a point in the corner of the element (supposed its always rect) to // the center of the element doesn't change during the rotation and therefore it equals // to a distance on unrotated element. // We can find the distance as DISTANCE = (ELEMENTWIDTH/2)^2 + (ELEMENTHEIGHT/2)^2)^0.5. var radius = Math.sqrt((width * width) + (height * height)) / 2; // Now we are looking for an angle between x-axis and the line starting at image of fixed point // and ending at the center of the element. We call this angle `alpha`. // The image of a fixed point is located in n-th quadrant. For each quadrant passed // going anti-clockwise we have to add 90 degrees. Note that the first quadrant has index 0. // // 3 | 2 // --c-- Quadrant positions around the element's center `c` // 0 | 1 // var alpha = quadrant * Math.PI / 2; // Add an angle between the beginning of the current quadrant (line parallel with x-axis or y-axis // going through the center of the element) and line crossing the indent of the fixed point and the center // of the element. This is the angle we need but on the unrotated element. alpha += Math.atan(quadrant % 2 == 0 ? height / width : width / height); // Lastly we have to deduct the original angle the element was rotated by and that's it. alpha -= g.toRad(angle); // With this angle and distance we can easily calculate the centre of the unrotated element. // Note that fromPolar constructor accepts an angle in radians. var center = g.point.fromPolar(radius, alpha, imageFixedPoint); // The top left corner on the unrotated element has to be half a width on the left // and half a height to the top from the center. This will be the origin of rectangle // we were looking for. var origin = g.point(center).offset( width / -2, height / -2); // Resize the element (before re-positioning it). this.set('size', { width: width, height: height }, opt); // Finally, re-position the element. this.position(origin.x, origin.y, opt); } else { // Resize the element. this.set('size', { width: width, height: height }, opt); } this.stopBatch('resize', opt); return this; }, scale: function(sx, sy, origin, opt) { var scaledBBox = this.getBBox().scale(sx, sy, origin); this.startBatch('scale', opt); this.position(scaledBBox.x, scaledBBox.y, opt); this.resize(scaledBBox.width, scaledBBox.height, opt); this.stopBatch('scale'); return this; }, fitEmbeds: function(opt) { opt = opt || {}; // Getting the children's size and position requires the collection. // Cell.get('embdes') helds an array of cell ids only. if (!this.graph) throw new Error('Element must be part of a graph.'); var embeddedCells = this.getEmbeddedCells(); if (embeddedCells.length > 0) { this.startBatch('fit-embeds', opt); if (opt.deep) { // Recursively apply fitEmbeds on all embeds first. _.invoke(embeddedCells, 'fitEmbeds', opt); } // Compute cell's size and position based on the children bbox // and given padding. var bbox = this.graph.getCellsBBox(embeddedCells); var padding = joint.util.normalizeSides(opt.padding); // Apply padding computed above to the bbox. bbox.moveAndExpand({ x: - padding.left, y: - padding.top, width: padding.right + padding.left, height: padding.bottom + padding.top }); // Set new element dimensions finally. this.set({ position: { x: bbox.x, y: bbox.y }, size: { width: bbox.width, height: bbox.height } }, opt); this.stopBatch('fit-embeds'); } return this; }, // Rotate element by `angle` degrees, optionally around `origin` point. // If `origin` is not provided, it is considered to be the center of the element. // If `absolute` is `true`, the `angle` is considered is abslute, i.e. it is not // the difference from the previous angle. rotate: function(angle, absolute, origin) { if (origin) { var center = this.getBBox().center(); var size = this.get('size'); var position = this.get('position'); center.rotate(origin, this.get('angle') - angle); var dx = center.x - size.width / 2 - position.x; var dy = center.y - size.height / 2 - position.y; this.startBatch('rotate', { angle: angle, absolute: absolute, origin: origin }); this.translate(dx, dy); this.rotate(angle, absolute); this.stopBatch('rotate'); } else { this.set('angle', absolute ? angle : (this.get('angle') + angle) % 360); } return this; }, getBBox: function(opt) { opt = opt || {}; if (opt.deep && this.graph) { // Get all the embedded elements using breadth first algorithm, // that doesn't use recursion. var elements = this.getEmbeddedCells({ deep: true, breadthFirst: true }); // Add the model itself. elements.push(this); return this.graph.getCellsBBox(elements); } var position = this.get('position'); var size = this.get('size'); return g.rect(position.x, position.y, size.width, size.height); } }); // joint.dia.Element base view and controller. // ------------------------------------------- joint.dia.ElementView = joint.dia.CellView.extend({ SPECIAL_ATTRIBUTES: [ 'style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref-width', 'ref-height', 'ref', 'x-alignment', 'y-alignment', 'port' ], className: function() { var classNames = joint.dia.CellView.prototype.className.apply(this).split(' '); classNames.push('element'); return classNames.join(' '); }, initialize: function() { _.bindAll(this, 'translate', 'resize', 'rotate'); joint.dia.CellView.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:position', this.translate); this.listenTo(this.model, 'change:size', this.resize); this.listenTo(this.model, 'change:angle', this.rotate); }, // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function(cell, renderingOnlyAttrs) { var allAttrs = this.model.get('attrs'); var rotatable = this.rotatableNode; if (rotatable) { var rotation = rotatable.attr('transform'); rotatable.attr('transform', ''); } var relativelyPositioned = []; var nodesBySelector = {}; _.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) { // Elements that should be updated. var $selected = this.findBySelector(selector); // No element matched by the `selector` was found. We're done then. if ($selected.length === 0) return; nodesBySelector[selector] = $selected; // Special attributes are treated by JointJS, not by SVG. var specialAttributes = this.SPECIAL_ATTRIBUTES.slice(); // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { specialAttributes.push('filter'); this.applyFilter($selected, attrs.filter); } // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.fill)) { specialAttributes.push('fill'); this.applyGradient($selected, 'fill', attrs.fill); } if (_.isObject(attrs.stroke)) { specialAttributes.push('stroke'); this.applyGradient($selected, 'stroke', attrs.stroke); } // Make special case for `text` attribute. So that we can set text content of the `<text>` element // via the `attrs` object as well. // Note that it's important to set text before applying the rest of the final attributes. // Vectorizer `text()` method sets on the element its own attributes and it has to be possible // to rewrite them, if needed. (i.e display: 'none') if (!_.isUndefined(attrs.text)) { $selected.each(function() { V(this).text(attrs.text + '', { lineHeight: attrs.lineHeight, textPath: attrs.textPath, annotations: attrs.annotations }); }); specialAttributes.push('lineHeight', 'textPath', 'annotations'); } // Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr() // method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr(). var finalAttributes = _.omit(attrs, specialAttributes); $selected.each(function() { V(this).attr(finalAttributes); }); // `port` attribute contains the `id` of the port that the underlying magnet represents. if (attrs.port) { $selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id); } // `style` attribute is special in the sense that it sets the CSS style of the subelement. if (attrs.style) { $selected.css(attrs.style); } if (!_.isUndefined(attrs.html)) { $selected.each(function() { $(this).html(attrs.html + ''); }); } // Special `ref-x` and `ref-y` attributes make it possible to set both absolute or // relative positioning of subelements. if (!_.isUndefined(attrs['ref-x']) || !_.isUndefined(attrs['ref-y']) || !_.isUndefined(attrs['ref-dx']) || !_.isUndefined(attrs['ref-dy']) || !_.isUndefined(attrs['x-alignment']) || !_.isUndefined(attrs['y-alignment']) || !_.isUndefined(attrs['ref-width']) || !_.isUndefined(attrs['ref-height']) ) { _.each($selected, function(el, index, list) { var $el = $(el); // copy original list selector to the element $el.selector = list.selector; relativelyPositioned.push($el); }); } }, this); // We don't want the sub elements to affect the bounding box of the root element when // positioning the sub elements relatively to the bounding box. //_.invoke(relativelyPositioned, 'hide'); //_.invoke(relativelyPositioned, 'show'); // Note that we're using the bounding box without transformation because we are already inside // a transformed coordinate system. var size = this.model.get('size'); var bbox = { x: 0, y: 0, width: size.width, height: size.height }; renderingOnlyAttrs = renderingOnlyAttrs || {}; _.each(relativelyPositioned, function($el) { // if there was a special attribute affecting the position amongst renderingOnlyAttributes // we have to merge it with rest of the element's attributes as they are necessary // to update the position relatively (i.e `ref`) var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector]; var elAttrs = renderingOnlyElAttrs ? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs) : allAttrs[$el.selector]; this.positionRelative(V($el[0]), bbox, elAttrs, nodesBySelector); }, this); if (rotatable) { rotatable.attr('transform', rotation || ''); } }, positionRelative: function(vel, bbox, attributes, nodesBySelector) { var ref = attributes['ref']; var refDx = parseFloat(attributes['ref-dx']); var refDy = parseFloat(attributes['ref-dy']); var yAlignment = attributes['y-alignment']; var xAlignment = attributes['x-alignment']; // 'ref-y', 'ref-x', 'ref-width', 'ref-height' can be defined // by value or by percentage e.g 4, 0.5, '200%'. var refY = attributes['ref-y']; var refYPercentage = _.isString(refY) && refY.slice(-1) === '%'; refY = parseFloat(refY); if (refYPercentage) { refY /= 100; } var refX = attributes['ref-x']; var refXPercentage = _.isString(refX) && refX.slice(-1) === '%'; refX = parseFloat(refX); if (refXPercentage) { refX /= 100; } var refWidth = attributes['ref-width']; var refWidthPercentage = _.isString(refWidth) && refWidth.slice(-1) === '%'; refWidth = parseFloat(refWidth); if (refWidthPercentage) { refWidth /= 100; } var refHeight = attributes['ref-height']; var refHeightPercentage = _.isString(refHeight) && refHeight.slice(-1) === '%'; refHeight = parseFloat(refHeight); if (refHeightPercentage) { refHeight /= 100; } // Check if the node is a descendant of the scalable group. var scalable = vel.findParentByClass('scalable', this.el); // `ref` is the selector of the reference element. If no `ref` is passed, reference // element is the root element. if (ref) { var vref; if (nodesBySelector && nodesBySelector[ref]) { // First we check if the same selector has been already used. vref = V(nodesBySelector[ref][0]); } else { // Other wise we find the ref ourselves. vref = ref === '.' ? this.vel : this.vel.findOne(ref); } if (!vref) { throw new Error('dia.ElementView: reference does not exists.'); } // Get the bounding box of the reference element relative to the root `<g>` element. bbox = vref.bbox(false, this.el); } // Remove the previous translate() from the transform attribute and translate the element // relative to the root bounding box following the `ref-x` and `ref-y` attributes. if (vel.attr('transform')) { vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '').trim() || ''); } // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to // the reference element size // val in 0..1 ref-width = 0.75 sets the width to 75% of the ref. el. width // val < 0 || val > 1 ref-height = -20 sets the height to the the ref. el. height shorter by 20 if (isFinite(refWidth)) { if (refWidthPercentage || refWidth >= 0 && refWidth <= 1) { vel.attr('width', refWidth * bbox.width); } else { vel.attr('width', Math.max(refWidth + bbox.width, 0)); } } if (isFinite(refHeight)) { if (refHeightPercentage || refHeight >= 0 && refHeight <= 1) { vel.attr('height', refHeight * bbox.height); } else { vel.attr('height', Math.max(refHeight + bbox.height, 0)); } } // The final translation of the subelement. var tx = 0; var ty = 0; var scale; // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom // coordinate of the reference element. if (isFinite(refDx)) { if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); tx = bbox.x + bbox.width + refDx / scale.sx; } else { tx = bbox.x + bbox.width + refDx; } } if (isFinite(refDy)) { if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); ty = bbox.y + bbox.height + refDy / scale.sy; } else { ty = bbox.y + bbox.height + refDy; } } // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box // otherwise, `refX` is the left coordinate of the bounding box // Analogical rules apply for `refY`. if (isFinite(refX)) { if (refXPercentage || refX > 0 && refX < 1) { tx = bbox.x + bbox.width * refX; } else if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); tx = bbox.x + refX / scale.sx; } else { tx = bbox.x + refX; } } if (isFinite(refY)) { if (refYPercentage || refY > 0 && refY < 1) { ty = bbox.y + bbox.height * refY; } else if (scalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. scale = scale || scalable.scale(); ty = bbox.y + refY / scale.sy; } else { ty = bbox.y + refY; } } if (!_.isUndefined(yAlignment) || !_.isUndefined(xAlignment)) { var velBBox = vel.bbox(false, this.paper.viewport); // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate. // `y-alignment` when set to `bottom` uses the y coordinate as referenced to the bottom of the bbox. if (yAlignment === 'middle') { ty -= velBBox.height / 2; } else if (yAlignment === 'bottom') { ty -= velBBox.height; } else if (isFinite(yAlignment)) { ty += (yAlignment > -1 && yAlignment < 1) ? velBBox.height * yAlignment : yAlignment; } // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate. // `x-alignment` when set to `right` uses the x coordinate as referenced to the right of the bbox. if (xAlignment === 'middle') { tx -= velBBox.width / 2; } else if (xAlignment === 'right') { tx -= velBBox.width; } else if (isFinite(xAlignment)) { tx += (xAlignment > -1 && xAlignment < 1) ? velBBox.width * xAlignment : xAlignment; } } vel.translate(tx, ty); }, // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the // default markup is not desirable. renderMarkup: function() { var markup = this.model.get('markup') || this.model.markup; if (markup) { var svg = joint.util.template(markup)(); var nodes = V(svg); this.vel.append(nodes); } else { throw new Error('properties.markup is missing while the default render() implementation is used.'); } }, render: function() { this.$el.empty(); this.renderMarkup(); this.rotatableNode = this.vel.findOne('.rotatable'); this.scalableNode = this.vel.findOne('.scalable'); this.update(); this.resize(); this.rotate(); this.translate(); return this; }, // Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here. // `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only. // `update()` is then responsible for scaling only those elements that have the `follow-scale` // attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement // that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed // be be scaled. scale: function(sx, sy) { // TODO: take into account the origin coordinates `ox` and `oy`. this.vel.scale(sx, sy); }, resize: function() { var size = this.model.get('size') || { width: 1, height: 1 }; var angle = this.model.get('angle') || 0; var scalable = this.scalableNode; if (!scalable) { // If there is no scalable elements, than there is nothing to resize. return; } var scalableBbox = scalable.bbox(true); // Make sure `scalableBbox.width` and `scalableBbox.height` are not zero which can happen if the element does not have any content. By making // the width/height 1, we prevent HTML errors of the type `scale(Infinity, Infinity)`. scalable.attr('transform', 'scale(' + (size.width / (scalableBbox.width || 1)) + ',' + (size.height / (scalableBbox.height || 1)) + ')'); // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height` // Order of transformations is significant but we want to reconstruct the object always in the order: // resize(), rotate(), translate() no matter of how the object was transformed. For that to work, // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation // around the center of the resized object (which is a different origin then the origin of the previous rotation) // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was. // Cancel the rotation but now around a different origin, which is the center of the scaled object. var rotatable = this.rotatableNode; var rotation = rotatable && rotatable.attr('transform'); if (rotation && rotation !== 'null') { rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width / 2) + ',' + (size.height / 2) + ')'); var rotatableBbox = scalable.bbox(false, this.paper.viewport); // Store new x, y and perform rotate() again against the new rotation origin. this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y }); this.rotate(); } // Update must always be called on non-rotated element. Otherwise, relative positioning // would work with wrong (rotated) bounding boxes. this.update(); }, translate: function(model, changes, opt) { var position = this.model.get('position') || { x: 0, y: 0 }; this.vel.attr('transform', 'translate(' + position.x + ',' + position.y + ')'); }, rotate: function() { var rotatable = this.rotatableNode; if (!rotatable) { // If there is no rotatable elements, then there is nothing to rotate. return; } var angle = this.model.get('angle') || 0; var size = this.model.get('size') || { width: 1, height: 1 }; var ox = size.width / 2; var oy = size.height / 2; rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')'); }, getBBox: function(opt) { if (opt && opt.useModelGeometry) { var noTransformationBBox = this.model.getBBox().bbox(this.model.get('angle')); var transformationMatrix = this.paper.viewport.getCTM(); return g.rect(V.transformRect(noTransformationBBox, transformationMatrix)); } return joint.dia.CellView.prototype.getBBox.apply(this, arguments); }, // Embedding mode methods // ---------------------- prepareEmbedding: function(opt) { opt = opt || {}; var model = opt.model || this.model; var paper = opt.paper || this.paper; model.startBatch('to-front', opt); // Bring the model to the front with all his embeds. model.toFront({ deep: true, ui: true }); // Move to front also all the inbound and outbound links that are connected // to any of the element descendant. If we bring to front only embedded elements, // links connected to them would stay in the background. _.invoke(paper.model.getConnectedLinks(model, { deep: true }), 'toFront', { ui: true }); model.stopBatch('to-front'); // Before we start looking for suitable parent we remove the current one. var parentId = model.get('parent'); parentId && paper.model.getCell(parentId).unembed(model, { ui: true }); }, processEmbedding: function(opt) { opt = opt || {}; var model = opt.model || this.model; var paper = opt.paper || this.paper; var paperOptions = paper.options; var candidates = paper.model.findModelsUnderElement(model, { searchBy: paperOptions.findParentBy }); if (paperOptions.frontParentOnly) { // pick the element with the highest `z` index candidates = candidates.slice(-1); } var newCandidateView = null; var prevCandidateView = this._candidateEmbedView; // iterate over all candidates starting from the last one (has the highest z-index). for (var i = candidates.length - 1; i >= 0; i--) { var candidate = candidates[i]; if (prevCandidateView && prevCandidateView.model.id == candidate.id) { // candidate remains the same newCandidateView = prevCandidateView; break; } else { var view = candidate.findView(paper); if (paperOptions.validateEmbedding.call(paper, this, view)) { // flip to the new candidate newCandidateView = view; break; } } } if (newCandidateView && newCandidateView != prevCandidateView) { // A new candidate view found. Highlight the new one. prevCandidateView && prevCandidateView.unhighlight(null, { embedding: true }); this._candidateEmbedView = newCandidateView.highlight(null, { embedding: true }); } if (!newCandidateView && prevCandidateView) { // No candidate view found. Unhighlight the previous candidate. prevCandidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } }, finalizeEmbedding: function(opt) { opt = opt || {}; var candidateView = this._candidateEmbedView; var model = opt.model || this.model; var paper = opt.paper || this.paper; if (candidateView) { // We finished embedding. Candidate view is chosen to become the parent of the model. candidateView.model.embed(model, { ui: true }); candidateView.unhighlight(null, { embedding: true }); delete this._candidateEmbedView; } _.invoke(paper.model.getConnectedLinks(model, { deep: true }), 'reparent', { ui: true }); }, // Interaction. The controller part. // --------------------------------- pointerdown: function(evt, x, y) { var paper = this.paper; if ( evt.target.getAttribute('magnet') && this.can('addLinkFromMagnet') && paper.options.validateMagnet.call(paper, this, evt.target) ) { this.model.startBatch('add-link'); var link = paper.getDefaultLink(this, evt.target); link.set({ source: { id: this.model.id, selector: this.getSelector(evt.target), port: evt.target.getAttribute('port') }, target: { x: x, y: y } }); paper.model.addCell(link); var linkView = this._linkView = paper.findViewByModel(link); linkView.pointerdown(evt, x, y); linkView.startArrowheadMove('target', { whenNotAllowed: 'remove' }); } else { this._dx = x; this._dy = y; this.restrictedArea = paper.getRestrictedArea(this); joint.dia.CellView.prototype.pointerdown.apply(this, arguments); this.notify('element:pointerdown', evt, x, y); } }, pointermove: function(evt, x, y) { if (this._linkView) { // let the linkview deal with this event this._linkView.pointermove(evt, x, y); } else { var grid = this.paper.options.gridSize; if (this.can('elementMove')) { var position = this.model.get('position'); // Make sure the new element's position always snaps to the current grid after // translate as the previous one could be calculated with a different grid size. var tx = g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid); var ty = g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid); this.model.translate(tx, ty, { restrictedArea: this.restrictedArea, ui: true }); if (this.paper.options.embeddingMode) { if (!this._inProcessOfEmbedding) { // Prepare the element for embedding only if the pointer moves. // We don't want to do unnecessary action with the element // if an user only clicks/dblclicks on it. this.prepareEmbedding(); this._inProcessOfEmbedding = true; } this.processEmbedding(); } } this._dx = g.snapToGrid(x, grid); this._dy = g.snapToGrid(y, grid); joint.dia.CellView.prototype.pointermove.apply(this, arguments); this.notify('element:pointermove', evt, x, y); } }, pointerup: function(evt, x, y) { if (this._linkView) { // Let the linkview deal with this event. this._linkView.pointerup(evt, x, y); this._linkView = null; this.model.stopBatch('add-link'); } else { if (this._inProcessOfEmbedding) { this.finalizeEmbedding(); this._inProcessOfEmbedding = false; } this.notify('element:pointerup', evt, x, y); joint.dia.CellView.prototype.pointerup.apply(this, arguments); } } }); // JointJS diagramming library. // (c) 2011-2015 client IO // joint.dia.Link base model. // -------------------------- joint.dia.Link = joint.dia.Cell.extend({ // The default markup for links. markup: [ '<path class="connection" stroke="black" d="M 0 0 0 0"/>', '<path class="marker-source" fill="black" stroke="black" d="M 0 0 0 0"/>', '<path class="marker-target" fill="black" stroke="black" d="M 0 0 0 0"/>', '<path class="connection-wrap" d="M 0 0 0 0"/>', '<g class="labels"/>', '<g class="marker-vertices"/>', '<g class="marker-arrowheads"/>', '<g class="link-tools"/>' ].join(''), labelMarkup: [ '<g class="label">', '<rect />', '<text />', '</g>' ].join(''), toolMarkup: [ '<g class="link-tool">', '<g class="tool-remove" event="remove">', '<circle r="11" />', '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z" />', '<title>Remove link.</title>', '</g>', '<g class="tool-options" event="link:options">', '<circle r="11" transform="translate(25)"/>', '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>', '<title>Link options.</title>', '</g>', '</g>' ].join(''), // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`). // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for // dragging vertices (changin their position). The latter is used for removing vertices. vertexMarkup: [ '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">', '<circle class="marker-vertex" idx="<%= idx %>" r="10" />', '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>', '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">', '<title>Remove vertex.</title>', '</path>', '</g>' ].join(''), arrowheadMarkup: [ '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">', '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />', '</g>' ].join(''), defaults: { type: 'link', source: {}, target: {} }, isLink: function() { return true; }, disconnect: function() { return this.set({ source: g.point(0, 0), target: g.point(0, 0) }); }, // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter. label: function(idx, value) { idx = idx || 0; var labels = this.get('labels') || []; // Is it a getter? if (arguments.length === 0 || arguments.length === 1) { return labels[idx]; } var newValue = _.merge({}, labels[idx], value); var newLabels = labels.slice(); newLabels[idx] = newValue; return this.set({ labels: newLabels }); }, translate: function(tx, ty, opt) { // enrich the option object opt = opt || {}; opt.translateBy = opt.translateBy || this.id; opt.tx = tx; opt.ty = ty; return this.applyToPoints(function(p) { return { x: (p.x || 0) + tx, y: (p.y || 0) + ty }; }, opt); }, scale: function(sx, sy, origin, opt) { return this.applyToPoints(function(p) { return g.point(p).scale(sx, sy, origin).toJSON(); }, opt); }, applyToPoints: function(fn, opt) { if (!_.isFunction(fn)) { throw new TypeError('dia.Link: applyToPoints expects its first parameter to be a function.'); } var attrs = {}; var source = this.get('source'); if (!source.id) { attrs.source = fn(source); } var target = this.get('target'); if (!target.id) { attrs.target = fn(target); } var vertices = this.get('vertices'); if (vertices && vertices.length > 0) { attrs.vertices = _.map(vertices, fn); } return this.set(attrs, opt); }, reparent: function(opt) { var newParent; if (this.graph) { var source = this.graph.getCell(this.get('source').id); var target = this.graph.getCell(this.get('target').id); var prevParent = this.graph.getCell(this.get('parent')); if (source && target) { newParent = this.graph.getCommonAncestor(source, target); } if (prevParent && (!newParent || newParent.id !== prevParent.id)) { // Unembed the link if source and target has no common ancestor // or common ancestor changed prevParent.unembed(this, opt); } if (newParent) { newParent.embed(this, opt); } } return newParent; }, hasLoop: function(opt) { opt = opt || {}; var sourceId = this.get('source').id; var targetId = this.get('target').id; if (!sourceId || !targetId) { // Link "pinned" to the paper does not have a loop. return false; } var loop = sourceId === targetId; // Note that there in the deep mode a link can have a loop, // even if it connects only a parent and its embed. // A loop "target equals source" is valid in both shallow and deep mode. if (!loop && opt.deep && this.graph) { var sourceElement = this.graph.getCell(sourceId); var targetElement = this.graph.getCell(targetId); loop = sourceElement.isEmbeddedIn(targetElement) || targetElement.isEmbeddedIn(sourceElement); } return loop; }, getSourceElement: function() { var source = this.get('source'); return (source && source.id && this.graph && this.graph.getCell(source.id)) || null; }, getTargetElement: function() { var target = this.get('target'); return (target && target.id && this.graph && this.graph.getCell(target.id)) || null; }, // Returns the common ancestor for the source element, // target element and the link itself. getRelationshipAncestor: function() { var connectionAncestor; if (this.graph) { var cells = _.compact([ this, this.getSourceElement(), // null if source is a point this.getTargetElement() // null if target is a point ]); connectionAncestor = this.graph.getCommonAncestor.apply(this.graph, cells); } return connectionAncestor || null; }, // Is source, target and the link itself embedded in a given element? isRelationshipEmbeddedIn: function(element) { var elementId = _.isString(element) ? element : element.id; var ancestor = this.getRelationshipAncestor(); return !!ancestor && (ancestor.id === elementId || ancestor.isEmbeddedIn(elementId)); } }, { endsEqual: function(a, b) { var portsEqual = a.port === b.port || !a.port && !b.port; return a.id === b.id && portsEqual; } }); // joint.dia.Link base view and controller. // ---------------------------------------- joint.dia.LinkView = joint.dia.CellView.extend({ className: function() { var classNames = joint.dia.CellView.prototype.className.apply(this).split(' '); classNames.push('link'); return classNames.join(' '); }, options: { shortLinkLength: 100, doubleLinkTools: false, longLinkLength: 160, linkToolsOffset: 40, doubleLinkToolsOffset: 60, sampleInterval: 50 }, _z: null, initialize: function(options) { joint.dia.CellView.prototype.initialize.apply(this, arguments); // create methods in prototype, so they can be accessed from any instance and // don't need to be create over and over if (typeof this.constructor.prototype.watchSource !== 'function') { this.constructor.prototype.watchSource = this.createWatcher('source'); this.constructor.prototype.watchTarget = this.createWatcher('target'); } // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the // nodes in `updateLabelPosition()` in order to update the label positions. this._labelCache = {}; // keeps markers bboxes and positions again for quicker access this._markerCache = {}; // bind events this.startListening(); }, startListening: function() { var model = this.model; this.listenTo(model, 'change:markup', this.render); this.listenTo(model, 'change:smooth change:manhattan change:router change:connector', this.update); this.listenTo(model, 'change:toolMarkup', this.onToolsChange); this.listenTo(model, 'change:labels change:labelMarkup', this.onLabelsChange); this.listenTo(model, 'change:vertices change:vertexMarkup', this.onVerticesChange); this.listenTo(model, 'change:source', this.onSourceChange); this.listenTo(model, 'change:target', this.onTargetChange); }, onSourceChange: function(cell, source, opt) { // Start watching the new source model. this.watchSource(cell, source); // This handler is called when the source attribute is changed. // This can happen either when someone reconnects the link (or moves arrowhead), // or when an embedded link is translated by its ancestor. // 1. Always do update. // 2. Do update only if the opposite end ('target') is also a point. if (!opt.translateBy || !this.model.get('target').id) { opt.updateConnectionOnly = true; this.update(this.model, null, opt); } }, onTargetChange: function(cell, target, opt) { // Start watching the new target model. this.watchTarget(cell, target); // See `onSourceChange` method. if (!opt.translateBy) { opt.updateConnectionOnly = true; this.update(this.model, null, opt); } }, onVerticesChange: function(cell, changed, opt) { this.renderVertexMarkers(); // If the vertices have been changed by a translation we do update only if the link was // the only link that was translated. If the link was translated via another element which the link // is embedded in, this element will be translated as well and that triggers an update. // Note that all embeds in a model are sorted - first comes links, then elements. if (!opt.translateBy || opt.translateBy === this.model.id) { // Vertices were changed (not as a reaction on translate) // or link.translate() was called or opt.updateConnectionOnly = true; this.update(cell, null, opt); } }, onToolsChange: function() { this.renderTools().updateToolsPosition(); }, onLabelsChange: function() { this.renderLabels().updateLabelPositions(); }, // Rendering //---------- render: function() { this.$el.empty(); // A special markup can be given in the `properties.markup` property. This might be handy // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s. // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors // of elements with special meaning though. Therefore, those classes should be preserved in any // special markup passed in `properties.markup`. var model = this.model; var markup = model.get('markup') || model.markup; var children = V(markup); // custom markup may contain only one children if (!_.isArray(children)) children = [children]; // Cache all children elements for quicker access. this._V = {}; // vectorized markup; _.each(children, function(child) { var className = child.attr('class'); if (className) { // Strip the joint class name prefix, if there is one. className = joint.util.removeClassNamePrefix(className); this._V[$.camelCase(className)] = child; } }, this); // Only the connection path is mandatory if (!this._V.connection) throw new Error('link: no connection path in the markup'); // partial rendering this.renderTools(); this.renderVertexMarkers(); this.renderArrowheadMarkers(); this.vel.append(children); // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox // returns zero values) this.renderLabels(); // start watching the ends of the link for changes this.watchSource(model, model.get('source')) .watchTarget(model, model.get('target')) .update(); return this; }, renderLabels: function() { if (!this._V.labels) return this; this._labelCache = {}; var $labels = $(this._V.labels.node).empty(); var labels = this.model.get('labels') || []; if (!labels.length) return this; var labelTemplate = joint.util.template(this.model.get('labelMarkup') || this.model.labelMarkup); // This is a prepared instance of a vectorized SVGDOM node for the label element resulting from // compilation of the labelTemplate. The purpose is that all labels will just `clone()` this // node to create a duplicate. var labelNodeInstance = V(labelTemplate()); var canLabelMove = this.can('labelMove'); _.each(labels, function(label, idx) { var labelNode = labelNodeInstance.clone().node; V(labelNode).attr('label-idx', idx); if (canLabelMove) { V(labelNode).attr('cursor', 'move'); } // Cache label nodes so that the `updateLabels()` can just update the label node positions. this._labelCache[idx] = V(labelNode); var $text = $(labelNode).find('text'); var $rect = $(labelNode).find('rect'); // Text attributes with the default `text-anchor` and font-size set. var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/')); $text.attr(_.omit(textAttributes, 'text')); if (!_.isUndefined(textAttributes.text)) { V($text[0]).text(textAttributes.text + '', { annotations: textAttributes.annotations }); } // Note that we first need to append the `<text>` element to the DOM in order to // get its bounding box. $labels.append(labelNode); // `y-alignment` - center the text element around its y coordinate. var textBbox = V($text[0]).bbox(true, $labels[0]); V($text[0]).translate(0, -textBbox.height / 2); // Add default values. var rectAttributes = _.extend({ fill: 'white', rx: 3, ry: 3 }, joint.util.getByPath(label, 'attrs/rect', '/')); $rect.attr(_.extend(rectAttributes, { x: textBbox.x, y: textBbox.y - textBbox.height / 2, // Take into account the y-alignment translation. width: textBbox.width, height: textBbox.height })); }, this); return this; }, renderTools: function() { if (!this._V.linkTools) return this; // Tools are a group of clickable elements that manipulate the whole link. // A good example of this is the remove tool that removes the whole link. // Tools appear after hovering the link close to the `source` element/point of the link // but are offset a bit so that they don't cover the `marker-arrowhead`. var $tools = $(this._V.linkTools.node).empty(); var toolTemplate = joint.util.template(this.model.get('toolMarkup') || this.model.toolMarkup); var tool = V(toolTemplate()); $tools.append(tool.node); // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly. this._toolCache = tool; // If `doubleLinkTools` is enabled, we render copy of the tools on the other side of the // link as well but only if the link is longer than `longLinkLength`. if (this.options.doubleLinkTools) { var tool2; if (this.model.get('doubleToolMarkup') || this.model.doubleToolMarkup) { toolTemplate = joint.util.template(this.model.get('doubleToolMarkup') || this.model.doubleToolMarkup); tool2 = V(toolTemplate()); } else { tool2 = tool.clone(); } $tools.append(tool2.node); this._tool2Cache = tool2; } return this; }, renderVertexMarkers: function() { if (!this._V.markerVertices) return this; var $markerVertices = $(this._V.markerVertices.node).empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = joint.util.template(this.model.get('vertexMarkup') || this.model.vertexMarkup); _.each(this.model.get('vertices'), function(vertex, idx) { $markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node); }); return this; }, renderArrowheadMarkers: function() { // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case. if (!this._V.markerArrowheads) return this; var $markerArrowheads = $(this._V.markerArrowheads.node); $markerArrowheads.empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = joint.util.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup); this._V.sourceArrowhead = V(markupTemplate({ end: 'source' })); this._V.targetArrowhead = V(markupTemplate({ end: 'target' })); $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node); return this; }, // Updating //--------- // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function(model, attributes, opt) { opt = opt || {}; if (!opt.updateConnectionOnly) { // update SVG attributes defined by 'attrs/'. this.updateAttributes(); } // update the link path, label position etc. this.updateConnection(opt); this.updateLabelPositions(); this.updateToolsPosition(); this.updateArrowheadMarkers(); // Local perpendicular flag (as opposed to one defined on paper). // Could be enabled inside a connector/router. It's valid only // during the update execution. this.options.perpendicular = null; // Mark that postponed update has been already executed. this.updatePostponed = false; return this; }, updateConnection: function(opt) { opt = opt || {}; var model = this.model; var route; if (opt.translateBy && model.isRelationshipEmbeddedIn(opt.translateBy)) { // The link is being translated by an ancestor that will // shift source point, target point and all vertices // by an equal distance. var tx = opt.tx || 0; var ty = opt.ty || 0; route = this.route = _.map(this.route, function(point) { // translate point by point by delta translation return g.point(point).offset(tx, ty); }); // translate source and target connection and marker points. this._translateConnectionPoints(tx, ty); } else { // Necessary path finding route = this.route = this.findRoute(model.get('vertices') || [], opt); // finds all the connection points taking new vertices into account this._findConnectionPoints(route); } var pathData = this.getPathData(route); // The markup needs to contain a `.connection` this._V.connection.attr('d', pathData); this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData); this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget); }, updateAttributes: function() { // Update attributes. _.each(this.model.get('attrs'), function(attrs, selector) { var processedAttributes = []; // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.fill)) { this.applyGradient(selector, 'fill', attrs.fill); processedAttributes.push('fill'); } if (_.isObject(attrs.stroke)) { this.applyGradient(selector, 'stroke', attrs.stroke); processedAttributes.push('stroke'); } // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { this.applyFilter(selector, attrs.filter); processedAttributes.push('filter'); } // remove processed special attributes from attrs if (processedAttributes.length > 0) { processedAttributes.unshift(attrs); attrs = _.omit.apply(_, processedAttributes); } this.findBySelector(selector).attr(attrs); }, this); }, _findConnectionPoints: function(vertices) { // cache source and target points var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint; var firstVertex = _.first(vertices); sourcePoint = this.getConnectionPoint( 'source', this.model.get('source'), firstVertex || this.model.get('target') ).round(); var lastVertex = _.last(vertices); targetPoint = this.getConnectionPoint( 'target', this.model.get('target'), lastVertex || sourcePoint ).round(); // Move the source point by the width of the marker taking into account // its scale around x-axis. Note that scale is the only transform that // makes sense to be set in `.marker-source` attributes object // as all other transforms (translate/rotate) will be replaced // by the `translateAndAutoOrient()` function. var cache = this._markerCache; if (this._V.markerSource) { cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true); sourceMarkerPoint = g.point(sourcePoint).move( firstVertex || targetPoint, cache.sourceBBox.width * this._V.markerSource.scale().sx * -1 ).round(); } if (this._V.markerTarget) { cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true); targetMarkerPoint = g.point(targetPoint).move( lastVertex || sourcePoint, cache.targetBBox.width * this._V.markerTarget.scale().sx * -1 ).round(); } // if there was no markup for the marker, use the connection point. cache.sourcePoint = sourceMarkerPoint || sourcePoint; cache.targetPoint = targetMarkerPoint || targetPoint; // make connection points public this.sourcePoint = sourcePoint; this.targetPoint = targetPoint; }, _translateConnectionPoints: function(tx, ty) { var cache = this._markerCache; cache.sourcePoint.offset(tx, ty); cache.targetPoint.offset(tx, ty); this.sourcePoint.offset(tx, ty); this.targetPoint.offset(tx, ty); }, updateLabelPositions: function() { if (!this._V.labels) return this; // This method assumes all the label nodes are stored in the `this._labelCache` hash table // by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method. var labels = this.model.get('labels') || []; if (!labels.length) return this; var connectionElement = this._V.connection.node; var connectionLength = connectionElement.getTotalLength(); // Firefox returns connectionLength=NaN in odd cases (for bezier curves). // In that case we won't update labels at all. if (!_.isNaN(connectionLength)) { var samples; _.each(labels, function(label, idx) { var position = label.position; var distance = _.isObject(position) ? position.distance : position; var offset = _.isObject(position) ? position.offset : { x: 0, y: 0 }; if (!_.isNaN(distance)) { distance = (distance > connectionLength) ? connectionLength : distance; // sanity check distance = (distance < 0) ? connectionLength + distance : distance; distance = (distance > 1) ? distance : connectionLength * distance; } else { distance = connectionLength / 2; } var labelCoordinates = connectionElement.getPointAtLength(distance); if (_.isObject(offset)) { // Just offset the label by the x,y provided in the offset object. labelCoordinates = g.point(labelCoordinates).offset(offset.x, offset.y); } else if (_.isNumber(offset)) { if (!samples) { samples = this._samples || this._V.connection.sample(this.options.sampleInterval); } // Offset the label by the amount provided in `offset` to an either // side of the link. // 1. Find the closest sample & its left and right neighbours. var minSqDistance = Infinity; var closestSample; var closestSampleIndex; var p; var sqDistance; for (var i = 0, len = samples.length; i < len; i++) { p = samples[i]; sqDistance = g.line(p, labelCoordinates).squaredLength(); if (sqDistance < minSqDistance) { minSqDistance = sqDistance; closestSample = p; closestSampleIndex = i; } } var prevSample = samples[closestSampleIndex - 1]; var nextSample = samples[closestSampleIndex + 1]; // 2. Offset the label on the perpendicular line between // the current label coordinate ("at `distance`") and // the next sample. var angle = 0; if (nextSample) { angle = g.point(labelCoordinates).theta(nextSample); } else if (prevSample) { angle = g.point(prevSample).theta(labelCoordinates); } labelCoordinates = g.point(labelCoordinates).offset(offset).rotate(labelCoordinates, angle - 90); } this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')'); }, this); } return this; }, updateToolsPosition: function() { if (!this._V.linkTools) return this; // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker. // Note that the offset is hardcoded here. The offset should be always // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking // this up all the time would be slow. var scale = ''; var offset = this.options.linkToolsOffset; var connectionLength = this.getConnectionLength(); // Firefox returns connectionLength=NaN in odd cases (for bezier curves). // In that case we won't update tools position at all. if (!_.isNaN(connectionLength)) { // If the link is too short, make the tools half the size and the offset twice as low. if (connectionLength < this.options.shortLinkLength) { scale = 'scale(.5)'; offset /= 2; } var toolPosition = this.getPointAtLength(offset); this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); if (this.options.doubleLinkTools && connectionLength >= this.options.longLinkLength) { var doubleLinkToolsOffset = this.options.doubleLinkToolsOffset || offset; toolPosition = this.getPointAtLength(connectionLength - doubleLinkToolsOffset); this._tool2Cache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); this._tool2Cache.attr('visibility', 'visible'); } else if (this.options.doubleLinkTools) { this._tool2Cache.attr('visibility', 'hidden'); } } return this; }, updateArrowheadMarkers: function() { if (!this._V.markerArrowheads) return this; // getting bbox of an element with `display="none"` in IE9 ends up with access violation if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this; var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1; this._V.sourceArrowhead.scale(sx); this._V.targetArrowhead.scale(sx); this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead); return this; }, // Returns a function observing changes on an end of the link. If a change happens and new end is a new model, // it stops listening on the previous one and starts listening to the new one. createWatcher: function(endType) { // create handler for specific end type (source|target). var onModelChange = _.partial(this.onEndModelChange, endType); function watchEndModel(link, end) { end = end || {}; var endModel = null; var previousEnd = link.previous(endType) || {}; if (previousEnd.id) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', onModelChange); } if (end.id) { // If the observed model changes, it caches a new bbox and do the link update. endModel = this.paper.getModelById(end.id); this.listenTo(endModel, 'change', onModelChange); } onModelChange.call(this, endModel, { cacheOnly: true }); return this; } return watchEndModel; }, onEndModelChange: function(endType, endModel, opt) { var doUpdate = !opt.cacheOnly; var model = this.model; var end = model.get(endType) || {}; if (endModel) { var selector = this.constructor.makeSelector(end); var oppositeEndType = endType == 'source' ? 'target' : 'source'; var oppositeEnd = model.get(oppositeEndType) || {}; var oppositeSelector = oppositeEnd.id && this.constructor.makeSelector(oppositeEnd); // Caching end models bounding boxes. // If `opt.handleBy` equals the client-side ID of this link view and it is a loop link, then we already cached // the bounding boxes in the previous turn (e.g. for loop link, the change:source event is followed // by change:target and so on change:source, we already chached the bounding boxes of - the same - element). if (opt.handleBy === this.cid && selector == oppositeSelector) { // Source and target elements are identical. We're dealing with a loop link. We are handling `change` event for the // second time now. There is no need to calculate bbox and find magnet element again. // It was calculated already for opposite link end. this[endType + 'BBox'] = this[oppositeEndType + 'BBox']; this[endType + 'View'] = this[oppositeEndType + 'View']; this[endType + 'Magnet'] = this[oppositeEndType + 'Magnet']; } else if (opt.translateBy) { // `opt.translateBy` optimizes the way we calculate bounding box of the source/target element. // If `opt.translateBy` is an ID of the element that was originally translated. This allows us // to just offset the cached bounding box by the translation instead of calculating the bounding // box from scratch on every translate. var bbox = this[endType + 'BBox']; bbox.x += opt.tx; bbox.y += opt.ty; } else { // The slowest path, source/target could have been rotated or resized or any attribute // that affects the bounding box of the view might have been changed. var view = this.paper.findViewByModel(end.id); var magnetElement = view.el.querySelector(selector); this[endType + 'BBox'] = view.getStrokeBBox(magnetElement); this[endType + 'View'] = view; this[endType + 'Magnet'] = magnetElement; } if (opt.handleBy === this.cid && opt.translateBy && model.isEmbeddedIn(endModel) && !_.isEmpty(model.get('vertices'))) { // Loop link whose element was translated and that has vertices (that need to be translated with // the parent in which my element is embedded). // If the link is embedded, has a loop and vertices and the end model // has been translated, do not update yet. There are vertices still to be updated (change:vertices // event will come in the next turn). doUpdate = false; } if (!this.updatePostponed && oppositeEnd.id) { // The update was not postponed (that can happen e.g. on the first change event) and the opposite // end is a model (opposite end is the opposite end of the link we're just updating, e.g. if // we're reacting on change:source event, the oppositeEnd is the target model). var oppositeEndModel = this.paper.getModelById(oppositeEnd.id); // Passing `handleBy` flag via event option. // Note that if we are listening to the same model for event 'change' twice. // The same event will be handled by this method also twice. if (end.id === oppositeEnd.id) { // We're dealing with a loop link. Tell the handlers in the next turn that they should update // the link instead of me. (We know for sure there will be a next turn because // loop links react on at least two events: change on the source model followed by a change on // the target model). opt.handleBy = this.cid; } if (opt.handleBy === this.cid || (opt.translateBy && oppositeEndModel.isEmbeddedIn(opt.translateBy))) { // Here are two options: // - Source and target are connected to the same model (not necessarily the same port). // - Both end models are translated by the same ancestor. We know that opposite end // model will be translated in the next turn as well. // In both situations there will be more changes on the model that trigger an // update. So there is no need to update the linkView yet. this.updatePostponed = true; doUpdate = false; } } } else { // the link end is a point ~ rect 1x1 this[endType + 'BBox'] = g.rect(end.x || 0, end.y || 0, 1, 1); this[endType + 'View'] = this[endType + 'Magnet'] = null; } if (doUpdate) { opt.updateConnectionOnly = true; this.update(model, null, opt); } }, _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) { // Make the markers "point" to their sticky points being auto-oriented towards // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them. if (sourceArrow) { sourceArrow.translateAndAutoOrient( this.sourcePoint, _.first(this.route) || this.targetPoint, this.paper.viewport ); } if (targetArrow) { targetArrow.translateAndAutoOrient( this.targetPoint, _.last(this.route) || this.sourcePoint, this.paper.viewport ); } }, removeVertex: function(idx) { var vertices = _.clone(this.model.get('vertices')); if (vertices && vertices.length) { vertices.splice(idx, 1); this.model.set('vertices', vertices, { ui: true }); } return this; }, // This method ads a new vertex to the `vertices` array of `.connection`. This method // uses a heuristic to find the index at which the new `vertex` should be placed at assuming // the new vertex is somewhere on the path. addVertex: function(vertex) { // As it is very hard to find a correct index of the newly created vertex, // a little heuristics is taking place here. // The heuristics checks if length of the newly created // path is lot more than length of the old path. If this is the case, // new vertex was probably put into a wrong index. // Try to put it into another index and repeat the heuristics again. var vertices = (this.model.get('vertices') || []).slice(); // Store the original vertices for a later revert if needed. var originalVertices = vertices.slice(); // A `<path>` element used to compute the length of the path during heuristics. var path = this._V.connection.node.cloneNode(false); // Length of the original path. var originalPathLength = path.getTotalLength(); // Current path length. var pathLength; // Tolerance determines the highest possible difference between the length // of the old and new path. The number has been chosen heuristically. var pathLengthTolerance = 20; // Total number of vertices including source and target points. var idx = vertices.length + 1; // Loop through all possible indexes and check if the difference between // path lengths changes significantly. If not, the found index is // most probably the right one. while (idx--) { vertices.splice(idx, 0, vertex); V(path).attr('d', this.getPathData(this.findRoute(vertices))); pathLength = path.getTotalLength(); // Check if the path lengths changed significantly. if (pathLength - originalPathLength > pathLengthTolerance) { // Revert vertices to the original array. The path length has changed too much // so that the index was not found yet. vertices = originalVertices.slice(); } else { break; } } if (idx === -1) { // If no suitable index was found for such a vertex, make the vertex the first one. idx = 0; vertices.splice(idx, 0, vertex); } this.model.set('vertices', vertices, { ui: true }); return idx; }, // Send a token (an SVG element, usually a circle) along the connection path. // Example: `paper.findViewByModel(link).sendToken(V('circle', { r: 7, fill: 'green' }).node)` // `duration` is optional and is a time in milliseconds that the token travels from the source to the target of the link. Default is `1000`. // `callback` is optional and is a function to be called once the token reaches the target. sendToken: function(token, duration, callback) { duration = duration || 1000; V(this.paper.viewport).append(token); V(token).animateAlongPath({ dur: duration + 'ms', repeatCount: 1 }, this._V.connection.node); _.delay(function() { V(token).remove(); callback && callback(); }, duration); }, findRoute: function(oldVertices) { var namespace = joint.routers; var router = this.model.get('router'); var defaultRouter = this.paper.options.defaultRouter; if (!router) { if (this.model.get('manhattan')) { // backwards compability router = { name: 'orthogonal' }; } else if (defaultRouter) { router = defaultRouter; } else { return oldVertices; } } var args = router.args || {}; var routerFn = _.isFunction(router) ? router : namespace[router.name]; if (!_.isFunction(routerFn)) { throw new Error('unknown router: "' + router.name + '"'); } var newVertices = routerFn.call(this, oldVertices || [], args, this); return newVertices; }, // Return the `d` attribute value of the `<path>` element representing the link // between `source` and `target`. getPathData: function(vertices) { var namespace = joint.connectors; var connector = this.model.get('connector'); var defaultConnector = this.paper.options.defaultConnector; if (!connector) { // backwards compability if (this.model.get('smooth')) { connector = { name: 'smooth' }; } else { connector = defaultConnector || {}; } } var connectorFn = _.isFunction(connector) ? connector : namespace[connector.name]; var args = connector.args || {}; if (!_.isFunction(connectorFn)) { throw new Error('unknown connector: "' + connector.name + '"'); } var pathData = connectorFn.call( this, this._markerCache.sourcePoint, // Note that the value is translated by the size this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint) vertices || (this.model.get('vertices') || {}), args, // options this ); return pathData; }, // Find a point that is the start of the connection. // If `selectorOrPoint` is a point, then we're done and that point is the start of the connection. // If the `selectorOrPoint` is an element however, we need to know a reference point (or element) // that the link leads to in order to determine the start of the connection on the original element. getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) { var spot; // If the `selectorOrPoint` (or `referenceSelectorOrPoint`) is `undefined`, the `source`/`target` of the link model is `undefined`. // We want to allow this however so that one can create links such as `var link = new joint.dia.Link` and // set the `source`/`target` later. _.isEmpty(selectorOrPoint) && (selectorOrPoint = { x: 0, y: 0 }); _.isEmpty(referenceSelectorOrPoint) && (referenceSelectorOrPoint = { x: 0, y: 0 }); if (!selectorOrPoint.id) { // If the source is a point, we don't need a reference point to find the sticky point of connection. spot = g.point(selectorOrPoint); } else { // If the source is an element, we need to find a point on the element boundary that is closest // to the reference point (or reference element). // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). // `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`) // method, it exists since first render and are automatically updated var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox; var reference; if (!referenceSelectorOrPoint.id) { // Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element. reference = g.point(referenceSelectorOrPoint); } else { // Reference was passed as an element, therefore we need to find a point on the reference // element boundary closest to the source element. // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox; reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center()); reference = reference || g.rect(referenceBbox).center(); } // If `perpendicularLinks` flag is set on the paper and there are vertices // on the link, then try to find a connection point that makes the link perpendicular // even though the link won't point to the center of the targeted object. if (this.paper.options.perpendicularLinks || this.options.perpendicular) { var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1); var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height); var nearestSide; if (horizontalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'left': spot = g.point(spotBbox.x, reference.y); break; case 'right': spot = g.point(spotBbox.x + spotBbox.width, reference.y); break; default: spot = g.rect(spotBbox).center(); break; } } else if (verticalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'top': spot = g.point(reference.x, spotBbox.y); break; case 'bottom': spot = g.point(reference.x, spotBbox.y + spotBbox.height); break; default: spot = g.rect(spotBbox).center(); break; } } else { // If there is no intersection horizontally or vertically with the object bounding box, // then we fall back to the regular situation finding straight line (not perpendicular) // between the object and the reference point. spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } else if (this.paper.options.linkConnectionPoint) { var view = end === 'target' ? this.targetView : this.sourceView; var magnet = end === 'target' ? this.targetMagnet : this.sourceMagnet; spot = this.paper.options.linkConnectionPoint(this, view, magnet, reference); } else { spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } return spot; }, // Public API // ---------- getConnectionLength: function() { return this._V.connection.node.getTotalLength(); }, getPointAtLength: function(length) { return this._V.connection.node.getPointAtLength(length); }, // Interaction. The controller part. // --------------------------------- _beforeArrowheadMove: function() { this._z = this.model.get('z'); this.model.toFront(); // Let the pointer propagate throught the link view elements so that // the `evt.target` is another element under the pointer, not the link itself. this.el.style.pointerEvents = 'none'; if (this.paper.options.markAvailable) { this._markAvailableMagnets(); } }, _afterArrowheadMove: function() { if (!_.isNull(this._z)) { this.model.set('z', this._z, { ui: true }); this._z = null; } // Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation. // Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead. // See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`. this.el.style.pointerEvents = 'visiblePainted'; if (this.paper.options.markAvailable) { this._unmarkAvailableMagnets(); } }, _createValidateConnectionArgs: function(arrowhead) { // It makes sure the arguments for validateConnection have the following form: // (source view, source magnet, target view, target magnet and link view) var args = []; args[4] = arrowhead; args[5] = this; var oppositeArrowhead; var i = 0; var j = 0; if (arrowhead === 'source') { i = 2; oppositeArrowhead = 'target'; } else { j = 2; oppositeArrowhead = 'source'; } var end = this.model.get(oppositeArrowhead); if (end.id) { args[i] = this.paper.findViewByModel(end.id); args[i + 1] = end.selector && args[i].el.querySelector(end.selector); } function validateConnectionArgs(cellView, magnet) { args[j] = cellView; args[j + 1] = cellView.el === magnet ? undefined : magnet; return args; } return validateConnectionArgs; }, _markAvailableMagnets: function() { function isMagnetAvailable(view, magnet) { var paper = view.paper; var validate = paper.options.validateConnection; return validate.apply(paper, this._validateConnectionArgs(view, magnet)); } var paper = this.paper; var elements = paper.model.getElements(); this._marked = {}; _.chain(elements).map(paper.findViewByModel, paper).each(function(view) { var magnets = Array.prototype.slice.call(view.el.querySelectorAll('[magnet]')); if (view.el.getAttribute('magnet') !== 'false') { // Element wrapping group is also a magnet magnets.push(view.el); } var availableMagnets = _.filter(magnets, _.partial(isMagnetAvailable, view), this); if (availableMagnets.length > 0) { // highlight all available magnets _.each(availableMagnets, _.partial(view.highlight, _, { magnetAvailability: true }), view); // highlight the entire view view.highlight(null, { elementAvailability: true }); this._marked[view.model.id] = availableMagnets; } }, this).value(); }, _unmarkAvailableMagnets: function() { _.each(this._marked, function(markedMagnets, id) { var view = this.paper.findViewByModel(id); if (view) { _.each(markedMagnets, _.partial(view.unhighlight, _, { magnetAvailability: true }), view); view.unhighlight(null, { elementAvailability: true }); } }, this); this._marked = null; }, startArrowheadMove: function(end, opt) { opt = _.defaults(opt || {}, { whenNotAllowed: 'revert' }); // Allow to delegate events from an another view to this linkView in order to trigger arrowhead // move without need to click on the actual arrowhead dom element. this._action = 'arrowhead-move'; this._whenNotAllowed = opt.whenNotAllowed; this._arrowhead = end; this._initialMagnet = this[end + 'Magnet'] || (this[end + 'View'] ? this[end + 'View'].el : null); this._initialEnd = _.clone(this.model.get(end)) || { x: 0, y: 0 }; this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead); this._beforeArrowheadMove(); }, pointerdown: function(evt, x, y) { joint.dia.CellView.prototype.pointerdown.apply(this, arguments); this.notify('link:pointerdown', evt, x, y); this._dx = x; this._dy = y; // if are simulating pointerdown on a link during a magnet click, skip link interactions if (evt.target.getAttribute('magnet') != null) return; var className = joint.util.removeClassNamePrefix(evt.target.getAttribute('class')); var parentClassName = joint.util.removeClassNamePrefix(evt.target.parentNode.getAttribute('class')); var labelNode; if (parentClassName === 'label') { className = parentClassName; labelNode = evt.target.parentNode; } else { labelNode = evt.target; } switch (className) { case 'marker-vertex': if (this.can('vertexMove')) { this._action = 'vertex-move'; this._vertexIdx = evt.target.getAttribute('idx'); } break; case 'marker-vertex-remove': case 'marker-vertex-remove-area': if (this.can('vertexRemove')) { this.removeVertex(evt.target.getAttribute('idx')); } break; case 'marker-arrowhead': if (this.can('arrowheadMove')) { this.startArrowheadMove(evt.target.getAttribute('end')); } break; case 'label': if (this.can('labelMove')) { this._action = 'label-move'; this._labelIdx = parseInt(V(labelNode).attr('label-idx'), 10); // Precalculate samples so that we don't have to do that // over and over again while dragging the label. this._samples = this._V.connection.sample(1); this._linkLength = this._V.connection.node.getTotalLength(); } break; default: var targetParentEvent = evt.target.parentNode.getAttribute('event'); if (targetParentEvent) { if (this.can('useLinkTools')) { // `remove` event is built-in. Other custom events are triggered on the paper. if (targetParentEvent === 'remove') { this.model.remove(); } else { this.notify(targetParentEvent, evt, x, y); } } } else { if (this.can('vertexAdd')) { // Store the index at which the new vertex has just been placed. // We'll be update the very same vertex position in `pointermove()`. this._vertexIdx = this.addVertex({ x: x, y: y }); this._action = 'vertex-move'; } } } }, pointermove: function(evt, x, y) { switch (this._action) { case 'vertex-move': var vertices = _.clone(this.model.get('vertices')); vertices[this._vertexIdx] = { x: x, y: y }; this.model.set('vertices', vertices, { ui: true }); break; case 'label-move': var dragPoint = { x: x, y: y }; var label = this.model.get('labels')[this._labelIdx]; var samples = this._samples; var minSqDistance = Infinity; var closestSample; var closestSampleIndex; var p; var sqDistance; for (var i = 0, len = samples.length; i < len; i++) { p = samples[i]; sqDistance = g.line(p, dragPoint).squaredLength(); if (sqDistance < minSqDistance) { minSqDistance = sqDistance; closestSample = p; closestSampleIndex = i; } } var prevSample = samples[closestSampleIndex - 1]; var nextSample = samples[closestSampleIndex + 1]; var closestSampleDistance = g.point(closestSample).distance(dragPoint); var offset = 0; if (prevSample && nextSample) { offset = g.line(prevSample, nextSample).pointOffset(dragPoint); } else if (prevSample) { offset = g.line(prevSample, closestSample).pointOffset(dragPoint); } else if (nextSample) { offset = g.line(closestSample, nextSample).pointOffset(dragPoint); } this.model.label(this._labelIdx, { position: { distance: closestSample.distance / this._linkLength, offset: offset } }); break; case 'arrowhead-move': if (this.paper.options.snapLinks) { // checking view in close area of the pointer var r = this.paper.options.snapLinks.radius || 50; var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r }); if (this._closestView) { this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true }); } this._closestView = this._closestEnd = null; var distance; var minDistance = Number.MAX_VALUE; var pointer = g.point(x, y); _.each(viewsInArea, function(view) { // skip connecting to the element in case '.': { magnet: false } attribute present if (view.el.getAttribute('magnet') !== 'false') { // find distance from the center of the model to pointer coordinates distance = view.model.getBBox().center().distance(pointer); // the connection is looked up in a circle area by `distance < r` if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, null) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id }; } } } view.$('[magnet]').each(_.bind(function(index, magnet) { var bbox = V(magnet).bbox(false, this.paper.viewport); distance = pointer.distance({ x: bbox.x + bbox.width / 2, y: bbox.y + bbox.height / 2 }); if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, magnet) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id, selector: view.getSelector(magnet), port: magnet.getAttribute('port') }; } } }, this)); }, this); if (this._closestView) { this._closestView.highlight(this._closestEnd.selector, { connecting: true, snapping: true }); } this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y }, { ui: true }); } else { // checking views right under the pointer // Touchmove event's target is not reflecting the element under the coordinates as mousemove does. // It holds the element when a touchstart triggered. var target = (evt.type === 'mousemove') ? evt.target : document.elementFromPoint(evt.clientX, evt.clientY); if (this._targetEvent !== target) { // Unhighlight the previous view under pointer if there was one. if (this._magnetUnderPointer) { this._viewUnderPointer.unhighlight(this._magnetUnderPointer, { connecting: true }); } this._viewUnderPointer = this.paper.findView(target); if (this._viewUnderPointer) { // If we found a view that is under the pointer, we need to find the closest // magnet based on the real target element of the event. this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target); if (this._magnetUnderPointer && this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer) )) { // If there was no magnet found, do not highlight anything and assume there // is no view under pointer we're interested in reconnecting to. // This can only happen if the overall element has the attribute `'.': { magnet: false }`. if (this._magnetUnderPointer) { this._viewUnderPointer.highlight(this._magnetUnderPointer, { connecting: true }); } } else { // This type of connection is not valid. Disregard this magnet. this._magnetUnderPointer = null; } } else { // Make sure we'll unset previous magnet. this._magnetUnderPointer = null; } } this._targetEvent = target; this.model.set(this._arrowhead, { x: x, y: y }, { ui: true }); } break; } this._dx = x; this._dy = y; joint.dia.CellView.prototype.pointermove.apply(this, arguments); this.notify('link:pointermove', evt, x, y); }, pointerup: function(evt, x, y) { if (this._action === 'label-move') { this._samples = null; } else if (this._action === 'arrowhead-move') { var paper = this.paper; var paperOptions = paper.options; var arrowhead = this._arrowhead; var initialEnd = this._initialEnd; var magnetUnderPointer; if (paperOptions.snapLinks) { // Finish off link snapping. // Everything except view unhighlighting was already done on pointermove. if (this._closestView) { this._closestView.unhighlight(this._closestEnd.selector, { connecting: true, snapping: true }); magnetUnderPointer = this._closestView.findMagnet(this._closestEnd.selector); } this._closestView = this._closestEnd = null; } else { var viewUnderPointer = this._viewUnderPointer; magnetUnderPointer = this._magnetUnderPointer; this._viewUnderPointer = null; this._magnetUnderPointer = null; if (magnetUnderPointer) { viewUnderPointer.unhighlight(magnetUnderPointer, { connecting: true }); // Find a unique `selector` of the element under pointer that is a magnet. If the // `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself, // the returned `selector` will be `undefined`. That means we can directly pass it to the // `source`/`target` attribute of the link model below. var selector = viewUnderPointer.getSelector(magnetUnderPointer); var port = magnetUnderPointer.getAttribute('port'); var arrowheadValue = { id: viewUnderPointer.model.id }; if (selector != null) arrowheadValue.port = port; if (port != null) arrowheadValue.selector = selector; this.model.set(arrowhead, arrowheadValue, { ui: true }); } } // If the changed link is not allowed, revert to its previous state. if (!paper.linkAllowed(this)) { switch (this._whenNotAllowed) { case 'remove': this.model.remove(); break; case 'revert': default: this.model.set(arrowhead, initialEnd, { ui: true }); break; } } // Reparent the link if embedding is enabled if (paperOptions.embeddingMode && this.model.reparent()) { // Make sure we don't reverse to the original 'z' index (see afterArrowheadMove()). this._z = null; } var currentEnd = this.model.prop(arrowhead) || {}; var endChanged = !joint.dia.Link.endsEqual(initialEnd, currentEnd); if (endChanged) { if (initialEnd.id) { this.notify('link:disconnect', evt, paper.findViewByModel(initialEnd.id), this._initialMagnet, arrowhead); } if (currentEnd.id) { this.notify('link:connect', evt, paper.findViewByModel(currentEnd.id), magnetUnderPointer, arrowhead); } } this._afterArrowheadMove(); } this._action = null; this._whenNotAllowed = null; this._initialMagnet = null; this._initialEnd = null; this._validateConnectionArgs = null; this.notify('link:pointerup', evt, x, y); joint.dia.CellView.prototype.pointerup.apply(this, arguments); } }, { makeSelector: function(end) { var selector = '[model-id="' + end.id + '"]'; // `port` has a higher precendence over `selector`. This is because the selector to the magnet // might change while the name of the port can stay the same. if (end.port) { selector += ' [port="' + end.port + '"]'; } else if (end.selector) { selector += ' ' + end.selector; } return selector; } }); // JointJS library. // (c) 2011-2015 client IO joint.dia.Paper = joint.mvc.View.extend({ className: 'paper', options: { width: 800, height: 600, origin: { x: 0, y: 0 }, // x,y coordinates in top-left corner gridSize: 1, /* Whether or not to draw the grid lines on the paper's DOM element. e.g drawGrid: true, drawGrid: { color: 'red', thickness: 2 } */ drawGrid: false, perpendicularLinks: false, elementView: joint.dia.ElementView, linkView: joint.dia.LinkView, snapLinks: false, // false, true, { radius: value } // When set to FALSE, an element may not have more than 1 link with the same source and target element. multiLinks: true, // For adding custom guard logic. guard: function(evt, view) { // FALSE means the event isn't guarded. return false; }, highlighting: { 'default': { name: 'stroke', options: { padding: 3 } }, magnetAvailability: { name: 'addClass', options: { className: 'available-magnet' } }, elementAvailability: { name: 'addClass', options: { className: 'available-cell' } } }, // Prevent the default context menu from being displayed. preventContextMenu: true, // Restrict the translation of elements by given bounding box. // Option accepts a boolean: // true - the translation is restricted to the paper area // false - no restrictions // A method: // restrictTranslate: function(elementView) { // var parentId = elementView.model.get('parent'); // return parentId && this.model.getCell(parentId).getBBox(); // }, // Or a bounding box: // restrictTranslate: { x: 10, y: 10, width: 790, height: 590 } restrictTranslate: false, // Marks all available magnets with 'available-magnet' class name and all available cells with // 'available-cell' class name. Marks them when dragging a link is started and unmark // when the dragging is stopped. markAvailable: false, // Defines what link model is added to the graph after an user clicks on an active magnet. // Value could be the Backbone.model or a function returning the Backbone.model // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() } defaultLink: new joint.dia.Link, // A connector that is used by links with no connector defined on the model. // e.g. { name: 'rounded', args: { radius: 5 }} or a function defaultConnector: { name: 'normal' }, // A router that is used by links with no router defined on the model. // e.g. { name: 'oneSide', args: { padding: 10 }} or a function defaultRouter: { name: 'normal' }, /* CONNECTING */ // Check whether to add a new link to the graph when user clicks on an a magnet. validateMagnet: function(cellView, magnet) { return magnet.getAttribute('magnet') !== 'passive'; }, // Check whether to allow or disallow the link connection while an arrowhead end (source/target) // being changed. validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) { return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView; }, /* EMBEDDING */ // Enables embedding. Reparents the dragged element with elements under it and makes sure that // all links and elements are visible taken the level of embedding into account. embeddingMode: false, // Check whether to allow or disallow the element embedding while an element being translated. validateEmbedding: function(childView, parentView) { // by default all elements can be in relation child-parent return true; }, // Determines the way how a cell finds a suitable parent when it's dragged over the paper. // The cell with the highest z-index (visually on the top) will be choosen. findParentBy: 'bbox', // 'bbox'|'center'|'origin'|'corner'|'topRight'|'bottomLeft' // If enabled only the element on the very front is taken into account for the embedding. // If disabled the elements under the dragged view are tested one by one // (from front to back) until a valid parent found. frontParentOnly: true, // Interactive flags. See online docs for the complete list of interactive flags. interactive: { labelMove: false }, // When set to true the links can be pinned to the paper. // i.e. link source/target can be a point e.g. link.get('source') ==> { x: 100, y: 100 }; linkPinning: true, // Allowed number of mousemove events after which the pointerclick event will be still triggered. clickThreshold: 0, // The namespace, where all the cell views are defined. cellViewNamespace: joint.shapes, // The namespace, where all the cell views are defined. highlighterNamespace: joint.highlighters }, events: { 'mousedown': 'pointerdown', 'dblclick': 'mousedblclick', 'click': 'mouseclick', 'touchstart': 'pointerdown', 'touchend': 'mouseclick', 'touchmove': 'pointermove', 'mousemove': 'pointermove', 'mouseover .element': 'cellMouseover', 'mouseover .link': 'cellMouseover', 'mouseout .element': 'cellMouseout', 'mouseout .link': 'cellMouseout', 'contextmenu': 'contextmenu', 'mousewheel': 'mousewheel', 'DOMMouseScroll': 'mousewheel' }, _highlights: [], init: function() { _.bindAll(this, 'pointerup'); this.model = this.options.model || new joint.dia.Graph; // This is a fix for the case where two papers share the same options. // Changing origin.x for one paper would change the value of origin.x for the other. // This prevents that behavior. this.options.origin = _.clone(this.options.origin); this.options.defaultConnector = _.clone(this.options.defaultConnector); // Return default highlighting options into the user specified options. _.defaults(this.options.highlighting, this.constructor.prototype.options.highlighting); this.options.highlighting = _.cloneDeep(this.options.highlighting); this.svg = V('svg').node; this.viewport = V('g').addClass(joint.util.addClassNamePrefix('viewport')).node; this.defs = V('defs').node; // Append `<defs>` element to the SVG document. This is useful for filters and gradients. V(this.svg).append([this.viewport, this.defs]); this.$el.append(this.svg); this.listenTo(this.model, 'add', this.onCellAdded); this.listenTo(this.model, 'remove', this.removeView); this.listenTo(this.model, 'reset', this.resetViews); this.listenTo(this.model, 'sort', this._onSort); this.listenTo(this.model, 'batch:stop', this._onBatchStop); this.setOrigin(); this.setDimensions(); $(document).on('mouseup touchend', this.pointerup); // Hold the value when mouse has been moved: when mouse moved, no click event will be triggered. this._mousemoved = 0; // Hash of all cell views. this._views = {}; this.on('cell:highlight', this.onCellHighlight, this); this.on('cell:unhighlight', this.onCellUnhighlight, this); }, _onSort: function() { if (!this.model.hasActiveBatch('add')) { this.sortViews(); } }, _onBatchStop: function(data) { var name = data && data.batchName; if (name === 'add' && !this.model.hasActiveBatch('add')) { this.sortViews(); } }, onRemove: function() { //clean up all DOM elements/views to prevent memory leaks this.removeViews(); $(document).off('mouseup touchend', this.pointerup); }, setDimensions: function(width, height) { width = this.options.width = width || this.options.width; height = this.options.height = height || this.options.height; V(this.svg).attr({ width: width, height: height }); this.trigger('resize', width, height); }, setOrigin: function(ox, oy) { this.options.origin.x = ox || 0; this.options.origin.y = oy || 0; V(this.viewport).translate(ox, oy, { absolute: true }); this.trigger('translate', ox, oy); if (this.options.drawGrid) { this.drawGrid(); } }, // Expand/shrink the paper to fit the content. Snap the width/height to the grid // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper. // When options { fitNegative: true } it also translates the viewport in order to make all // the content visible. fitToContent: function(gridWidth, gridHeight, padding, opt) { // alternatively function(opt) if (_.isObject(gridWidth)) { // first parameter is an option object opt = gridWidth; gridWidth = opt.gridWidth || 1; gridHeight = opt.gridHeight || 1; padding = opt.padding || 0; } else { opt = opt || {}; gridWidth = gridWidth || 1; gridHeight = gridHeight || 1; padding = padding || 0; } padding = joint.util.normalizeSides(padding); // Calculate the paper size to accomodate all the graph's elements. var bbox = V(this.viewport).bbox(true, this.svg); var currentScale = V(this.viewport).scale(); bbox.x *= currentScale.sx; bbox.y *= currentScale.sy; bbox.width *= currentScale.sx; bbox.height *= currentScale.sy; var calcWidth = Math.max(Math.ceil((bbox.width + bbox.x) / gridWidth), 1) * gridWidth; var calcHeight = Math.max(Math.ceil((bbox.height + bbox.y) / gridHeight), 1) * gridHeight; var tx = 0; var ty = 0; if ((opt.allowNewOrigin == 'negative' && bbox.x < 0) || (opt.allowNewOrigin == 'positive' && bbox.x >= 0) || opt.allowNewOrigin == 'any') { tx = Math.ceil(-bbox.x / gridWidth) * gridWidth; tx += padding.left; calcWidth += tx; } if ((opt.allowNewOrigin == 'negative' && bbox.y < 0) || (opt.allowNewOrigin == 'positive' && bbox.y >= 0) || opt.allowNewOrigin == 'any') { ty = Math.ceil(-bbox.y / gridHeight) * gridHeight; ty += padding.top; calcHeight += ty; } calcWidth += padding.right; calcHeight += padding.bottom; // Make sure the resulting width and height are greater than minimum. calcWidth = Math.max(calcWidth, opt.minWidth || 0); calcHeight = Math.max(calcHeight, opt.minHeight || 0); // Make sure the resulting width and height are lesser than maximum. calcWidth = Math.min(calcWidth, opt.maxWidth || Number.MAX_VALUE); calcHeight = Math.min(calcHeight, opt.maxHeight || Number.MAX_VALUE); var dimensionChange = calcWidth != this.options.width || calcHeight != this.options.height; var originChange = tx != this.options.origin.x || ty != this.options.origin.y; // Change the dimensions only if there is a size discrepency or an origin change if (originChange) { this.setOrigin(tx, ty); } if (dimensionChange) { this.setDimensions(calcWidth, calcHeight); } }, scaleContentToFit: function(opt) { var contentBBox = this.getContentBBox(); if (!contentBBox.width || !contentBBox.height) return; opt = opt || {}; _.defaults(opt, { padding: 0, preserveAspectRatio: true, scaleGrid: null, minScale: 0, maxScale: Number.MAX_VALUE //minScaleX //minScaleY //maxScaleX //maxScaleY //fittingBBox }); var padding = opt.padding; var minScaleX = opt.minScaleX || opt.minScale; var maxScaleX = opt.maxScaleX || opt.maxScale; var minScaleY = opt.minScaleY || opt.minScale; var maxScaleY = opt.maxScaleY || opt.maxScale; var fittingBBox = opt.fittingBBox || ({ x: this.options.origin.x, y: this.options.origin.y, width: this.options.width, height: this.options.height }); fittingBBox = g.rect(fittingBBox).moveAndExpand({ x: padding, y: padding, width: -2 * padding, height: -2 * padding }); var currentScale = V(this.viewport).scale(); var newSx = fittingBBox.width / contentBBox.width * currentScale.sx; var newSy = fittingBBox.height / contentBBox.height * currentScale.sy; if (opt.preserveAspectRatio) { newSx = newSy = Math.min(newSx, newSy); } // snap scale to a grid if (opt.scaleGrid) { var gridSize = opt.scaleGrid; newSx = gridSize * Math.floor(newSx / gridSize); newSy = gridSize * Math.floor(newSy / gridSize); } // scale min/max boundaries newSx = Math.min(maxScaleX, Math.max(minScaleX, newSx)); newSy = Math.min(maxScaleY, Math.max(minScaleY, newSy)); this.scale(newSx, newSy); var contentTranslation = this.getContentBBox(); var newOx = fittingBBox.x - contentTranslation.x; var newOy = fittingBBox.y - contentTranslation.y; this.setOrigin(newOx, newOy); }, getContentBBox: function() { var crect = this.viewport.getBoundingClientRect(); // Using Screen CTM was the only way to get the real viewport bounding box working in both // Google Chrome and Firefox. var screenCTM = this.viewport.getScreenCTM(); // for non-default origin we need to take the viewport translation into account var viewportCTM = this.viewport.getCTM(); return g.rect({ x: crect.left - screenCTM.e + viewportCTM.e, y: crect.top - screenCTM.f + viewportCTM.f, width: crect.width, height: crect.height }); }, // Returns a geometry rectangle represeting the entire // paper area (coordinates from the left paper border to the right one // and the top border to the bottom one). getArea: function() { var transformationMatrix = this.viewport.getCTM().inverse(); var noTransformationBBox = { x: 0, y: 0, width: this.options.width, height: this.options.height }; return g.rect(V.transformRect(noTransformationBBox, transformationMatrix)); }, getRestrictedArea: function() { var restrictedArea; if (_.isFunction(this.options.restrictTranslate)) { // A method returning a bounding box restrictedArea = this.options.restrictTranslate.apply(this, arguments); } else if (this.options.restrictTranslate === true) { // The paper area restrictedArea = this.getArea(); } else { // Either false or a bounding box restrictedArea = this.options.restrictTranslate || null; } return restrictedArea; }, createViewForModel: function(cell) { // A class taken from the paper options. var optionalViewClass; // A default basic class (either dia.ElementView or dia.LinkView) var defaultViewClass; // A special class defined for this model in the corresponding namespace. // e.g. joint.shapes.basic.Rect searches for joint.shapes.basic.RectView var namespace = this.options.cellViewNamespace; var type = cell.get('type') + 'View'; var namespaceViewClass = joint.util.getByPath(namespace, type, '.'); if (cell.isLink()) { optionalViewClass = this.options.linkView; defaultViewClass = joint.dia.LinkView; } else { optionalViewClass = this.options.elementView; defaultViewClass = joint.dia.ElementView; } // a) the paper options view is a class (deprecated) // 1. search the namespace for a view // 2. if no view was found, use view from the paper options // b) the paper options view is a function // 1. call the function from the paper options // 2. if no view was return, search the namespace for a view // 3. if no view was found, use the default var ViewClass = (optionalViewClass.prototype instanceof Backbone.View) ? namespaceViewClass || optionalViewClass : optionalViewClass.call(this, cell) || namespaceViewClass || defaultViewClass; return new ViewClass({ model: cell, interactive: this.options.interactive }); }, onCellAdded: function(cell, graph, opt) { if (this.options.async && opt.async !== false && _.isNumber(opt.position)) { this._asyncCells = this._asyncCells || []; this._asyncCells.push(cell); if (opt.position == 0) { if (this._frameId) throw new Error('another asynchronous rendering in progress'); this.asyncRenderViews(this._asyncCells, opt); delete this._asyncCells; } } else { this.renderView(cell); } }, removeView: function(cell) { var view = this._views[cell.id]; if (view) { view.remove(); delete this._views[cell.id]; } return view; }, renderView: function(cell) { var view = this._views[cell.id] = this.createViewForModel(cell); V(this.viewport).append(view.el); view.paper = this; view.render(); // This is the only way to prevent image dragging in Firefox that works. // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help. $(view.el).find('image').on('dragstart', function() { return false; }); return view; }, beforeRenderViews: function(cells) { // Make sure links are always added AFTER elements. // They wouldn't find their sources/targets in the DOM otherwise. cells.sort(function(a) { return a instanceof joint.dia.Link ? 1 : -1; }); return cells; }, afterRenderViews: function() { this.sortViews(); }, resetViews: function(cellsCollection, opt) { // clearing views removes any event listeners this.removeViews(); var cells = cellsCollection.models.slice(); // `beforeRenderViews()` can return changed cells array (e.g sorted). cells = this.beforeRenderViews(cells, opt) || cells; if (this._frameId) { joint.util.cancelFrame(this._frameId); delete this._frameId; } if (this.options.async) { this.asyncRenderViews(cells, opt); // Sort the cells once all elements rendered (see asyncRenderViews()). } else { _.each(cells, this.renderView, this); // Sort the cells in the DOM manually as we might have changed the order they // were added to the DOM (see above). this.sortViews(); } }, removeViews: function() { _.invoke(this._views, 'remove'); this._views = {}; }, asyncBatchAdded: _.noop, asyncRenderViews: function(cells, opt) { if (this._frameId) { var batchSize = (this.options.async && this.options.async.batchSize) || 50; var batchCells = cells.splice(0, batchSize); var collection = this.model.get('cells'); _.each(batchCells, function(cell) { // The cell has to be part of the graph collection. // There is a chance in asynchronous rendering // that a cell was removed before it's rendered to the paper. if (cell.collection === collection) this.renderView(cell); }, this); this.asyncBatchAdded(); } if (!cells.length) { // No cells left to render. delete this._frameId; this.afterRenderViews(opt); this.trigger('render:done', opt); } else { // Schedule a next batch to render. this._frameId = joint.util.nextFrame(function() { this.asyncRenderViews(cells, opt); }, this); } }, sortViews: function() { // Run insertion sort algorithm in order to efficiently sort DOM elements according to their // associated model `z` attribute. var $cells = $(this.viewport).children('[model-id]'); var cells = this.model.get('cells'); joint.util.sortElements($cells, function(a, b) { var cellA = cells.get($(a).attr('model-id')); var cellB = cells.get($(b).attr('model-id')); return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1; }); }, scale: function(sx, sy, ox, oy) { sy = sy || sx; if (_.isUndefined(ox)) { ox = 0; oy = 0; } // Remove previous transform so that the new scale is not affected by previous scales, especially // the old translate() does not affect the new translate if an origin is specified. V(this.viewport).attr('transform', ''); var oldTx = this.options.origin.x; var oldTy = this.options.origin.y; // TODO: V.scale() doesn't support setting scale origin. #Fix if (ox || oy || oldTx || oldTy) { var newTx = oldTx - ox * (sx - 1); var newTy = oldTy - oy * (sy - 1); this.setOrigin(newTx, newTy); } V(this.viewport).scale(sx, sy); this.trigger('scale', sx, sy, ox, oy); if (this.options.drawGrid) { this.drawGrid(); } return this; }, rotate: function(deg, ox, oy) { // If the origin is not set explicitely, rotate around the center. Note that // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us // the real bounding box (`bbox()`) including transformations). if (_.isUndefined(ox)) { var bbox = this.viewport.getBBox(); ox = bbox.width / 2; oy = bbox.height / 2; } V(this.viewport).rotate(deg, ox, oy); }, // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also // be a selector or a jQuery object. findView: function($el) { var el = _.isString($el) ? this.viewport.querySelector($el) : $el instanceof $ ? $el[0] : $el; while (el && el !== this.el && el !== document) { var id = el.getAttribute('model-id'); if (id) return this._views[id]; el = el.parentNode; } return undefined; }, // Find a view for a model `cell`. `cell` can also be a string representing a model `id`. findViewByModel: function(cell) { var id = _.isString(cell) ? cell : cell.id; return this._views[id]; }, // Find all views at given point findViewsFromPoint: function(p) { p = g.point(p); var views = _.map(this.model.getElements(), this.findViewByModel, this); return _.filter(views, function(view) { return view && g.rect(view.vel.bbox(false, this.viewport)).containsPoint(p); }, this); }, // Find all views in given area findViewsInArea: function(rect, opt) { opt = _.defaults(opt || {}, { strict: false }); rect = g.rect(rect); var views = _.map(this.model.getElements(), this.findViewByModel, this); var method = opt.strict ? 'containsRect' : 'intersect'; return _.filter(views, function(view) { return view && rect[method](g.rect(view.vel.bbox(false, this.viewport))); }, this); }, getModelById: function(id) { return this.model.getCell(id); }, snapToGrid: function(p) { // Convert global coordinates to the local ones of the `viewport`. Otherwise, // improper transformation would be applied when the viewport gets transformed (scaled/rotated). var localPoint = V(this.viewport).toLocalPoint(p.x, p.y); return { x: g.snapToGrid(localPoint.x, this.options.gridSize), y: g.snapToGrid(localPoint.y, this.options.gridSize) }; }, // Transform client coordinates to the paper local coordinates. // Useful when you have a mouse event object and you'd like to get coordinates // inside the paper that correspond to `evt.clientX` and `evt.clientY` point. // Exmaple: var paperPoint = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY }); clientToLocalPoint: function(p) { p = g.point(p); // This is a hack for Firefox! If there wasn't a fake (non-visible) rectangle covering the // whole SVG area, `$(paper.svg).offset()` used below won't work. var fakeRect = V('rect', { width: this.options.width, height: this.options.height, x: 0, y: 0, opacity: 0 }); V(this.svg).prepend(fakeRect); var paperOffset = $(this.svg).offset(); // Clean up the fake rectangle once we have the offset of the SVG document. fakeRect.remove(); var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft; p.offset(scrollLeft - paperOffset.left, scrollTop - paperOffset.top); // Transform point into the viewport coordinate system. return V.transformPoint(p, this.viewport.getCTM().inverse()); }, linkAllowed: function(linkViewOrModel) { var link; if (linkViewOrModel instanceof joint.dia.Link) { link = linkViewOrModel; } else if (linkViewOrModel instanceof joint.dia.LinkView) { link = linkViewOrModel.model; } else { throw new Error('Must provide link model or view.'); } if (!this.options.multiLinks) { // Do not allow multiple links to have the same source and target. var source = link.get('source'); var target = link.get('target'); if (source.id && target.id) { var sourceModel = link.getSourceElement(); if (sourceModel) { var connectedLinks = this.model.getConnectedLinks(sourceModel, { outbound: true, inbound: false }); var numSameLinks = _.filter(connectedLinks, function(_link) { var _source = _link.get('source'); var _target = _link.get('target'); return _source && _source.id === source.id && (!_source.port || (_source.port === source.port)) && _target && _target.id === target.id && (!_target.port || (_target.port === target.port)); }).length; if (numSameLinks > 1) { return false; } } } } if ( !this.options.linkPinning && ( !_.has(link.get('source'), 'id') || !_.has(link.get('target'), 'id') ) ) { // Link pinning is not allowed and the link is not connected to the target. return false; } return true; }, getDefaultLink: function(cellView, magnet) { return _.isFunction(this.options.defaultLink) // default link is a function producing link model ? this.options.defaultLink.call(this, cellView, magnet) // default link is the Backbone model : this.options.defaultLink.clone(); }, // Cell highlighting // ----------------- resolveHighlighter: function(opt) { opt = opt || {}; var highlighterDef = opt.highlighter; var paperOpt = this.options; /* Expecting opt.highlighter to have the following structure: { name: 'highlighter-name', options: { some: 'value' } } */ if (_.isUndefined(highlighterDef)) { // check for built-in types var type = _.chain(opt) .pick('embedding', 'connecting', 'magnetAvailability', 'elementAvailability') .keys().first().value(); highlighterDef = (type && paperOpt.highlighting[type]) || paperOpt.highlighting['default']; } // Do nothing if opt.highlighter is falsey. // This allows the case to not highlight cell(s) in certain cases. // For example, if you want to NOT highlight when embedding elements. if (!highlighterDef) return false; var name = highlighterDef.name; var highlighter = paperOpt.highlighterNamespace[name]; // Highlighter validation if (!highlighter) { throw new Error('Unknown highlighter ("' + name + '")'); } if (typeof highlighter.highlight !== 'function') { throw new Error('Highlighter ("' + name + '") is missing required highlight() method'); } if (typeof highlighter.unhighlight !== 'function') { throw new Error('Highlighter ("' + name + '") is missing required unhighlight() method'); } return { highlighter: highlighter, options: highlighterDef.options, name: name }; }, onCellHighlight: function(cellView, magnetEl, opt) { opt = this.resolveHighlighter(opt); if (!opt) return; var key = opt.name + magnetEl.id + JSON.stringify(opt.options); if (!this._highlights[key]) { var highlighter = opt.highlighter; highlighter.highlight(cellView, magnetEl, _.clone(opt.options)); this._highlights[key] = { cellView: cellView, magnetEl: magnetEl, opt: opt.options, highlighter: highlighter }; } }, onCellUnhighlight: function(cellView, magnetEl, opt) { opt = this.resolveHighlighter(opt); if (!opt) return; var key = opt.name + magnetEl.id + JSON.stringify(opt.options); var highlight = this._highlights[key]; if (highlight) { // Use the cellView and magnetEl that were used by the highlighter.highlight() method. highlight.highlighter.unhighlight(highlight.cellView, highlight.magnetEl, highlight.opt); this._highlights[key] = null; } }, // Interaction. // ------------ mousedblclick: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerdblclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y); } }, mouseclick: function(evt) { // Trigger event when mouse not moved. if (this._mousemoved <= this.options.clickThreshold) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y); } } }, // Guard guards the event received. If the event is not interesting, guard returns `true`. // Otherwise, it return `false`. guard: function(evt, view) { if (this.options.guard && this.options.guard(evt, view)) { return true; } if (view && view.model && (view.model instanceof joint.dia.Cell)) { return false; } else if (this.svg === evt.target || this.el === evt.target || $.contains(this.svg, evt.target)) { return false; } return true; // Event guarded. Paper should not react on it in any way. }, contextmenu: function(evt) { evt = joint.util.normalizeEvent(evt); if (this.options.preventContextMenu) { evt.preventDefault(); } var view = this.findView(evt.target); if (this.guard(evt, view)) return; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.contextmenu(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:contextmenu', evt, localPoint.x, localPoint.y); } }, pointerdown: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; evt.preventDefault(); this._mousemoved = 0; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { this.sourceView = view; view.pointerdown(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y); } }, pointermove: function(evt) { if (this.sourceView) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); // Mouse moved counter. this._mousemoved++; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); this.sourceView.pointermove(evt, localPoint.x, localPoint.y); } }, pointerup: function(evt) { evt = joint.util.normalizeEvent(evt); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (this.sourceView) { this.sourceView.pointerup(evt, localPoint.x, localPoint.y); //"delete sourceView" occasionally throws an error in chrome (illegal access exception) this.sourceView = null; } else { this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y); } }, mousewheel: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (this.guard(evt, view)) return; var originalEvent = evt.originalEvent; var localPoint = this.snapToGrid({ x: originalEvent.clientX, y: originalEvent.clientY }); var delta = Math.max(-1, Math.min(1, (originalEvent.wheelDelta || -originalEvent.detail))); if (view) { view.mousewheel(evt, localPoint.x, localPoint.y, delta); } else { this.trigger('blank:mousewheel', evt, localPoint.x, localPoint.y, delta); } }, cellMouseover: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { if (this.guard(evt, view)) return; view.mouseover(evt); } }, cellMouseout: function(evt) { evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); if (view) { if (this.guard(evt, view)) return; view.mouseout(evt); } }, setGridSize: function(gridSize) { this.options.gridSize = gridSize; if (this.options.drawGrid) { this.drawGrid(); } return this; }, clearGrid: function() { this.el.style.backgroundImage = 'none'; return this; }, drawGrid: function(opt) { opt = _.defaults(opt || {}, this.options.drawGrid, { color: '#aaa', thickness: 1 }); var gridSize = this.options.gridSize; if (gridSize <= 1) { return this.clearGrid(); } var currentScale = V(this.viewport).scale(); var scaleX = currentScale.sx; var scaleY = currentScale.sy; var originX = this.options.origin.x; var originY = this.options.origin.y; var gridX = gridSize * scaleX; var gridY = gridSize * scaleY; var canvas = document.createElement('canvas'); canvas.width = gridX; canvas.height = gridY; gridX = originX >= 0 ? originX % gridX : gridX + originX % gridX; gridY = originY >= 0 ? originY % gridY : gridY + originY % gridY; var context = canvas.getContext('2d'); context.beginPath(); context.rect(gridX, gridY, opt.thickness * scaleX, opt.thickness * scaleY); context.fillStyle = opt.color; context.fill(); var backgroundImage = canvas.toDataURL('image/png'); this.el.style.backgroundImage = 'url("' + backgroundImage + '")'; return this; }, setInteractivity: function(value) { this.options.interactive = value; _.invoke(this._views, 'setInteractivity', value); } }); // JointJS library. // (c) 2011-2013 client IO joint.shapes.basic = {}; joint.shapes.basic.Generic = joint.dia.Element.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Generic', attrs: { '.': { fill: '#ffffff', stroke: 'none' } } }, joint.dia.Element.prototype.defaults) }); joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Rect', attrs: { 'rect': { fill: '#ffffff', stroke: '#000000', width: 100, height: 60 }, 'text': { fill: '#000000', text: '', 'font-size': 14, 'ref-x': .5, 'ref-y': .5, 'text-anchor': 'middle', 'y-alignment': 'middle', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.TextView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); // The element view is not automatically rescaled to fit the model size // when the attribute 'attrs' is changed. this.listenTo(this.model, 'change:attrs', this.resize); } }); joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><text/></g></g>', defaults: joint.util.deepSupplement({ type: 'basic.Text', attrs: { 'text': { 'font-size': 18, fill: '#000000' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Circle', size: { width: 60, height: 60 }, attrs: { 'circle': { fill: '#ffffff', stroke: '#000000', r: 30, cx: 30, cy: 30 }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Ellipse = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><ellipse/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Ellipse', size: { width: 60, height: 40 }, attrs: { 'ellipse': { fill: '#ffffff', stroke: '#000000', rx: 30, ry: 20, cx: 30, cy: 20 }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Polygon = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Polygon', size: { width: 60, height: 40 }, attrs: { 'polygon': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Polyline = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><polyline/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Polyline', size: { width: 60, height: 40 }, attrs: { 'polyline': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Image', attrs: { 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, 'y-alignment': 'middle', fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Path', size: { width: 60, height: 60 }, attrs: { 'path': { fill: '#ffffff', stroke: '#000000' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref': 'path', 'ref-x': .5, 'ref-dy': 10, fill: '#000000', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Rhombus = joint.shapes.basic.Path.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Rhombus', attrs: { 'path': { d: 'M 30 0 L 60 30 30 60 0 30 z' }, 'text': { 'ref-y': .5, 'y-alignment': 'middle' } } }, joint.shapes.basic.Path.prototype.defaults) }); // PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy // to create new shapes with ports functionality. It is assumed that the new shapes have // `inPorts` and `outPorts` array properties. Only these properties should be used to set ports. // In other words, using this interface, it is no longer recommended to set ports directly through the // `attrs` object. // Usage: // joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, { // getPortAttrs: function(portName, index, total, selector, type) { // var attrs = {}; // var portClass = 'port' + index; // var portSelector = selector + '>.' + portClass; // var portTextSelector = portSelector + '>text'; // var portBodySelector = portSelector + '>.port-body'; // // attrs[portTextSelector] = { text: portName }; // attrs[portBodySelector] = { port: { id: portName || _.uniqueId(type) , type: type } }; // attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) }; // // if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; } // // return attrs; // } //})); joint.shapes.basic.PortsModelInterface = { initialize: function() { this.updatePortsAttrs(); this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this); // Call the `initialize()` of the parent. this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments); }, updatePortsAttrs: function(eventName) { if (this._portSelectors) { var newAttrs = _.omit(this.get('attrs'), this._portSelectors); this.set('attrs', newAttrs, { silent: true }); } // This holds keys to the `attrs` object for all the port specific attribute that // we set in this method. This is necessary in order to remove previously set // attributes for previous ports. this._portSelectors = []; var attrs = {}; _.each(this.get('inPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); _.each(this.get('outPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); // Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure // that, for example, command manager does not register `change:attrs` command but only // the important `change:inPorts`/`change:outPorts` command. this.attr(attrs, { silent: true }); // Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent). this.processPorts(); // Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object. this.trigger('process:ports'); }, getPortSelector: function(name) { var selector = '.inPorts'; var index = this.get('inPorts').indexOf(name); if (index < 0) { selector = '.outPorts'; index = this.get('outPorts').indexOf(name); if (index < 0) throw new Error("getPortSelector(): Port doesn't exist."); } return selector + '>g:nth-child(' + (index + 1) + ')>.port-body'; } }; joint.shapes.basic.PortsViewInterface = { initialize: function() { // `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports. this.listenTo(this.model, 'process:ports', this.update); joint.dia.ElementView.prototype.initialize.apply(this, arguments); }, update: function() { // First render ports so that `attrs` can be applied to those newly created DOM elements // in `ElementView.prototype.update()`. this.renderPorts(); joint.dia.ElementView.prototype.update.apply(this, arguments); }, renderPorts: function() { var $inPorts = this.$('.inPorts').empty(); var $outPorts = this.$('.outPorts').empty(); var portTemplate = joint.util.template(this.model.portMarkup); _.each(_.filter(this.model.ports, function(p) { return p.type === 'in'; }), function(port, index) { $inPorts.append(V(portTemplate({ id: index, port: port })).node); }); _.each(_.filter(this.model.ports, function(p) { return p.type === 'out'; }), function(port, index) { $outPorts.append(V(portTemplate({ id: index, port: port })).node); }); } }; joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({ markup: [ '<g class="rotatable">', '<g class="scalable"><rect/></g>', joint.env.test('svgforeignobject') ? '<foreignObject class="fobj"><body xmlns="http://www.w3.org/1999/xhtml"><div class="content"/></body></foreignObject>' : '<text class="content"/>', '</g>' ].join(''), defaults: joint.util.deepSupplement({ type: 'basic.TextBlock', // see joint.css for more element styles attrs: { rect: { fill: '#ffffff', stroke: '#000000', width: 80, height: 100 }, text: { fill: '#000000', 'font-size': 14, 'font-family': 'Arial, helvetica, sans-serif' }, '.content': { text: '', ref: 'rect', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'x-alignment': 'middle' } }, content: '' }, joint.shapes.basic.Generic.prototype.defaults), initialize: function() { this.listenTo(this, 'change:size', this.updateSize); this.listenTo(this, 'change:content', this.updateContent); this.updateSize(this, this.get('size')); this.updateContent(this, this.get('content')); joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments); }, updateSize: function(cell, size) { // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead. // We have to clone size as we don't want attributes.div.style to be same object as attributes.size. this.attr({ '.fobj': _.clone(size), div: { style: _.clone(size) } }); }, updateContent: function(cell, content) { if (joint.env.test('svgforeignobject')) { // Content element is a <div> element. this.attr({ '.content': { html: content } }); } else { // Content element is a <text> element. // SVG elements don't have innerHTML attribute. this.attr({ '.content': { text: content } }); } }, // Here for backwards compatibility: setForeignObjectSize: function() { this.updateSize.apply(this, arguments); }, // Here for backwards compatibility: setDivContent: function() { this.updateContent.apply(this, arguments); } }); // TextBlockView implements the fallback for IE when no foreignObject exists and // the text needs to be manually broken. joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); // Keep this for backwards compatibility: this.noSVGForeignObjectElement = !joint.env.test('svgforeignobject'); if (!joint.env.test('svgforeignobject')) { this.listenTo(this.model, 'change:content', function(cell) { // avoiding pass of extra paramters this.updateContent(cell); }); } }, update: function(cell, renderingOnlyAttrs) { if (joint.env.test('svgforeignobject')) { var model = this.model; // Update everything but the content first. var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content'); joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs); if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) { // Update the content itself. this.updateContent(model, renderingOnlyAttrs); } } else { joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs); } }, updateContent: function(cell, renderingOnlyAttrs) { // Create copy of the text attributes var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']); textAttrs = _.omit(textAttrs, 'text'); // Break the content to fit the element size taking into account the attributes // set on the model. var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, { // measuring sandbox svg document svgDocument: this.paper.svg }); // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }} var attrs = joint.util.setByPath({}, '.content', textAttrs, '/'); // Replace text attribute with the one we just processed. attrs['.content'].text = text; // Update the view using renderingOnlyAttributes parameter. joint.dia.ElementView.prototype.update.call(this, cell, attrs); } }); joint.routers.manhattan = (function(g, _, joint) { 'use strict'; var config = { // size of the step to find a route step: 10, // use of the perpendicular linkView option to connect center of element with first vertex perpendicular: true, // should be source or target not to be consider as an obstacle excludeEnds: [], // 'source', 'target' // should be any element with a certain type not to be consider as an obstacle excludeTypes: ['basic.Text'], // if number of route finding loops exceed the maximum, stops searching and returns // fallback route maximumLoops: 2000, // possible starting directions from an element startDirections: ['left', 'right', 'top', 'bottom'], // possible ending directions to an element endDirections: ['left', 'right', 'top', 'bottom'], // specify directions above directionMap: { right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 }, top: { x: 0, y: -1 } }, // maximum change of the direction maxAllowedDirectionChange: 90, // padding applied on the element bounding boxes paddingBox: function() { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }, // an array of directions to find next points on the route directions: function() { var step = this.step; return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: -step , cost: step } ]; }, // a penalty received for direction change penalties: function() { return { 0: 0, 45: this.step / 2, 90: this.step / 2 }; }, // * Deprecated * // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). /* i.e. function(from, to, opts) { // Find an orthogonal route ignoring obstacles. var point = ((opts.previousDirAngle || 0) % 180 === 0) ? g.point(from.x, to.y) : g.point(to.x, from.y); return [point, to]; }, */ fallbackRoute: _.constant(null), // if a function is provided, it's used to route the link while dragging an end // i.e. function(from, to, opts) { return []; } draggingRoute: null }; // Map of obstacles // Helper structure to identify whether a point lies in an obstacle. function ObstacleMap(opt) { this.map = {}; this.options = opt; // tells how to divide the paper when creating the elements map this.mapGridSize = 100; } ObstacleMap.prototype.build = function(graph, link) { var opt = this.options; // source or target element could be excluded from set of obstacles var excludedEnds = _.chain(opt.excludeEnds) .map(link.get, link) .pluck('id') .map(graph.getCell, graph).value(); // Exclude any embedded elements from the source and the target element. var excludedAncestors = []; var source = graph.getCell(link.get('source').id); if (source) { excludedAncestors = _.union(excludedAncestors, _.map(source.getAncestors(), 'id')); }; var target = graph.getCell(link.get('target').id); if (target) { excludedAncestors = _.union(excludedAncestors, _.map(target.getAncestors(), 'id')); } // builds a map of all elements for quicker obstacle queries (i.e. is a point contained // in any obstacle?) (a simplified grid search) // The paper is divided to smaller cells, where each of them holds an information which // elements belong to it. When we query whether a point is in an obstacle we don't need // to go through all obstacles, we check only those in a particular cell. var mapGridSize = this.mapGridSize; _.chain(graph.getElements()) // remove source and target element if required .difference(excludedEnds) // remove all elements whose type is listed in excludedTypes array .reject(function(element) { // reject any element which is an ancestor of either source or target return _.contains(opt.excludeTypes, element.get('type')) || _.contains(excludedAncestors, element.id); }) // change elements (models) to their bounding boxes .invoke('getBBox') // expand their boxes by specific padding .invoke('moveAndExpand', opt.paddingBox) // build the map .foldl(function(map, bbox) { var origin = bbox.origin().snapToGrid(mapGridSize); var corner = bbox.corner().snapToGrid(mapGridSize); for (var x = origin.x; x <= corner.x; x += mapGridSize) { for (var y = origin.y; y <= corner.y; y += mapGridSize) { var gridKey = x + '@' + y; map[gridKey] = map[gridKey] || []; map[gridKey].push(bbox); } } return map; }, this.map).value(); return this; }; ObstacleMap.prototype.isPointAccessible = function(point) { var mapKey = point.clone().snapToGrid(this.mapGridSize).toString(); return _.every(this.map[mapKey], function(obstacle) { return !obstacle.containsPoint(point); }); }; // Sorted Set // Set of items sorted by given value. function SortedSet() { this.items = []; this.hash = {}; this.values = {}; this.OPEN = 1; this.CLOSE = 2; } SortedSet.prototype.add = function(item, value) { if (this.hash[item]) { // item removal this.items.splice(this.items.indexOf(item), 1); } else { this.hash[item] = this.OPEN; } this.values[item] = value; var index = _.sortedIndex(this.items, item, function(i) { return this.values[i]; }, this); this.items.splice(index, 0, item); }; SortedSet.prototype.remove = function(item) { this.hash[item] = this.CLOSE; }; SortedSet.prototype.isOpen = function(item) { return this.hash[item] === this.OPEN; }; SortedSet.prototype.isClose = function(item) { return this.hash[item] === this.CLOSE; }; SortedSet.prototype.isEmpty = function() { return this.items.length === 0; }; SortedSet.prototype.pop = function() { var item = this.items.shift(); this.remove(item); return item; }; function normalizePoint(point) { return g.point( point.x === 0 ? 0 : Math.abs(point.x) / point.x, point.y === 0 ? 0 : Math.abs(point.y) / point.y ); } // reconstructs a route by concating points with their parents function reconstructRoute(parents, point, startCenter, endCenter) { var route = []; var prevDiff = normalizePoint(endCenter.difference(point)); var current = point; var parent; while ((parent = parents[current])) { var diff = normalizePoint(current.difference(parent)); if (!diff.equals(prevDiff)) { route.unshift(current); prevDiff = diff; } current = parent; } var startDiff = normalizePoint(g.point(current).difference(startCenter)); if (!startDiff.equals(prevDiff)) { route.unshift(current); } return route; } // find points around the rectangle taking given directions in the account function getRectPoints(bbox, directionList, opt) { var step = opt.step; var center = bbox.center(); var startPoints = _.chain(opt.directionMap).pick(directionList).map(function(direction) { var x = direction.x * bbox.width / 2; var y = direction.y * bbox.height / 2; var point = center.clone().offset(x, y); if (bbox.containsPoint(point)) { point.offset(direction.x * step, direction.y * step); } return point.snapToGrid(step); }).value(); return startPoints; }; // returns a direction index from start point to end point function getDirectionAngle(start, end, dirLen) { var q = 360 / dirLen; return Math.floor(g.normalizeAngle(start.theta(end) + q / 2) / q) * q; } function getDirectionChange(angle1, angle2) { var dirChange = Math.abs(angle1 - angle2); return dirChange > 180 ? 360 - dirChange : dirChange; } // heurestic method to determine the distance between two points function estimateCost(from, endPoints) { var min = Infinity; for (var i = 0, len = endPoints.length; i < len; i++) { var cost = from.manhattanDistance(endPoints[i]); if (cost < min) min = cost; }; return min; } // finds the route between to points/rectangles implementing A* alghoritm function findRoute(start, end, map, opt) { var step = opt.step; var startPoints, endPoints; var startCenter, endCenter; // set of points we start pathfinding from if (start instanceof g.rect) { startPoints = getRectPoints(start, opt.startDirections, opt); startCenter = start.center().snapToGrid(step); } else { startCenter = start.clone().snapToGrid(step); startPoints = [startCenter]; } // set of points we want the pathfinding to finish at if (end instanceof g.rect) { endPoints = getRectPoints(end, opt.endDirections, opt); endCenter = end.center().snapToGrid(step); } else { endCenter = end.clone().snapToGrid(step); endPoints = [endCenter]; } // take into account only accessible end points startPoints = _.filter(startPoints, map.isPointAccessible, map); endPoints = _.filter(endPoints, map.isPointAccessible, map); // Check if there is a accessible end point. // We would have to use a fallback route otherwise. if (startPoints.length > 0 && endPoints.length > 0) { // The set of tentative points to be evaluated, initially containing the start points. var openSet = new SortedSet(); // Keeps reference to a point that is immediate predecessor of given element. var parents = {}; // Cost from start to a point along best known path. var costs = {}; _.each(startPoints, function(point) { var key = point.toString(); openSet.add(key, estimateCost(point, endPoints)); costs[key] = 0; }); // directions var dir, dirChange; var dirs = opt.directions; var dirLen = dirs.length; var loopsRemain = opt.maximumLoops; var endPointsKeys = _.invoke(endPoints, 'toString'); // main route finding loop while (!openSet.isEmpty() && loopsRemain > 0) { // remove current from the open list var currentKey = openSet.pop(); var currentPoint = g.point(currentKey); var currentDist = costs[currentKey]; var previousDirAngle = currentDirAngle; var currentDirAngle = parents[currentKey] ? getDirectionAngle(parents[currentKey], currentPoint, dirLen) : opt.previousDirAngle != null ? opt.previousDirAngle : getDirectionAngle(startCenter, currentPoint, dirLen); // Check if we reached any endpoint if (endPointsKeys.indexOf(currentKey) >= 0) { // We don't want to allow route to enter the end point in opposite direction. dirChange = getDirectionChange(currentDirAngle, getDirectionAngle(currentPoint, endCenter, dirLen)); if (currentPoint.equals(endCenter) || dirChange < 180) { opt.previousDirAngle = currentDirAngle; return reconstructRoute(parents, currentPoint, startCenter, endCenter); } } // Go over all possible directions and find neighbors. for (var i = 0; i < dirLen; i++) { dir = dirs[i]; dirChange = getDirectionChange(currentDirAngle, dir.angle); // if the direction changed rapidly don't use this point // Note that check is relevant only for points with previousDirAngle i.e. // any direction is allowed for starting points if (previousDirAngle && dirChange > opt.maxAllowedDirectionChange) { continue; } var neighborPoint = currentPoint.clone().offset(dir.offsetX, dir.offsetY); var neighborKey = neighborPoint.toString(); // Closed points from the openSet were already evaluated. if (openSet.isClose(neighborKey) || !map.isPointAccessible(neighborPoint)) { continue; } // The current direction is ok to proccess. var costFromStart = currentDist + dir.cost + opt.penalties[dirChange]; if (!openSet.isOpen(neighborKey) || costFromStart < costs[neighborKey]) { // neighbor point has not been processed yet or the cost of the path // from start is lesser than previously calcluated. parents[neighborKey] = currentPoint; costs[neighborKey] = costFromStart; openSet.add(neighborKey, costFromStart + estimateCost(neighborPoint, endPoints)); }; }; loopsRemain--; } } // no route found ('to' point wasn't either accessible or finding route took // way to much calculations) return opt.fallbackRoute(startCenter, endCenter, opt); } // resolve some of the options function resolveOptions(opt) { opt.directions = _.result(opt, 'directions'); opt.penalties = _.result(opt, 'penalties'); opt.paddingBox = _.result(opt, 'paddingBox'); _.each(opt.directions, function(direction) { var point1 = g.point(0, 0); var point2 = g.point(direction.offsetX, direction.offsetY); direction.angle = g.normalizeAngle(point1.theta(point2)); }); } // initiation of the route finding function router(vertices, opt) { resolveOptions(opt); // enable/disable linkView perpendicular option this.options.perpendicular = !!opt.perpendicular; // expand boxes by specific padding var sourceBBox = g.rect(this.sourceBBox).moveAndExpand(opt.paddingBox); var targetBBox = g.rect(this.targetBBox).moveAndExpand(opt.paddingBox); // pathfinding var map = (new ObstacleMap(opt)).build(this.paper.model, this.model); var oldVertices = _.map(vertices, g.point); var newVertices = []; var tailPoint = sourceBBox.center().snapToGrid(opt.step); // find a route by concating all partial routes (routes need to go through the vertices) // startElement -> vertex[1] -> ... -> vertex[n] -> endElement for (var i = 0, len = oldVertices.length; i <= len; i++) { var partialRoute = null; var from = to || sourceBBox; var to = oldVertices[i]; if (!to) { to = targetBBox; // 'to' is not a vertex. If the target is a point (i.e. it's not an element), we // might use dragging route instead of main routing method if that is enabled. var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id; if (endingAtPoint && _.isFunction(opt.draggingRoute)) { // Make sure we passing points only (not rects). var dragFrom = from instanceof g.rect ? from.center() : from; partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute(from, to, map, opt); if (partialRoute === null) { // The partial route could not be found. // use orthogonal (do not avoid elements) route instead. if (!_.isFunction(joint.routers.orthogonal)) { throw new Error('Manhattan requires the orthogonal router.'); } return joint.routers.orthogonal(vertices, opt, this); }; var leadPoint = _.first(partialRoute); if (leadPoint && leadPoint.equals(tailPoint)) { // remove the first point if the previous partial route had the same point as last partialRoute.shift(); } tailPoint = _.last(partialRoute) || tailPoint; Array.prototype.push.apply(newVertices, partialRoute); }; return newVertices; } // public function return function(vertices, opt, linkView) { return router.call(linkView, vertices, _.extend({}, config, opt)); }; })(g, _, joint); joint.routers.metro = (function() { if (!_.isFunction(joint.routers.manhattan)) { throw new Error('Metro requires the manhattan router.'); } var config = { // cost of a diagonal step (calculated if not defined). diagonalCost: null, // an array of directions to find next points on the route directions: function() { var step = this.step; var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1)); return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: step , offsetY: step , cost: diagonalCost }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: step , cost: diagonalCost }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: -step , offsetY: -step , cost: diagonalCost }, { offsetX: 0 , offsetY: -step , cost: step }, { offsetX: step , offsetY: -step , cost: diagonalCost } ]; }, maxAllowedDirectionChange: 45, // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). fallbackRoute: function(from, to, opts) { // Find a route which breaks by 45 degrees ignoring all obstacles. var theta = from.theta(to); var a = { x: to.x, y: from.y }; var b = { x: from.x, y: to.y }; if (theta % 180 > 90) { var t = a; a = b; b = t; } var p1 = (theta % 90) < 45 ? a : b; var l1 = g.line(from, p1); var alpha = 90 * Math.ceil(theta / 90); var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1); var l2 = g.line(to, p2); var point = l1.intersection(l2); return point ? [point.round(), to] : [to]; } }; // public function return function(vertices, opts, linkView) { return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView); }; })(); // Does not make any changes to vertices. // Returns the arguments that are passed to it, unchanged. joint.routers.normal = function(vertices, opt, linkView) { return vertices; }; // Routes the link always to/from a certain side // // Arguments: // padding ... gap between the element and the first vertex. :: Default 40. // side ... 'left' | 'right' | 'top' | 'bottom' :: Default 'bottom'. // joint.routers.oneSide = function(vertices, opt, linkView) { var side = opt.side || 'bottom'; var padding = opt.padding || 40; // LinkView contains cached source an target bboxes. // Note that those are Geometry rectangle objects. var sourceBBox = linkView.sourceBBox; var targetBBox = linkView.targetBBox; var sourcePoint = sourceBBox.center(); var targetPoint = targetBBox.center(); var coordinate, coordinateValue, dimension, direction; switch (side) { case 'bottom': direction = 1; coordinate = 'y'; dimension = 'height'; break; case 'top': direction = -1; coordinate = 'y'; dimension = 'height'; break; case 'left': direction = -1; coordinate = 'x'; dimension = 'width'; break; case 'right': direction = 1; coordinate = 'x'; dimension = 'width'; break; default: throw new Error('Router: invalid side'); } // move the points from the center of the element to outside of it. sourcePoint[coordinate] += direction * (sourceBBox[dimension] / 2 + padding); targetPoint[coordinate] += direction * (targetBBox[dimension] / 2 + padding); // make link orthogonal (at least the first and last vertex). if (direction * (sourcePoint[coordinate] - targetPoint[coordinate]) > 0) { targetPoint[coordinate] = sourcePoint[coordinate]; } else { sourcePoint[coordinate] = targetPoint[coordinate]; } return [sourcePoint].concat(vertices, targetPoint); }; joint.routers.orthogonal = (function() { // bearing -> opposite bearing var opposite = { N: 'S', S: 'N', E: 'W', W: 'E' }; // bearing -> radians var radians = { N: -Math.PI / 2 * 3, S: -Math.PI / 2, E: 0, W: Math.PI }; // HELPERS // // simple bearing method (calculates only orthogonal cardinals) function bearing(from, to) { if (from.x == to.x) return from.y > to.y ? 'N' : 'S'; if (from.y == to.y) return from.x > to.x ? 'W' : 'E'; return null; } // returns either width or height of a bbox based on the given bearing function boxSize(bbox, brng) { return bbox[brng == 'W' || brng == 'E' ? 'width' : 'height']; } // expands a box by specific value function expand(bbox, val) { return g.rect(bbox).moveAndExpand({ x: -val, y: -val, width: 2 * val, height: 2 * val }); } // transform point to a rect function pointBox(p) { return g.rect(p.x, p.y, 0, 0); } // returns a minimal rect which covers the given boxes function boundary(bbox1, bbox2) { var x1 = Math.min(bbox1.x, bbox2.x); var y1 = Math.min(bbox1.y, bbox2.y); var x2 = Math.max(bbox1.x + bbox1.width, bbox2.x + bbox2.width); var y2 = Math.max(bbox1.y + bbox1.height, bbox2.y + bbox2.height); return g.rect(x1, y1, x2 - x1, y2 - y1); } // returns a point `p` where lines p,p1 and p,p2 are perpendicular and p is not contained // in the given box function freeJoin(p1, p2, bbox) { var p = g.point(p1.x, p2.y); if (bbox.containsPoint(p)) p = g.point(p2.x, p1.y); // kept for reference // if (bbox.containsPoint(p)) p = null; return p; } // PARTIAL ROUTERS // function vertexVertex(from, to, brng) { var p1 = g.point(from.x, to.y); var p2 = g.point(to.x, from.y); var d1 = bearing(from, p1); var d2 = bearing(from, p2); var xBrng = opposite[brng]; var p = (d1 == brng || (d1 != xBrng && (d2 == xBrng || d2 != brng))) ? p1 : p2; return { points: [p], direction: bearing(p, to) }; } function elementVertex(from, to, fromBBox) { var p = freeJoin(from, to, fromBBox); return { points: [p], direction: bearing(p, to) }; } function vertexElement(from, to, toBBox, brng) { var route = {}; var pts = [g.point(from.x, to.y), g.point(to.x, from.y)]; var freePts = _.filter(pts, function(pt) { return !toBBox.containsPoint(pt); }); var freeBrngPts = _.filter(freePts, function(pt) { return bearing(pt, from) != brng; }); var p; if (freeBrngPts.length > 0) { // try to pick a point which bears the same direction as the previous segment p = _.filter(freeBrngPts, function(pt) { return bearing(from, pt) == brng; }).pop(); p = p || freeBrngPts[0]; route.points = [p]; route.direction = bearing(p, to); } else { // Here we found only points which are either contained in the element or they would create // a link segment going in opposite direction from the previous one. // We take the point inside element and move it outside the element in the direction the // route is going. Now we can join this point with the current end (using freeJoin). p = _.difference(pts, freePts)[0]; var p2 = g.point(to).move(p, -boxSize(toBBox, brng) / 2); var p1 = freeJoin(p2, from, toBBox); route.points = [p1, p2]; route.direction = bearing(p2, to); } return route; } function elementElement(from, to, fromBBox, toBBox) { var route = elementVertex(to, from, toBBox); var p1 = route.points[0]; if (fromBBox.containsPoint(p1)) { route = elementVertex(from, to, fromBBox); var p2 = route.points[0]; if (toBBox.containsPoint(p2)) { var fromBorder = g.point(from).move(p2, -boxSize(fromBBox, bearing(from, p2)) / 2); var toBorder = g.point(to).move(p1, -boxSize(toBBox, bearing(to, p1)) / 2); var mid = g.line(fromBorder, toBorder).midpoint(); var startRoute = elementVertex(from, mid, fromBBox); var endRoute = vertexVertex(mid, to, startRoute.direction); route.points = [startRoute.points[0], endRoute.points[0]]; route.direction = endRoute.direction; } } return route; } // Finds route for situations where one of end is inside the other. // Typically the route is conduct outside the outer element first and // let go back to the inner element. function insideElement(from, to, fromBBox, toBBox, brng) { var route = {}; var bndry = expand(boundary(fromBBox, toBBox), 1); // start from the point which is closer to the boundary var reversed = bndry.center().distance(to) > bndry.center().distance(from); var start = reversed ? to : from; var end = reversed ? from : to; var p1, p2, p3; if (brng) { // Points on circle with radius equals 'W + H` are always outside the rectangle // with width W and height H if the center of that circle is the center of that rectangle. p1 = g.point.fromPolar(bndry.width + bndry.height, radians[brng], start); p1 = bndry.pointNearestToPoint(p1).move(p1, -1); } else { p1 = bndry.pointNearestToPoint(start).move(start, 1); } p2 = freeJoin(p1, end, bndry); if (p1.round().equals(p2.round())) { p2 = g.point.fromPolar(bndry.width + bndry.height, g.toRad(p1.theta(start)) + Math.PI / 2, end); p2 = bndry.pointNearestToPoint(p2).move(end, 1).round(); p3 = freeJoin(p1, p2, bndry); route.points = reversed ? [p2, p3, p1] : [p1, p3, p2]; } else { route.points = reversed ? [p2, p1] : [p1, p2]; } route.direction = reversed ? bearing(p1, to) : bearing(p2, to); return route; } // MAIN ROUTER // // Return points that one needs to draw a connection through in order to have a orthogonal link // routing from source to target going through `vertices`. function findOrthogonalRoute(vertices, opt, linkView) { var padding = opt.elementPadding || 20; var orthogonalVertices = []; var sourceBBox = expand(linkView.sourceBBox, padding); var targetBBox = expand(linkView.targetBBox, padding); vertices = _.map(vertices, g.point); vertices.unshift(sourceBBox.center()); vertices.push(targetBBox.center()); var brng; for (var i = 0, max = vertices.length - 1; i < max; i++) { var route = null; var from = vertices[i]; var to = vertices[i + 1]; var isOrthogonal = !!bearing(from, to); if (i == 0) { if (i + 1 == max) { // route source -> target // Expand one of elements by 1px so we detect also situations when they // are positioned one next other with no gap between. if (sourceBBox.intersect(expand(targetBBox, 1))) { route = insideElement(from, to, sourceBBox, targetBBox); } else if (!isOrthogonal) { route = elementElement(from, to, sourceBBox, targetBBox); } } else { // route source -> vertex if (sourceBBox.containsPoint(to)) { route = insideElement(from, to, sourceBBox, expand(pointBox(to), padding)); } else if (!isOrthogonal) { route = elementVertex(from, to, sourceBBox); } } } else if (i + 1 == max) { // route vertex -> target var orthogonalLoop = isOrthogonal && bearing(to, from) == brng; if (targetBBox.containsPoint(from) || orthogonalLoop) { route = insideElement(from, to, expand(pointBox(from), padding), targetBBox, brng); } else if (!isOrthogonal) { route = vertexElement(from, to, targetBBox, brng); } } else if (!isOrthogonal) { // route vertex -> vertex route = vertexVertex(from, to, brng); } if (route) { Array.prototype.push.apply(orthogonalVertices, route.points); brng = route.direction; } else { // orthogonal route and not looped brng = bearing(from, to); } if (i + 1 < max) { orthogonalVertices.push(to); } } return orthogonalVertices; }; return findOrthogonalRoute; })(); joint.connectors.normal = function(sourcePoint, targetPoint, vertices) { // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex) { d.push(vertex.x, vertex.y); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) { opts = opts || {}; var offset = opts.radius || 10; var c1, c2, d1, d2, prev, next; // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex, index) { // the closest vertices prev = vertices[index - 1] || sourcePoint; next = vertices[index + 1] || targetPoint; // a half distance to the closest vertex d1 = d2 || g.point(vertex).distance(prev) / 2; d2 = g.point(vertex).distance(next) / 2; // control points c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round(); c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round(); d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L'); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) { var d; if (vertices.length) { d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint])); } else { // if we have no vertices use a default cubic bezier curve, cubic bezier requires // two control points. The two control points are both defined with X as mid way // between the source and target points. SourceControlPoint Y is equal to sourcePoint Y // and targetControlPointY being equal to targetPointY. var controlPointX = (sourcePoint.x + targetPoint.x) / 2; d = [ 'M', sourcePoint.x, sourcePoint.y, 'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y, targetPoint.x, targetPoint.y ]; } return d.join(' '); }; joint.connectors.jumpover = (function(_, g) { // default size of jump if not specified in options var JUMP_SIZE = 5; // available jump types var JUMP_TYPES = ['arc', 'gap', 'cubic']; // takes care of math. error for case when jump is too close to end of line var CLOSE_PROXIMITY_PADDING = 1; // list of connector types not to jump over. var IGNORED_CONNECTORS = ['smooth']; /** * Transform start/end and vertices into series of lines * @param {g.point} sourcePoint start point * @param {g.point} targetPoint end point * @param {g.point[]} vertices optional list of vertices * @return {g.line[]} [description] */ function createLines(sourcePoint, targetPoint, vertices) { // make a flattened array of all points var points = [].concat(sourcePoint, vertices, targetPoint); return points.reduce(function(resultLines, point, idx) { // if there is a next point, make a line with it var nextPoint = points[idx + 1]; if (nextPoint != null) { resultLines[idx] = g.line(point, nextPoint); } return resultLines; }, []); } function setupUpdating(jumpOverLinkView) { var updateList = jumpOverLinkView.paper._jumpOverUpdateList; // first time setup for this paper if (updateList == null) { updateList = jumpOverLinkView.paper._jumpOverUpdateList = []; jumpOverLinkView.paper.on('cell:pointerup', updateJumpOver); jumpOverLinkView.paper.model.on('reset', function() { updateList = []; }); } // add this link to a list so it can be updated when some other link is updated if (updateList.indexOf(jumpOverLinkView) < 0) { updateList.push(jumpOverLinkView); // watch for change of connector type or removal of link itself // to remove the link from a list of jump over connectors jumpOverLinkView.listenToOnce(jumpOverLinkView.model, 'change:connector remove', function() { updateList.splice(updateList.indexOf(jumpOverLinkView), 1); }); } } /** * Handler for a batch:stop event to force * update of all registered links with jump over connector * @param {object} batchEvent optional object with info about batch */ function updateJumpOver() { var updateList = this._jumpOverUpdateList; for (var i = 0; i < updateList.length; i++) { updateList[i].update(); } } /** * Utility function to collect all intersection poinst of a single * line against group of other lines. * @param {g.line} line where to find points * @param {g.line[]} crossCheckLines lines to cross * @return {g.point[]} list of intersection points */ function findLineIntersections(line, crossCheckLines) { return _(crossCheckLines).map(function(crossCheckLine) { return line.intersection(crossCheckLine); }).compact().value(); } /** * Sorting function for list of points by their distance. * @param {g.point} p1 first point * @param {g.point} p2 second point * @return {number} squared distance between points */ function sortPoints(p1, p2) { return g.line(p1, p2).squaredLength(); } /** * Split input line into multiple based on intersection points. * @param {g.line} line input line to split * @param {g.point[]} intersections poinst where to split the line * @param {number} jumpSize the size of jump arc (length empty spot on a line) * @return {g.line[]} list of lines being split */ function createJumps(line, intersections, jumpSize) { return intersections.reduce(function(resultLines, point, idx) { // skipping points that were merged with the previous line // to make bigger arc over multiple lines that are close to each other if (point.skip === true) { return resultLines; } // always grab the last line from buffer and modify it var lastLine = resultLines.pop() || line; // calculate start and end of jump by moving by a given size of jump var jumpStart = g.point(point).move(lastLine.start, -(jumpSize)); var jumpEnd = g.point(point).move(lastLine.start, +(jumpSize)); // now try to look at the next intersection point var nextPoint = intersections[idx + 1]; if (nextPoint != null) { var distance = jumpEnd.distance(nextPoint); if (distance <= jumpSize) { // next point is close enough, move the jump end by this // difference and mark the next point to be skipped jumpEnd = nextPoint.move(lastLine.start, distance); nextPoint.skip = true; } } else { // this block is inside of `else` as an optimization so the distance is // not calculated when we know there are no other intersection points var endDistance = jumpStart.distance(lastLine.end); // if the end is too close to possible jump, draw remaining line instead of a jump if (endDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { resultLines.push(lastLine); return resultLines; } } var startDistance = jumpEnd.distance(lastLine.start); if (startDistance < jumpSize * 2 + CLOSE_PROXIMITY_PADDING) { // if the start of line is too close to jump, draw that line instead of a jump resultLines.push(lastLine); return resultLines; } // finally create a jump line var jumpLine = g.line(jumpStart, jumpEnd); // it's just simple line but with a `isJump` property jumpLine.isJump = true; resultLines.push( g.line(lastLine.start, jumpStart), jumpLine, g.line(jumpEnd, lastLine.end) ); return resultLines; }, []); } /** * Assemble `D` attribute of a SVG path by iterating given lines. * @param {g.line[]} lines source lines to use * @param {number} jumpSize the size of jump arc (length empty spot on a line) * @return {string} */ function buildPath(lines, jumpSize, jumpType) { // first move to the start of a first line var start = ['M', lines[0].start.x, lines[0].start.y]; // make a paths from lines var paths = _(lines).map(function(line) { if (line.isJump) { var diff; if (jumpType === 'arc') { diff = line.start.difference(line.end); // determine rotation of arc based on difference between points var xAxisRotate = Number(diff.x < 0 && diff.y < 0); // for a jump line we create an arc instead return ['A', jumpSize, jumpSize, 0, 0, xAxisRotate, line.end.x, line.end.y]; } else if (jumpType === 'gap') { return ['M', line.end.x, line.end.y]; } else if (jumpType === 'cubic') { diff = line.start.difference(line.end); var angle = line.start.theta(line.end); var xOffset = jumpSize * 0.6; var yOffset = jumpSize * 1.35; // determine rotation of curve based on difference between points if (diff.x < 0 && diff.y < 0) { yOffset *= -1; } var controlStartPoint = g.point(line.start.x + xOffset, line.start.y + yOffset).rotate(line.start, angle); var controlEndPoint = g.point(line.end.x - xOffset, line.end.y + yOffset).rotate(line.end, angle); // create a cubic bezier curve return ['C', controlStartPoint.x, controlStartPoint.y, controlEndPoint.x, controlEndPoint.y, line.end.x, line.end.y]; } } return ['L', line.end.x, line.end.y]; }).flatten().value(); return [].concat(start, paths).join(' '); } /** * Actual connector function that will be run on every update. * @param {g.point} sourcePoint start point of this link * @param {g.point} targetPoint end point of this link * @param {g.point[]} vertices of this link * @param {object} opts options * @property {number} size optional size of a jump arc * @return {string} created `D` attribute of SVG path */ return function(sourcePoint, targetPoint, vertices, opts) { // eslint-disable-line max-params setupUpdating(this); var jumpSize = opts.size || JUMP_SIZE; var jumpType = opts.jump && ('' + opts.jump).toLowerCase(); var ignoreConnectors = opts.ignoreConnectors || IGNORED_CONNECTORS; // grab the first jump type as a default if specified one is invalid if (JUMP_TYPES.indexOf(jumpType) === -1) { jumpType = JUMP_TYPES[0]; } var paper = this.paper; var graph = paper.model; var allLinks = graph.getLinks(); // there is just one link, draw it directly if (allLinks.length === 1) { return buildPath( createLines(sourcePoint, targetPoint, vertices), jumpSize, jumpType ); } var thisModel = this.model; var thisIndex = allLinks.indexOf(thisModel); var defaultConnector = paper.options.defaultConnector || {}; // not all links are meant to be jumped over. var links = allLinks.filter(function(link, idx) { var connector = link.get('connector') || defaultConnector; // avoid jumping over links with connector type listed in `ignored connectors`. if (_.contains(ignoreConnectors, connector.name)) { return false; } // filter out links that are above this one and have the same connector type // otherwise there would double hoops for each intersection if (idx > thisIndex) { return connector.name !== 'jumpover'; } return true; }); // find views for all links var linkViews = links.map(function(link) { return paper.findViewByModel(link); }); // create lines for this link var thisLines = createLines( sourcePoint, targetPoint, vertices ); // create lines for all other links var linkLines = linkViews.map(function(linkView) { if (linkView == null) { return []; } if (linkView === this) { return thisLines; } return createLines( linkView.sourcePoint, linkView.targetPoint, linkView.route ); }, this); // transform lines for this link by splitting with jump lines at // points of intersection with other links var jumpingLines = thisLines.reduce(function(resultLines, thisLine) { // iterate all links and grab the intersections with this line // these are then sorted by distance so the line can be split more easily var intersections = _(links).map(function(link, i) { // don't intersection with itself if (link === thisModel) { return null; } return findLineIntersections(thisLine, linkLines[i]); }).flatten().compact().sortBy(_.partial(sortPoints, thisLine.start)).value(); if (intersections.length > 0) { // split the line based on found intersection points resultLines.push.apply(resultLines, createJumps(thisLine, intersections, jumpSize)); } else { // without any intersection the line goes uninterrupted resultLines.push(thisLine); } return resultLines; }, []); return buildPath(jumpingLines, jumpSize, jumpType); }; }(_, g)); joint.highlighters.addClass = { className: joint.util.addClassNamePrefix('highlighted'), highlight: function(cellView, magnetEl, opt) { var className = opt.className || this.className; V(magnetEl).addClass(className); }, unhighlight: function(cellView, magnetEl, opt) { var className = opt.className || this.className; V(magnetEl).removeClass(className); } }; joint.highlighters.opacity = { highlight: function(cellView, magnetEl, opt) { V(magnetEl).addClass(joint.util.addClassNamePrefix('highlight-opacity')); }, unhighlight: function(cellView, magnetEl, opt) { V(magnetEl).removeClass(joint.util.addClassNamePrefix('highlight-opacity')); } }; joint.highlighters.stroke = { defaultOptions: { padding: 3, rx: 0, ry: 0 }, _views: {}, highlight: function(cellView, magnetEl, opt) { // Only highlight once. if (this._views[magnetEl.id]) return; opt = _.defaults(opt || {}, this.defaultOptions); var magnetVel = V(magnetEl); var magnetBBox = magnetVel.bbox(true/* without transforms */); try { var pathData = magnetVel.convertToPathData(); } catch (error) { // Failed to get path data from magnet element. // Draw a rectangle around the entire cell view instead. pathData = V.rectToPath(_.extend({}, opt, magnetBBox)); } var highlightVel = V('path').attr({ d: pathData, 'pointer-events': 'none' }); highlightVel.transform(cellView.el.getCTM().inverse()); highlightVel.transform(magnetEl.getCTM()); var padding = opt.padding; if (padding) { // Add padding to the highlight element. var cx = magnetBBox.x + (magnetBBox.width / 2); var cy = magnetBBox.y + (magnetBBox.height / 2); var sx = (magnetBBox.width + padding) / magnetBBox.width; var sy = (magnetBBox.height + padding) / magnetBBox.height; highlightVel.transform({ a: sx, b: 0, c: 0, d: sy, e: cx - sx * cx, f: cy - sy * cy }); } // joint.mvc.View will handle the theme class name and joint class name prefix. var highlightView = this._views[magnetEl.id] = new joint.mvc.View({ className: 'highlight-stroke', // This is necessary because we're passing in a vectorizer element (not jQuery). el: highlightVel.node, $el: highlightVel }); // Remove the highlight view when the cell is removed from the graph. highlightView.listenTo(cellView.model, 'remove', highlightView.remove); cellView.vel.append(highlightVel); }, unhighlight: function(cellView, magnetEl, opt) { opt = _.defaults(opt || {}, this.defaultOptions); if (this._views[magnetEl.id]) { this._views[magnetEl.id].remove(); this._views[magnetEl.id] = null; } } }; joint.g = g; joint.V = joint.Vectorizer = V; return joint; }));
src/app/components/Footer.js
Boluwatifes/andela24
import React from 'react'; const Footer = () => ( <div className="col s12 home-inner footer" > <div className="inner-content center m-auto"> <p> Copyright &copy; 2017 Andela24 News - All rights reserved </p> </div> </div> ); export default Footer;
src/components/Handle.js
mirokk/react-content-builder
import React from 'react'; import order from '../order'; let rem=(rid)=>{ var element = document.getElementById(rid); element.outerHTML = ""; order(); } export default ({clazz, children, rid})=>( <div className={"handle "+clazz}> {children} <i className="fa fa-trash" onClick={rem.bind(null, rid)} aria-hidden="true"></i> <i className="fa fa-arrows" aria-hidden="true"></i> </div> ); /* var Handle = React.createClass({ render: function(){ return( <div className={"handle "+this.props.clazz}>Move</div> ); } }); export default Handle*/
packages/lightning-core/common/NavFooter.js
DaReaper/lightning-app
import React from 'react' import { Box, Media, Text } from 'lightning-components' import NavFooterAccount from './NavFooterAccount' import { Money, MoneySign } from './' import { total } from '../helpers/wallet' export const NavFooter = ({ pubkey, currency, balances, onClickAccount }) => { return ( <div> <Box padding="small" fontSize="medium" color="gray"> <Media paddingLeft="small" left={ <MoneySign currency={ currency } /> } > <Text color="off-white"> <Money amount={ total(balances) } currency={ currency } /> </Text> </Media> </Box> <NavFooterAccount identity={ pubkey } onClick={ onClickAccount } /> </div> ) } export default NavFooter
web/app/comp.js
bitemyapp/serials
// @flow var React = require('react') export class FormSection extends React.Component { render():React.Element { var contentStyle = { padding: 15, } var headerStyle = { backgroundColor: '#F2F2F2', padding: 15, } var mainStyle = { border: 'solid 1px #D8D8D8', marginBottom: 20 } return <div> <div style={mainStyle}> <div style={headerStyle}>{this.props.title}</div> <div style={contentStyle}>{this.props.children}</div> </div> </div> } } export class DisabledButton extends React.Component { render():React.Element { if (this.props.disabled) { var text = "Disabled" var className = "secondary" } else { var text = "Active" var className = "success" } return <div> <button className={className} onClick={this.props.onClick}>{text}</button> </div> } //toggleActive() { //var source = this.state.source //source.disabled = !source.disabled //this.setState({source: source}) //} }
ajax/libs/js-data/1.5.0/js-data-debug.js
WebReflection/cdnjs
/** * @author Jason Dobry <[email protected]> * @file dist/js-data-debug.js * @version 1.5.0 - Homepage <http://www.js-data.io/> * @copyright (c) 2014 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Data store. */ !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.JSData=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright 2012 Google 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. // Modifications // Copyright 2014-2015 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way to to define a default equality operator for diffObjectFromOldObject // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, delete: true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.diffObjectFromOldObject = diffObjectFromOldObject; global.setEqualityFn = function (fn) { equalityFn = fn; }; global.setBlacklist = function (bl) { blacklist = bl; }; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })(exports); },{}],2:[function(require,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return es6$promise$umd$$ES6Promise; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],3:[function(require,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 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; }; },{}],4:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":6}],5:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],6:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],7:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; },{"./indexOf":6}],8:[function(require,module,exports){ /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; },{}],9:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],10:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],11:[function(require,module,exports){ /** * Checks if the object is a primitive */ function isPrimitive(value) { // Using switch fallthrough because it's simple to read and is // generally fast: http://jsperf.com/testing-value-is-primitive/5 switch (typeof value) { case "string": case "number": case "boolean": return true; } return value == null; } module.exports = isPrimitive; },{}],12:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],13:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":10,"./forOwn":15}],14:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{"./hasOwn":17}],15:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":14,"./hasOwn":17}],16:[function(require,module,exports){ var isPrimitive = require('../lang/isPrimitive'); /** * get "nested" object property */ function get(obj, prop){ var parts = prop.split('.'), last = parts.pop(); while (prop = parts.shift()) { obj = obj[prop]; if (obj == null) return; } return obj[last]; } module.exports = get; },{"../lang/isPrimitive":11}],17:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],18:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; },{"../array/forEach":5}],19:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; },{"../array/slice":8}],20:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; },{"./namespace":18}],21:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":12,"./lowerCase":22,"./removeNonWord":24,"./replaceAccents":25,"./upperCase":26}],22:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":12}],23:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":12,"./camelCase":21,"./upperCase":26}],24:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":12}],25:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; },{"../lang/toString":12}],26:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":12}],27:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function create(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; attrs = attrs || {}; var rejectionError; if (!definition) { rejectionError = new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs)) { rejectionError = DSUtils._oErr('attrs'); } else { options = DSUtils._(definition, options); if (options.upsert && DSUtils._sn(attrs[definition.idAttribute])) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } options.logFn('create', attrs, options); } return new DSUtils.Promise(function (resolve, reject) { if (rejectionError) { reject(rejectionError); } else { resolve(attrs); } }) .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.beforeCreate', definition, DSUtils.copy(attrs)); } return _this.getAdapter(options).create(definition, attrs, options); }) .then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.afterCreate', definition, DSUtils.copy(attrs)); } if (options.cacheResponse) { var created = _this.inject(definition.n, attrs, options); var id = created[definition.idAttribute]; _this.s[resourceName].completedQueries[id] = new Date().getTime(); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = create; },{"../../errors":48,"../../utils":50}],28:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroy(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); options.logFn('destroy', id, options); resolve(item); } }) .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.beforeDestroy', definition, DSUtils.copy(attrs)); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }) .then(function () { return options.afterDestroy.call(item, options, item); }) .then(function (item) { if (options.notify) { definition.emit('DS.afterDestroy', definition, DSUtils.copy(item)); } _this.eject(resourceName, id); return id; })['catch'](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } module.exports = destroy; },{"../../errors":48,"../../utils":50}],29:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroyAll(resourceName, params, options) { var _this = this; var definition = _this.defs[resourceName]; var ejected, toEject; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('attrs')); } else { options = DSUtils._(definition, options); options.logFn('destroyAll', params, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.beforeDestroy', definition, DSUtils.copy(toEject)); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { definition.emit('DS.afterDestroy', definition, DSUtils.copy(toEject)); } return ejected || _this.ejectAll(resourceName, params); })['catch'](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } module.exports = destroyAll; },{"../../errors":48,"../../utils":50}],30:[function(require,module,exports){ /* jshint -W082 */ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function find(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); options.logFn('find', id, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries && _this.get(resourceName, id)) { resolve(_this.get(resourceName, id)); } else { delete resource.completedQueries[id]; resolve(); } } }).then(function (item) { if (!item) { if (!(id in resource.pendingQueries)) { var promise; var strategy = options.findStrategy || options.strategy; if (strategy === 'fallback') { function makeFallbackCall(index) { return _this.getAdapter((options.findFallbackAdapters || options.fallbackAdapters)[index]).find(definition, id, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); } promise = makeFallbackCall(0); } else { promise = _this.getAdapter(options).find(definition, id, options); } resource.pendingQueries[id] = promise.then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { var injected = _this.inject(resourceName, data, options); resource.completedQueries[id] = new Date().getTime(); return injected; } else { return _this.createInstance(resourceName, data, options); } }); } return resource.pendingQueries[id]; } else { return item; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } module.exports = find; },{"../../errors":48,"../../utils":50}],31:[function(require,module,exports){ /* jshint -W082 */ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function processResults(data, resourceName, queryHash, options) { var _this = this; var resource = _this.s[resourceName]; var idAttribute = _this.defs[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options); // Make sure each object is added to completedQueries if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { options.errorFn('response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var queryHash; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.defs[resourceName]) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(params)) { reject(DSUtils._oErr('params')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); options.logFn('findAll', params, options); if (options.params) { options.params = DSUtils.copy(options.params); } if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; } if (queryHash in resource.completedQueries) { if (options.useFilter) { resolve(_this.filter(resourceName, params, options)); } else { resolve(resource.queryData[queryHash]); } } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { var promise; var strategy = options.findAllStrategy || options.strategy; if (strategy === 'fallback') { function makeFallbackCall(index) { return _this.getAdapter((options.findAllFallbackAdapters || options.fallbackAdapters)[index]).findAll(definition, params, options)['catch'](function (err) { index++; if (index < options.fallbackAdapters.length) { return makeFallbackCall(index); } else { return Promise.reject(err); } }); } promise = makeFallbackCall(0); } else { promise = _this.getAdapter(options).findAll(definition, params, options); } resource.pendingQueries[queryHash] = promise.then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { resource.queryData[queryHash] = processResults.call(_this, data, resourceName, queryHash, options); resource.queryData[queryHash].$$injected = true; return resource.queryData[queryHash]; } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } module.exports = findAll; },{"../../errors":48,"../../utils":50}],32:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function reap(resourceName, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('notify')) { options.notify = false; } options.logFn('reap', options); var items = []; var now = new Date().getTime(); var expiredItem; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); definition.emit('DS.beforeReap', definition, DSUtils.copy(items)); } if (options.reapAction === 'inject') { DSUtils.forEach(items, function (item) { var id = item[definition.idAttribute]; resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); }); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return DSUtils.Promise.all(tasks); } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); definition.emit('DS.afterReap', definition, DSUtils.copy(items)); } return items; }); } function refresh(resourceName, id, options) { var _this = this; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.defs[resourceName]; id = DSUtils.resolveId(_this.defs[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); options.bypassCache = true; options.logFn('refresh', id, options); resolve(_this.get(resourceName, id)); } }).then(function (item) { if (item) { return _this.find(resourceName, id, options); } else { return item; } }); } module.exports = { create: require('./create'), destroy: require('./destroy'), destroyAll: require('./destroyAll'), find: require('./find'), findAll: require('./findAll'), loadRelations: require('./loadRelations'), reap: reap, refresh: refresh, save: require('./save'), update: require('./update'), updateAll: require('./updateAll') }; },{"../../errors":48,"../../utils":50,"./create":27,"./destroy":28,"./destroyAll":29,"./find":30,"./findAll":31,"./loadRelations":33,"./save":34,"./update":35,"./updateAll":36}],33:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function loadRelations(resourceName, instance, relations, options) { var _this = this; var definition = _this.defs[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils._sn(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils._s(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._o(instance)) { reject(new DSErrors.IA('"instance(id)" must be a string, number or object!')); } else if (!DSUtils._a(relations)) { reject(new DSErrors.IA('"relations" must be a string or an array!')); } else { var _options = DSUtils._(definition, options); if (!_options.hasOwnProperty('findBelongsTo')) { _options.findBelongsTo = true; } if (!_options.hasOwnProperty('findHasMany')) { _options.findHasMany = true; } _options.logFn('loadRelations', instance, relations, _options); var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = definition.getResource(relationName); var __options = DSUtils._(relationDef, options); if (DSUtils.contains(relations, relationName) || DSUtils.contains(relations, def.localField)) { var task; var params = {}; if (__options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany' && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], __options); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, __options).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); } }) .then(function (tasks) { return DSUtils.Promise.all(tasks); }) .then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } module.exports = loadRelations; },{"../../errors":48,"../../utils":50}],34:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function save(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); options.logFn('save', id, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, DSUtils.copy(attrs)); } if (options.changesOnly) { var resource = _this.s[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.n, attrs, options); } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = save; },{"../../errors":48,"../../utils":50}],35:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function update(resourceName, id, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils._sn(id)) { reject(DSUtils._snErr('id')); } else { options = DSUtils._(definition, options); options.logFn('update', id, attrs, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, DSUtils.copy(attrs)); } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.afterUpdate', definition, DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.n, attrs, options); } else { return _this.createInstance(resourceName, attrs, options); } }); } module.exports = update; },{"../../errors":48,"../../utils":50}],36:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function updateAll(resourceName, attrs, params, options) { var _this = this; var definition = _this.defs[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); options.logFn('updateAll', attrs, params, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { definition.emit('DS.beforeUpdate', definition, DSUtils.copy(attrs)); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (data) { if (options.notify) { definition.emit('DS.afterUpdate', definition, DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.n, data, options); } else { var instances = []; DSUtils.forEach(data, function (item) { instances.push(_this.createInstance(resourceName, item, options)); }); return instances; } }); } module.exports = updateAll; },{"../../errors":48,"../../utils":50}],37:[function(require,module,exports){ var DSUtils = require('../utils'); var DSErrors = require('../errors'); var syncMethods = require('./sync_methods'); var asyncMethods = require('./async_methods'); var Schemator; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(orderBy, index, a, b) { var def = orderBy[index]; var cA = DSUtils.get(a, def[0]), cB = DSUtils.get(b, def[0]); if (DSUtils._s(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils._s(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } } function Defaults() { } var defaultsPrototype = Defaults.prototype; defaultsPrototype.actions = {}; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.basePath = ''; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.bypassCache = false; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.debug = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.endpoint = ''; defaultsPrototype.error = console ? function (a, b, c) { console[typeof console.error === 'function' ? 'error' : 'log'](a, b, c); } : false; defaultsPrototype.errorFn = function (a, b) { if (this.error && typeof this.error === 'function') { try { if (typeof a === 'string') { throw new Error(a); } else { throw a; } } catch (err) { a = err; } this.error(this.name || null, a || null, b || null); } }; defaultsPrototype.fallbackAdapters = ['http']; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.findInverseLinks = true; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.ignoreMissing = false; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.loadFromServer = false; defaultsPrototype.log = console ? function (a, b, c, d, e) { console[typeof console.info === 'function' ? 'info' : 'log'](a, b, c, d, e); } : false; defaultsPrototype.logFn = function (a, b, c, d) { if (this.debug && this.log && typeof this.log === 'function') { this.log(this.name || null, a || null, b || null, c || null, d || null); } }; defaultsPrototype.maxAge = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.reapAction = !!DSUtils.w ? 'inject' : 'none'; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.strategy = 'single'; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.useClass = true; defaultsPrototype.useFilter = false; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (DSUtils._o(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils._s(clause)) { clause = { '===': clause }; } else if (DSUtils._n(clause) || DSUtils.isBoolean(clause)) { clause = { '==': clause }; } if (DSUtils._o(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr; var isOr = op[0] === '|'; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === '==') { expr = val == term; } else if (op === '===') { expr = val === term; } else if (op === '!=') { expr = val != term; } else if (op === '!==') { expr = val !== term; } else if (op === '>') { expr = val > term; } else if (op === '>=') { expr = val >= term; } else if (op === '<') { expr = val < term; } else if (op === '<=') { expr = val <= term; } else if (op === 'isectEmpty') { expr = !DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'isectNotEmpty') { expr = DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'in') { if (DSUtils._s(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === 'notIn') { if (DSUtils._s(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } else if (op === 'contains') { if (DSUtils._s(val)) { expr = val.indexOf(term) !== -1; } else { expr = DSUtils.contains(val, term); } } else if (op === 'notContains') { if (DSUtils._s(val)) { expr = val.indexOf(term) === -1; } else { expr = !DSUtils.contains(val, term); } } if (expr !== undefined) { keep = first ? expr : (isOr ? keep || expr : keep && expr); } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils._s(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (DSUtils._a(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils._s(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && DSUtils._a(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils._s(def)) { orderBy[i] = [def, 'ASC']; } else if (!DSUtils._a(def)) { throw new DSErrors.IA('DS.filter(resourceName[, params][, options]): ' + DSUtils.toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); } var limit = DSUtils._n(params.limit) ? params.limit : null; var skip = null; if (DSUtils._n(params.skip)) { skip = params.skip; } else if (DSUtils._n(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils._n(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils._n(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; function DS(options) { var _this = this; options = options || {}; try { Schemator = require('js-data-schema'); } catch (e) { } if (!Schemator || DSUtils.isEmpty(Schemator)) { try { Schemator = window.Schemator; } catch (e) { } } if (Schemator || options.schemator) { _this.schemator = options.schemator || new Schemator(); } _this.store = {}; // alias store, shaves 0.1 kb off the minified build _this.s = _this.store; _this.definitions = {}; // alias definitions, shaves 0.3 kb off the minified build _this.defs = _this.definitions; _this.adapters = {}; _this.defaults = new Defaults(); _this.observe = DSUtils.observe; DSUtils.forOwn(options, function (v, k) { _this.defaults[k] = v; }); _this.defaults.logFn('new data store created', _this.defaults); } var dsPrototype = DS.prototype; dsPrototype.getAdapter = function getAdapter(options) { var errorIfNotExist = false; options = options || {}; this.defaults.logFn('getAdapter', options); if (DSUtils._s(options)) { errorIfNotExist = true; options = { adapter: options }; } var adapter = this.adapters[options.adapter]; if (adapter) { return adapter; } else if (errorIfNotExist) { throw new Error(options.adapter + ' is not a registered adapter!'); } else { return this.adapters[options.defaultAdapter]; } }; dsPrototype.getAdapter.shorthand = false; dsPrototype.registerAdapter = function registerAdapter(name, Adapter, options) { var _this = this; options = options || {}; _this.defaults.logFn('registerAdapter', name, Adapter, options); if (DSUtils.isFunction(Adapter)) { _this.adapters[name] = new Adapter(options); } else { _this.adapters[name] = Adapter; } if (options.default) { _this.defaults.defaultAdapter = name; } _this.defaults.logFn('default adapter is ' + _this.defaults.defaultAdapter); }; dsPrototype.registerAdapter.shorthand = false; dsPrototype.is = function is(resourceName, instance) { var definition = this.defs[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } return instance instanceof definition[definition.class]; }; dsPrototype.errors = require('../errors'); dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; },{"../errors":48,"../utils":50,"./async_methods":32,"./sync_methods":42,"js-data-schema":"js-data-schema"}],38:[function(require,module,exports){ /*jshint evil:true, loopfunc:true*/ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function Resource(options) { DSUtils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var instanceMethods = [ 'compute', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'link', 'linkInverse', 'previous', 'unlinkInverse' ]; function defineResource(definition) { var _this = this; var definitions = _this.defs; if (DSUtils._s(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!DSUtils._o(definition)) { throw DSUtils._oErr('definition'); } else if (!DSUtils._s(definition.name)) { throw new DSErrors.IA('"name" must be a string!'); } else if (_this.s[definition.name]) { throw new DSErrors.R(definition.name + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; // alias name, shaves 0.08 kb off the minified build def.n = def.name; def.logFn('Preparing resource.'); if (!DSUtils._s(def.idAttribute)) { throw new DSErrors.IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils._a(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.n; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; def.parentField = relation.localField; } }); }); } if (typeof Object.freeze === 'function') { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getResource = function (resourceName) { return _this.defs[resourceName]; }; def.getEndpoint = function (id, options) { options.params = options.params || {}; var item; var parentKey = def.parentKey; var endpoint = options.hasOwnProperty('endpoint') ? options.endpoint : def.endpoint; var parentField = def.parentField; var parentDef = definitions[def.parent]; var parentId = options.params[parentKey]; if (parentId === false || !parentKey || !parentDef) { if (parentId === false) { delete options.params[parentKey]; } return endpoint; } else { delete options.params[parentKey]; if (DSUtils._sn(id)) { item = def.get(id); } else if (DSUtils._o(id)) { item = id; } if (item) { parentId = parentId || item[parentKey] || (item[parentField] ? item[parentField][parentDef.idAttribute] : null); } if (parentId) { delete options.endpoint; var _options = {}; DSUtils.forOwn(options, function (value, key) { _options[key] = value; }); return DSUtils.makePath(parentDef.getEndpoint(parentId, DSUtils._(parentDef, _options)), parentId, endpoint); } else { return endpoint; } } }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource def['class'] = DSUtils.pascalCase(def.name); try { if (typeof def.useClass === 'function') { eval('function ' + def['class'] + '() { def.useClass.call(this); }'); def[def['class']] = eval(def['class']); def[def['class']].prototype = (function (proto) { function Ctor() { } Ctor.prototype = proto; return new Ctor(); })(def.useClass.prototype); } else { eval('function ' + def['class'] + '() {}'); def[def['class']] = eval(def['class']); } } catch (e) { def[def['class']] = function () { }; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[def['class']].prototype, def.methods); } def[def['class']].prototype.set = function (key, value) { DSUtils.set(this, key, value); var observer = _this.s[def.n].observers[this[def.idAttribute]]; if (observer && !DSUtils.observe.hasObjectObserve) { observer.deliver(); } else { _this.compute(def.n, this); } return this; }; def[def['class']].prototype.get = function (key) { return DSUtils.get(this, key); }; // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { def.errorFn('Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { def.errorFn('Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.n, definition.schema); if (!definition.hasOwnProperty('validate')) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this[def.idAttribute] || this); args.unshift(def.n); return _this[name].apply(_this, args); }; }); def[def['class']].prototype.DSCreate = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this); args.unshift(def.n); return _this.create.apply(_this, args); }; // Initialize store data for the new resource _this.s[def.n] = { collection: [], expiresHeap: new DSUtils.DSBinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, queryData: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { _this.reap(def.n, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones for (var key in _this) { if (typeof _this[key] === 'function') { if (_this[key].shorthand !== false) { (function (k) { def[k] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.n); return _this[k].apply(_this, args); }; })(key); } else { (function (k) { def[k] = function () { return _this[k].apply(_this, Array.prototype.slice.call(arguments)); }; })(key); } } } def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); DSUtils.forOwn(def.actions, function addAction(action, name) { if (def[name]) { throw new Error('Cannot override existing method "' + name + '"!'); } def[name] = function (options) { options = options || {}; var adapter = _this.getAdapter(action.adapter || 'http'); var config = DSUtils.deepMixIn({}, action); if (!options.hasOwnProperty('endpoint') && config.endpoint) { options.endpoint = config.endpoint; } if (typeof options.getEndpoint === 'function') { config.url = options.getEndpoint(def, options); } else { config.url = DSUtils.makePath(options.basePath || adapter.defaults.basePath || def.basePath, def.getEndpoint(null, options), name); } config.method = config.method || 'GET'; DSUtils.deepMixIn(config, options); return adapter.HTTP(config); }; }); // Mix-in events DSUtils.Events(def); def.logFn('Done preparing resource.'); return def; } catch (err) { delete definitions[definition.name]; delete _this.s[definition.name]; throw err; } } module.exports = defineResource; },{"../../errors":48,"../../utils":50}],39:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function eject(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var item; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } options = DSUtils._(definition, options); options.logFn('eject', id, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { if (options.notify) { definition.beforeEject(options, item); definition.emit('DS.beforeEject', definition, DSUtils.copy(item)); } _this.unlinkInverse(definition.n, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); var toRemove = []; DSUtils.forOwn(resource.queryData, function (items, queryHash) { if (items.$$injected) { DSUtils.remove(items, item); } if (!items.length) { toRemove.push(queryHash); } }); DSUtils.forEach(toRemove, function (queryHash) { delete resource.completedQueries[queryHash]; delete resource.queryData[queryHash]; }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); definition.emit('DS.afterEject', definition, DSUtils.copy(item)); } return item; } } module.exports = eject; },{"../../errors":48,"../../utils":50}],40:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function ejectAll(resourceName, params, options) { var _this = this; var definition = _this.defs[resourceName]; params = params || {}; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(params)) { throw DSUtils._oErr('params'); } definition.logFn('ejectAll', params, options); var resource = _this.s[resourceName]; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.n, params); var ids = []; DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.n, id, options); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } module.exports = ejectAll; },{"../../errors":48,"../../utils":50}],41:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function filter(resourceName, params, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } else if (params && !DSUtils._o(params)) { throw DSUtils._oErr('params'); } options = DSUtils._(definition, options); options.logFn('filter', params, options); // Protect against null params = params || {}; var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } module.exports = filter; },{"../../errors":48,"../../utils":50}],42:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); var NER = DSErrors.NER; var IA = DSErrors.IA; var R = DSErrors.R; function changes(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } options = DSUtils._(definition, options); options.logFn('changes', id, options); var item = _this.get(resourceName, id); if (item) { if (DSUtils.w) { _this.s[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.s[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return diff; } } function changeHistory(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.defs[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils._sn(id)) { throw DSUtils._snErr('id'); } definition.logFn('changeHistory', id); if (!definition.keepChangeHistory) { definition.errorFn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } } function compute(resourceName, instance) { var _this = this; var definition = _this.defs[resourceName]; instance = DSUtils.resolveItem(_this.s[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!instance) { throw new R('Item not in the store!'); } else if (!DSUtils._o(instance) && !DSUtils._sn(instance)) { throw new IA('"instance" must be an object, string or number!'); } definition.logFn('compute', instance); DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; } function createInstance(resourceName, attrs, options) { var definition = this.defs[resourceName]; var item; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = DSUtils._(definition, options); options.logFn('createInstance', attrs, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition.class]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; } function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } function digest() { this.observe.Platform.performMicrotaskCheckpoint(); } function get(resourceName, id, options) { var _this = this; var definition = _this.defs[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } options = DSUtils._(definition, options); options.logFn('get', id, options); // cache miss, request resource from server var item = _this.s[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; } function getAll(resourceName, ids) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var collection = []; if (!definition) { throw new NER(resourceName); } else if (ids && !DSUtils._a(ids)) { throw DSUtils._aErr('ids'); } definition.logFn('getAll', ids); if (DSUtils._a(ids)) { var length = ids.length; for (var i = 0; i < length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; } function hasChanges(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } definition.logFn('hasChanges', id); // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } } function lastModified(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn('lastModified', id); if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } function lastSaved(resourceName, id) { var definition = this.defs[resourceName]; var resource = this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } definition.logFn('lastSaved', id); if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } function previous(resourceName, id) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } definition.logFn('previous', id); // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; } module.exports = { changes: changes, changeHistory: changeHistory, compute: compute, createInstance: createInstance, defineResource: require('./defineResource'), digest: digest, eject: require('./eject'), ejectAll: require('./ejectAll'), filter: require('./filter'), get: get, getAll: getAll, hasChanges: hasChanges, inject: require('./inject'), lastModified: lastModified, lastSaved: lastSaved, link: require('./link'), linkAll: require('./linkAll'), linkInverse: require('./linkInverse'), previous: previous, unlinkInverse: require('./unlinkInverse') }; },{"../../errors":48,"../../utils":50,"./defineResource":38,"./eject":39,"./ejectAll":40,"./filter":41,"./inject":43,"./link":44,"./linkAll":45,"./linkInverse":46,"./unlinkInverse":47}],43:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function _getReactFunction(DS, definition, resource) { var name = definition.n; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "' + name + '" resource is now in an undefined (probably broken) state.'); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected; if (DSUtils._a(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); } if (!(idA in attrs)) { var error = new DSErrors.R(definition.n + '.inject: "attrs" must contain the property specified by `idAttribute`!'); options.errorFn(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.defs[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R(definition.n + ' relation is defined but the resource is not!'); } if (DSUtils._a(toInject)) { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.s[relationName][toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } }); attrs[def.localField] = items; } else { if (toInject !== _this.s[relationName][toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { options.errorFn(err, 'Failed to inject ' + def.type + ' relation: "' + relationName + '"!'); } } } } }); var id = attrs[idA]; var item = _this.get(definition.n, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } } else { item = {}; } resource.previousAttributes[id] = DSUtils.copy(attrs); DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = {}; DSUtils.deepMixIn(resource.previousAttributes[id], attrs); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { options.errorFn(err, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) { _this.link(definition.n, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.defs[resourceName]; var resource = _this.s[resourceName]; var injected; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._o(attrs) && !DSUtils._a(attrs)) { throw new DSErrors.IA(resourceName + '.inject: "attrs" must be an object or an array!'); } var name = definition.n; options = DSUtils._(definition, options); options.logFn('inject', attrs, options); if (options.notify) { options.beforeInject(options, attrs); definition.emit('DS.beforeInject', definition, DSUtils.copy(attrs)); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils._a(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils._a(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); definition.emit('DS.afterInject', definition, DSUtils.copy(injected)); } return injected; } module.exports = inject; },{"../../errors":48,"../../utils":50}],44:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function link(resourceName, id, relations) { var _this = this; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr('relations'); } definition.logFn('link', id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === 'belongsTo') { var parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (parent) { linked[def.localField] = parent; } } else if (def.type === 'hasMany') { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === 'hasOne') { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } module.exports = link; },{"../../errors":48,"../../utils":50}],45:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkAll(resourceName, params, relations) { var _this = this; var definition = _this.defs[resourceName]; relations = relations || []; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr('relations'); } definition.logFn('linkAll', params, relations); var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === 'belongsTo') { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === 'hasMany') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === 'hasOne') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.s[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } module.exports = linkAll; },{"../../errors":48,"../../utils":50}],46:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkInverse(resourceName, id, relations) { var _this = this; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr('relations'); } definition.logFn('linkInverse', id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.n)) { return; } if (definition.n === relationName) { _this.linkAll(d.n, {}, [definition.n]); } }); }); }); } return linked; } module.exports = linkInverse; },{"../../errors":48,"../../utils":50}],47:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function unlinkInverse(resourceName, id, relations) { var _this = this; var definition = _this.defs[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils._sn(id)) { throw DSUtils._snErr('id'); } else if (!DSUtils._a(relations)) { throw DSUtils._aErr('relations'); } definition.logFn('unlinkInverse', id, relations); var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.defs, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.n === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.s[def.name].collection, function (item) { if (def.type === 'hasMany' && item[def.localField]) { var index; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); item[def.localField].splice(index, 1); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } module.exports = unlinkInverse; },{"../../errors":48,"../../utils":50}],48:[function(require,module,exports){ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = new Error(); IllegalArgumentError.prototype.constructor = IllegalArgumentError; function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = new Error(); RuntimeError.prototype.constructor = RuntimeError; function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = new Error(); NonexistentResourceError.prototype.constructor = NonexistentResourceError; module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; },{}],49:[function(require,module,exports){ var DS = require('./datastore'); module.exports = { DS: DS, createStore: function (options) { return new DS(options); }, DSUtils: require('./utils'), DSErrors: require('./errors'), version: { full: '1.5.0', major: parseInt('1', 10), minor: parseInt('5', 10), patch: parseInt('0', 10), alpha: 'false' !== 'false' ? 'false' : false, beta: 'false' !== 'false' ? 'false' : false } }; },{"./datastore":37,"./errors":48,"./utils":50}],50:[function(require,module,exports){ /* jshint -W041 */ var w, _Promise; var objectProto = Object.prototype; var toString = objectProto.toString; var DSErrors = require('./errors'); var forEach = require('mout/array/forEach'); var slice = require('mout/array/slice'); var forOwn = require('mout/object/forOwn'); var observe = require('../lib/observe-js/observe-js'); var es6Promise = require('es6-promise'); es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == '[object Array]' || false; }; function isRegExp(value) { return toString.call(value) == '[object RegExp]' || false; } // adapted from lodash.isBoolean function isBoolean(value) { return (value === true || value === false || value && typeof value == 'object' && toString.call(value) == '[object Boolean]') || false; } // adapted from lodash.isString function isString(value) { return typeof value == 'string' || (value && typeof value == 'object' && toString.call(value) == '[object String]') || false; } function isObject(value) { return toString.call(value) == '[object Object]' || false; } // adapted from lodash.isDate function isDate(value) { return (value && typeof value == 'object' && toString.call(value) == '[object Date]') || false; } // adapted from lodash.isNumber function isNumber(value) { var type = typeof value; return type == 'number' || (value && type == 'object' && toString.call(value) == '[object Number]') || false; } // adapted from lodash.isFunction function isFunction(value) { return typeof value == 'function' || (value && toString.call(value) === '[object Function]') || false; } // shorthand argument checking functions, using these shaves 1.18 kb off of the minified build function isStringOrNumber(value) { return isString(value) || isNumber(value); } function isStringOrNumberErr(field) { return new DSErrors.IA('"' + field + '" must be a string or a number!'); } function isObjectErr(field) { return new DSErrors.IA('"' + field + '" must be an object!'); } function isArrayErr(field) { return new DSErrors.IA('"' + field + '" must be an array!'); } // adapted from mout.isEmpty function isEmpty(val) { if (val == null) { // typeof null == 'object' so we check it first return true; } else if (typeof val === 'string' || isArray(val)) { return !val.length; } else if (typeof val === 'object') { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return result; } else { return true; } } function intersection(array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item; for (var i = 0, length = array1.length; i < length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; } function filter(array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; } function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype['finally']) { w.Promise.prototype['finally'] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = require('bluebird'); } function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { var args = Array.prototype.slice.call(arguments); var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(parent)) { break; } else { heap[parentN] = element; heap[n] = parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ function bubbleDown(heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } } function DSBinaryHeap(weightFunc, compareFunc) { if (weightFunc && !isFunction(weightFunc)) { throw new Error('DSBinaryHeap(weightFunc): weightFunc: must be a function!'); } weightFunc = weightFunc || function (x) { return x; }; compareFunc = compareFunc || function (x, y) { return x === y; }; this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } var dsp = DSBinaryHeap.prototype; dsp.push = function (node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); }; dsp.peek = function () { return this.heap[0]; }; dsp.pop = function () { var front = this.heap[0], end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; }; dsp.remove = function (node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; }; dsp.removeAll = function () { this.heap = []; }; dsp.size = function () { return this.heap.length; }; var toPromisify = [ 'beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; // adapted from angular.copy function copy(source, destination, stackSource, stackDest) { if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, [], stackSource, stackDest); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isRegExp(source)) { destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); destination.lastIndex = source.lastIndex; } else if (isObject(source)) { var emptyObject = Object.create(Object.getPrototypeOf(source)); destination = copy(source, emptyObject, stackSource, stackDest); } } } else { if (source === destination) { throw new Error('Cannot copy! Source and destination are identical.'); } stackSource = stackSource || []; stackDest = stackDest || []; if (isObject(source)) { var index = stackSource.indexOf(source); if (index !== -1) return stackDest[index]; stackSource.push(source); stackDest.push(destination); } var result; if (isArray(source)) { destination.length = 0; for (var i = 0; i < source.length; i++) { result = copy(source[i], null, stackSource, stackDest); if (isObject(source[i])) { stackSource.push(source[i]); stackDest.push(result); } destination.push(result); } } else { if (isArray(destination)) { destination.length = 0; } else { forEach(destination, function (value, key) { delete destination[key]; }); } for (var key in source) { if (source.hasOwnProperty(key)) { result = copy(source[key], null, stackSource, stackDest); if (isObject(source[key])) { stackSource.push(source[key]); stackDest.push(result); } destination[key] = result; } } } } return destination; } // adapted from angular.equals function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if (!isArray(o2)) return false; if ((length = o1.length) == o2.length) { for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { if (!isDate(o2)) return false; return equals(o1.getTime(), o2.getTime()); } else if (isRegExp(o1) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(o2)) return false; keySet = {}; for (key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for (key in o2) { if (!keySet.hasOwnProperty(key) && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function resolveId(definition, idOrInstance) { if (this.isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } } function resolveItem(resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } } function isValidString(val) { return (val != null && val !== ''); } function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } function makePath(var_args) { var result = join(slice(arguments), '/'); return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } observe.setEqualityFn(equals); var DSUtils = { // Options that inherit from defaults _: function (parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA('"options" must be an object!'); } forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('var args = Array') === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; return new O(options); }, _n: isNumber, _s: isString, _sn: isStringOrNumber, _snErr: isStringOrNumberErr, _o: isObject, _oErr: isObjectErr, _a: isArray, _aErr: isArrayErr, compute: function (fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: require('mout/array/contains'), copy: copy, deepMixIn: require('mout/object/deepMixIn'), diffObjectFromOldObject: observe.diffObjectFromOldObject, DSBinaryHeap: DSBinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function (json) { return isString(json) ? JSON.parse(json) : json; }, get: require('mout/object/get'), intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: require('mout/string/pascalCase'), pick: require('mout/object/pick'), Promise: _Promise, promisify: function (fn, target) { var Promise = this.Promise; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { var args = Array.prototype.slice.apply(arguments); return new Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: require('mout/array/remove'), set: require('mout/object/set'), slice: slice, sort: require('mout/array/sort'), toJson: JSON.stringify, updateTimestamp: updateTimestamp, upperCase: require('mout/string/upperCase'), removeCircular: function (object) { var objects = []; return (function rmCirc(value) { var i; var nu; if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return undefined; } } objects.push(value); if (DSUtils.isArray(value)) { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = rmCirc(value[i]); } } else { nu = {}; forOwn(value, function (v, k) { nu[k] = rmCirc(value[k]); }); } return nu; } return value; }(object)); }, resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; },{"../lib/observe-js/observe-js":1,"./errors":48,"bluebird":"bluebird","es6-promise":2,"mout/array/contains":4,"mout/array/forEach":5,"mout/array/remove":7,"mout/array/slice":8,"mout/array/sort":9,"mout/object/deepMixIn":13,"mout/object/forOwn":15,"mout/object/get":16,"mout/object/pick":19,"mout/object/set":20,"mout/string/pascalCase":23,"mout/string/upperCase":26}]},{},[49])(49) });
app/main.js
angoz/webpack-sample-project
// var greeter = require('./Greeter.js'); // // document.getElementById('root').appendChild(greeter()); import React from 'react'; import {render} from 'react-dom'; import Greeter from './Greeter.js'; import './main.css'; // 使用 require 导入 css 文件 render(<Greeter />, document.getElementById('root'));
docs/src/app/components/pages/components/Popover/ExampleSimple.js
matthewoates/material-ui
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import Popover from 'material-ui/Popover'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; export default class PopoverExampleSimple extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } handleTouchTap = (event) => { // This prevents ghost click. event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; render() { return ( <div> <RaisedButton onTouchTap={this.handleTouchTap} label="Click me" /> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} onRequestClose={this.handleRequestClose} > <Menu> <MenuItem primaryText="Refresh" /> <MenuItem primaryText="Help &amp; feedback" /> <MenuItem primaryText="Settings" /> <MenuItem primaryText="Sign out" /> </Menu> </Popover> </div> ); } }
fields/types/select/SelectColumn.js
tony2cssc/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; var SelectColumn = React.createClass({ displayName: 'SelectColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; const option = this.props.col.field.ops.filter(i => i.value === value)[0]; return option ? option.label : null; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = SelectColumn;
app/components/Nav.js
asuh/github-battle
import React from 'react' import { NavLink } from 'react-router-dom' function Nav() { return ( <ul className='nav'> <li> <NavLink exact activeClassName='active' to='/'> Home </NavLink> </li> <li> <NavLink activeClassName='active' to='/battle'> Battle </NavLink> </li> <li> <NavLink activeClassName='active' to='/popular'> Popular </NavLink> </li> </ul> ) } export default Nav;
src/parser/warlock/demonology/modules/soulshards/SoulShardDetails.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown'; import Panel from 'interface/others/Panel'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import WastedShardsIcon from 'parser/warlock/shared/images/warlock_soulshard_bw.jpg'; import SoulShardTracker from './SoulShardTracker'; const SOUL_SHARD_ICON = 'inv_misc_gem_amethyst_02'; class SoulShardDetails extends Analyzer { static dependencies = { soulShardTracker: SoulShardTracker, }; get suggestionThresholds() { const shardsWasted = this.soulShardTracker.wasted; const shardsWastedPerMinute = (shardsWasted / this.owner.fightDuration) * 1000 * 60; return { actual: shardsWastedPerMinute, isGreaterThan: { minor: 5 / 10, // 5 shards in 10 minute fight average: 5 / 3, // 5 shards in 3 minute fight major: 10 / 3, // 10 shards in 3 minute fight }, style: 'number', // TODO: not sure about this yet }; } suggestions(when) { const shardsWasted = this.soulShardTracker.wasted; when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest('You are wasting Soul Shards. Try to use them and not let them cap and go to waste unless you\'re preparing for bursting adds etc.') .icon(SOUL_SHARD_ICON) .actual(`${shardsWasted} Soul Shards wasted (${actual.toFixed(2)} per minute)`) .recommended(`< ${recommended.toFixed(2)} Soul Shards per minute wasted are recommended`); }); } statistic() { const shardsWasted = this.soulShardTracker.wasted; return ( <StatisticBox icon={( <img src={WastedShardsIcon} alt="Wasted Soul Shards" /> )} value={shardsWasted} label="Wasted Soul Shards" /> ); } tab() { return { title: 'Soul Shard usage', url: 'soul-shards', render: () => ( <Panel> <ResourceBreakdown tracker={this.soulShardTracker} showSpenders /> </Panel> ), }; } statisticOrder = STATISTIC_ORDER.CORE(2); } export default SoulShardDetails;
node_modules/react-router/es6/IndexLink.js
TheeSweeney/ComplexReactReduxMiddlewareReview
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; }; import React from 'react'; import Link from './Link'; /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = React.createClass({ displayName: 'IndexLink', render: function render() { return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); export default IndexLink;
fields/components/columns/IdColumn.js
dvdcastro/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var IdColumn = React.createClass({ displayName: 'IdColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, list: React.PropTypes.object, }, renderValue () { const value = this.props.data.id; if (!value) return null; return ( <ItemsTableValue padded interior title={value} href={Keystone.adminPath + '/' + this.props.list.path + '/' + value} field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = IdColumn;
ajax/libs/forerunnerdb/1.3.602/fdb-core+views.min.js
hare1039/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":33,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":28,"./Shared":31}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":28,"./Shared":31}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b);var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L=this._metrics.create("find"),M=this.primaryKey(),N=this,O=!0,P={},Q=[],R=[],S=[],T={},U={};if(b instanceof Array||(b=this.options(b)),K=function(c){return N._match(c,a,b,"and",T)},L.start(),a){if(a instanceof Array){for(J=this,A=0;A<a.length;A++)J=J.subset(a[A],b&&b[A]?b[A]:{});return J.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(L.time("analyseQuery"),c=this._analyseQuery(N.decouple(a),b,L),L.time("analyseQuery"),L.data("analysis",c),c.hasJoin&&c.queriesJoin){for(L.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],P[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];L.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(L.data("index.potential",c.indexMatch),L.data("index.used",c.indexMatch[0].index),L.time("indexLookup"),e=c.indexMatch[0].lookup||[],L.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(O=!1)):L.flag("usedIndex",!1),O&&(e&&e.length?(d=e.length,L.time("tableScan: "+d),e=e.filter(K)):(d=this._data.length,L.time("tableScan: "+d),e=this._data.filter(K)),L.time("tableScan: "+d)),b.$orderBy&&(L.time("sort"),e=this.sort(b.$orderBy,e),L.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(U.page=b.$page,U.pages=Math.ceil(e.length/b.$limit),U.records=e.length,b.$page&&b.$limit>0&&(L.data("cursor",U),e.splice(0,b.$page*b.$limit))),b.$skip&&(U.skip=b.$skip,e.splice(0,b.$skip),L.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(U.limit=b.$limit,e.length=b.$limit,L.data("limit",b.$limit)),b.$decouple&&(L.time("decouple"),e=this.decouple(e),L.time("decouple"),L.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(x=k,l=P[k]?P[k]:this._db.collection(k),m=b.$join[f][k],y=0;y<e.length;y++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if(w=m[n],"$"===n.substr(0,1))switch(n){case"$where":if(!w.$query&&!w.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';w.$query&&(o=N._resolveDynamicQuery(w.$query,e[y])),w.$options&&(p=w.$options);break;case"$as":x=w;break;case"$multi":q=w;break;case"$require":r=w;break;case"$prefix":v=w}else o[n]=N._resolveDynamicQuery(w,e[y]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===x){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[y];for(D in t)t.hasOwnProperty(D)&&void 0===u[v+D]&&(u[v+D]=t[D])}else e[y][x]=q===!1?s[0]:s;else Q.push(e[y])}L.data("flag.join",!0)}if(Q.length){for(L.time("removalQueue"),A=0;A<Q.length;A++)z=e.indexOf(Q[A]),z>-1&&e.splice(z,1);L.time("removalQueue")}if(b.$transform){for(L.time("transform"),A=0;A<e.length;A++)e.splice(A,1,b.$transform(e[A]));L.time("transform"),L.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(L.time("transformOut"),e=this.transformOut(e),L.time("transformOut")),L.data("results",e.length)}else e=[];if(!b.$aggregate){L.time("scanFields");for(A in b)b.hasOwnProperty(A)&&0!==A.indexOf("$")&&(1===b[A]?R.push(A):0===b[A]&&S.push(A));if(L.time("scanFields"),R.length||S.length){for(L.data("flag.limitFields",!0),L.data("limitFields.on",R),L.data("limitFields.off",S),L.time("limitFields"),A=0;A<e.length;A++){H=e[A];for(B in H)H.hasOwnProperty(B)&&(R.length&&B!==M&&-1===R.indexOf(B)&&delete H[B],S.length&&S.indexOf(B)>-1&&delete H[B])}L.time("limitFields")}if(b.$elemMatch){L.data("flag.elemMatch",!0),L.time("projection-elemMatch");for(A in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length)for(C=0;C<F.length;C++)if(N._match(F[C],b.$elemMatch[A],b,"",{})){E.set(e[B],A,[F[C]]);break}L.time("projection-elemMatch")}if(b.$elemsMatch){L.data("flag.elemsMatch",!0),L.time("projection-elemsMatch");for(A in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length){for(G=[],C=0;C<F.length;C++)N._match(F[C],b.$elemsMatch[A],b,"",{})&&G.push(F[C]);E.set(e[B],A,G)}L.time("projection-elemsMatch")}}return b.$aggregate&&(L.data("flag.aggregate",!0),L.time("aggregate"),I=new h(b.$aggregate),e=I.value(e),L.time("aggregate")),L.stop(),e.__fdbOp=L,e.$cursor=U,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){ var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},p.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":31}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a]); },f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":28,"./Shared":31}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":31}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":26,"./Shared":31}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":27,"./Serialiser":30}],19:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":27}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":27}],25:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":28,"./Shared":31}],27:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature "'+d+'" for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":31}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":31}],30:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],31:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.602",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":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(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],33:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l=a("./Overload");d=a("./Shared");var m=function(a,b,c){this.init.apply(this,arguments)};m.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",m),d.mixin(m.prototype,"Mixin.Common"),d.mixin(m.prototype,"Mixin.ChainReactor"),d.mixin(m.prototype,"Mixin.Constants"),d.mixin(m.prototype,"Mixin.Triggers"),d.mixin(m.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(m.prototype,"state"),d.synthesize(m.prototype,"name"),d.synthesize(m.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),m.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},m.prototype.update=function(){this._from.update.apply(this._from,arguments)},m.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},m.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},m.prototype.find=function(a,b){return this.publicData().find(a,b)},m.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},m.prototype.findById=function(a,b){return this.publicData().findById(a,b)},m.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},m.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},m.prototype.data=function(){return this._privateData},m.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from), this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},m.prototype._collectionDropped=function(a){a&&delete this._from},m.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},m.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},m.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},m.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},m.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},m.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},m.prototype.primaryKey=function(){return this.publicData().primaryKey()},m.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(m.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),m.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},m.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},m.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},m.prototype.query=new l({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings}}),m.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},m.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},m.prototype.pageFirst=function(){return this.page(0)},m.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},m.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},m.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},m.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},m.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},m.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},m.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},m.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},m.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},m.prototype.privateData=function(){return this._privateData},m.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new m(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof m?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new m(a).db(this),b.emit("create",[b._view[a],"view",a]),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=m},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
ajax/libs/react-router/0.12.2/ReactRouter.min.js
dhenson02/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.ReactRouter=e(require("react")):t.ReactRouter=e(t.React)}(this,function(t){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){e.DefaultRoute=n(1),e.Link=n(2),e.NotFoundRoute=n(3),e.Redirect=n(4),e.Route=n(5),e.RouteHandler=n(6),e.HashLocation=n(7),e.HistoryLocation=n(8),e.RefreshLocation=n(9),e.StaticLocation=n(10),e.ImitateBrowserBehavior=n(11),e.ScrollToTopBehavior=n(12),e.History=n(13),e.Navigation=n(14),e.RouteHandlerMixin=n(15),e.State=n(16),e.createRoute=n(17).createRoute,e.createDefaultRoute=n(17).createDefaultRoute,e.createNotFoundRoute=n(17).createNotFoundRoute,e.createRedirect=n(17).createRedirect,e.createRoutesFromReactChildren=n(18),e.create=n(19),e.run=n(20)},function(t,e,n){var r=n(21),o=n(22),i=n(23),a=r.createClass({displayName:"DefaultRoute",mixins:[o],propTypes:{name:i.string,path:i.falsy,children:i.falsy,handler:i.func.isRequired}});t.exports=a},function(t,e,n){function r(t){return 0===t.button}function o(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}var i=n(21),a=n(35),u=n(36),s=n(14),c=n(16),h=n(23),f=n(17),p=i.createClass({displayName:"Link",mixins:[s,c],propTypes:{activeClassName:h.string.isRequired,to:h.oneOfType([h.string,h.instanceOf(f)]),params:h.object,query:h.object,activeStyle:h.object,onClick:h.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(t){var e,n=!0;this.props.onClick&&(e=this.props.onClick(t)),!o(t)&&r(t)&&((e===!1||t.defaultPrevented===!0)&&(n=!1),t.preventDefault(),n&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var t={};return this.props.className&&(t[this.props.className]=!0),this.getActiveState()&&(t[this.props.activeClassName]=!0),a(t)},getActiveState:function(){return this.isActive(this.props.to,this.props.params,this.props.query)},render:function(){var t=u({},this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return t.activeStyle&&this.getActiveState()&&(t.style=t.activeStyle),i.DOM.a(t,this.props.children)}});t.exports=p},function(t,e,n){var r=n(21),o=n(22),i=n(23),a=r.createClass({displayName:"NotFoundRoute",mixins:[o],propTypes:{name:i.string,path:i.falsy,children:i.falsy,handler:i.func.isRequired}});t.exports=a},function(t,e,n){var r=n(21),o=n(22),i=n(23),a=r.createClass({displayName:"Redirect",mixins:[o],propTypes:{path:i.string,from:i.string,to:i.string,handler:i.falsy}});t.exports=a},function(t,e,n){var r=n(21),o=n(22),i=n(23),a=n(6),u=r.createClass({displayName:"Route",mixins:[o],propTypes:{name:i.string,path:i.string,handler:i.func,ignoreScrollBehavior:i.bool},getDefaultProps:function(){return{handler:a}}});t.exports=u},function(t,e,n){var r=n(21),o=n(15),i=r.createClass({displayName:"RouteHandler",mixins:[o],render:function(){return this.createChildRouteHandler()}});t.exports=i},function(t,e,n){function r(){return decodeURI(window.location.href.split("#")[1]||"")}function o(){var t=r();return"/"===t.charAt(0)?!0:(p.replace("/"+t),!1)}function i(t){t===s.PUSH&&(c.length+=1);var e={path:r(),type:t};h.forEach(function(t){t(e)})}function a(){o()&&(i(u||s.POP),u=null)}var u,s=n(24),c=n(13),h=[],f=!1,p={addChangeListener:function(t){h.push(t),o(),f||(window.addEventListener?window.addEventListener("hashchange",a,!1):window.attachEvent("onhashchange",a),f=!0)},removeChangeListener:function(t){h=h.filter(function(e){return e!==t}),0===h.length&&(window.removeEventListener?window.removeEventListener("hashchange",a,!1):window.removeEvent("onhashchange",a),f=!1)},push:function(t){u=s.PUSH,window.location.hash=t},replace:function(t){u=s.REPLACE,window.location.replace(window.location.pathname+window.location.search+"#"+t)},pop:function(){u=s.POP,c.back()},getCurrentPath:r,toString:function(){return"<HashLocation>"}};t.exports=p},function(t,e,n){function r(){return decodeURI(window.location.pathname+window.location.search)}function o(t){var e={path:r(),type:t};s.forEach(function(t){t(e)})}function i(t){void 0!==t.state&&o(a.POP)}var a=n(24),u=n(13),s=[],c=!1,h={addChangeListener:function(t){s.push(t),c||(window.addEventListener?window.addEventListener("popstate",i,!1):window.attachEvent("onpopstate",i),c=!0)},removeChangeListener:function(t){s=s.filter(function(e){return e!==t}),0===s.length&&(window.addEventListener?window.removeEventListener("popstate",i,!1):window.removeEvent("onpopstate",i),c=!1)},push:function(t){window.history.pushState({path:t},"",t),u.length+=1,o(a.PUSH)},replace:function(t){window.history.replaceState({path:t},"",t),o(a.REPLACE)},pop:u.back,getCurrentPath:r,toString:function(){return"<HistoryLocation>"}};t.exports=h},function(t,e,n){var r=n(8),o=n(13),i={push:function(t){window.location=t},replace:function(t){window.location.replace(t)},pop:o.back,getCurrentPath:r.getCurrentPath,toString:function(){return"<RefreshLocation>"}};t.exports=i},function(t,e,n){function r(){i(!1,"You cannot modify a static location")}function o(t){this.path=t}var i=n(37);o.prototype.push=r,o.prototype.replace=r,o.prototype.pop=r,o.prototype.getCurrentPath=function(){return this.path},o.prototype.toString=function(){return'<StaticLocation path="'+this.path+'">'},t.exports=o},function(t,e,n){var r=n(24),o={updateScrollPosition:function(t,e){switch(e){case r.PUSH:case r.REPLACE:window.scrollTo(0,0);break;case r.POP:t?window.scrollTo(t.x,t.y):window.scrollTo(0,0)}}};t.exports=o},function(t){var e={updateScrollPosition:function(){window.scrollTo(0,0)}};t.exports=e},function(t,e,n){var r=n(37),o=n(38).canUseDOM,i={length:1,back:function(){r(o,"Cannot use History.back without a DOM"),i.length-=1,window.history.back()}};t.exports=i},function(t,e,n){var r=n(23),o={contextTypes:{makePath:r.func.isRequired,makeHref:r.func.isRequired,transitionTo:r.func.isRequired,replaceWith:r.func.isRequired,goBack:r.func.isRequired},makePath:function(t,e,n){return this.context.makePath(t,e,n)},makeHref:function(t,e,n){return this.context.makeHref(t,e,n)},transitionTo:function(t,e,n){this.context.transitionTo(t,e,n)},replaceWith:function(t,e,n){this.context.replaceWith(t,e,n)},goBack:function(){return this.context.goBack()}};t.exports=o},function(t,e,n){var r=n(21),o=n(36),i=n(23),a="__routeHandler__",u={contextTypes:{getRouteAtDepth:i.func.isRequired,setRouteComponentAtDepth:i.func.isRequired,routeHandlers:i.array.isRequired},childContextTypes:{routeHandlers:i.array.isRequired},getChildContext:function(){return{routeHandlers:this.context.routeHandlers.concat([this])}},componentDidMount:function(){this._updateRouteComponent(this.refs[a])},componentDidUpdate:function(){this._updateRouteComponent(this.refs[a])},componentWillUnmount:function(){this._updateRouteComponent(null)},_updateRouteComponent:function(t){this.context.setRouteComponentAtDepth(this.getRouteDepth(),t)},getRouteDepth:function(){return this.context.routeHandlers.length},createChildRouteHandler:function(t){var e=this.context.getRouteAtDepth(this.getRouteDepth());return e?r.createElement(e.handler,o({},t||this.props,{ref:a})):null}};t.exports=u},function(t,e,n){var r=n(23),o={contextTypes:{getCurrentPath:r.func.isRequired,getCurrentRoutes:r.func.isRequired,getCurrentPathname:r.func.isRequired,getCurrentParams:r.func.isRequired,getCurrentQuery:r.func.isRequired,isActive:r.func.isRequired},getPath:function(){return this.context.getCurrentPath()},getRoutes:function(){return this.context.getCurrentRoutes()},getPathname:function(){return this.context.getCurrentPathname()},getParams:function(){return this.context.getCurrentParams()},getQuery:function(){return this.context.getCurrentQuery()},isActive:function(t,e,n){return this.context.isActive(t,e,n)}};t.exports=o},function(t,e,n){function r(t,e,n,r,o,i,a,s){this.name=t,this.path=e,this.paramNames=u.extractParamNames(this.path),this.ignoreScrollBehavior=!!n,this.isDefault=!!r,this.isNotFound=!!o,this.onEnter=i,this.onLeave=a,this.handler=s}var o=n(36),i=n(37),a=n(39),u=n(25);r.prototype.appendChild=function(t){i(t instanceof r,"route.appendChild must use a valid Route"),this.childRoutes||(this.childRoutes=[]),this.childRoutes.push(t)},r.prototype.toString=function(){var t="<Route";return this.name&&(t+=' name="'+this.name+'"'),t+=' path="'+this.path+'">'};var s;r.createRoute=function(t,e){t=t||{},"string"==typeof t&&(t={path:t});var n=s;n?a(null==t.parentRoute||t.parentRoute===n,"You should not use parentRoute with createRoute inside another route's child callback; it is ignored"):n=t.parentRoute;var o=t.name,c=t.path||o;c?u.isAbsolute(c)?n&&i(0===n.paramNames.length,'You cannot nest path "%s" inside "%s"; the parent requires URL parameters',c,n.path):c=n?u.join(n.path,c):"/"+c:c=n?n.path:"/",t.isNotFound&&!/\*$/.test(c)&&(c+="*");var h=new r(o,c,t.ignoreScrollBehavior,t.isDefault,t.isNotFound,t.onEnter,t.onLeave,t.handler);if(n&&(h.isDefault?(i(null==n.defaultRoute,"%s may not have more than one default route",n),n.defaultRoute=h):h.isNotFound&&(i(null==n.notFoundRoute,"%s may not have more than one not found route",n),n.notFoundRoute=h),n.appendChild(h)),"function"==typeof e){var f=s;s=h,e.call(h,h),s=f}return h},r.createDefaultRoute=function(t){return r.createRoute(o({},t,{isDefault:!0}))},r.createNotFoundRoute=function(t){return r.createRoute(o({},t,{isNotFound:!0}))},r.createRedirect=function(t){return r.createRoute(o({},t,{path:t.path||t.from||"*",onEnter:function(e,n,r){e.redirect(t.to,t.params||n,t.query||r)}}))},t.exports=r},function(t,e,n){function r(t,e,n){t=t||"UnknownComponent";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r](n,r,t);o instanceof Error&&c(!1,o.message)}}function o(t){var e=s({},t),n=e.handler;return n&&(e.onEnter=n.willTransitionTo,e.onLeave=n.willTransitionFrom),e}function i(t){if(u.isValidElement(t)){var e=t.type,n=t.props;return e.propTypes&&r(e.displayName,e.propTypes,n),e===h?l.createDefaultRoute(o(n)):e===f?l.createNotFoundRoute(o(n)):e===p?l.createRedirect(o(n)):l.createRoute(o(n),function(){n.children&&a(n.children)})}}function a(t){var e=[];return u.Children.forEach(t,function(t){(t=i(t))&&e.push(t)}),e}var u=n(21),s=n(36),c=n(39),h=n(1).type,f=n(3).type,p=n(4).type,l=n(17);t.exports=a},function(t,e,n){function r(t,e){for(var n in e)if(e.hasOwnProperty(n)&&t[n]!==e[n])return!1;return!0}function o(t,e,n,o,i,a){return t.some(function(t){if(t!==e)return!1;for(var u,s=e.paramNames,c=0,h=s.length;h>c;++c)if(u=s[c],o[u]!==n[u])return!1;return r(i,a)&&r(a,i)})}function i(t,e){for(var n,r=0,o=t.length;o>r;++r)n=t[r],n.name&&(c(null==e[n.name],'You may not have more than one route named "%s"',n.name),e[n.name]=n),n.childRoutes&&i(n.childRoutes,e)}function a(t){t=t||{},x(t)&&(t={routes:t});var e=[],n=t.location||T,r=t.scrollBehavior||q,a={},p={},D=null,N=null;"string"==typeof n&&(n=new y(n)),n instanceof y?s(!h||!1,"You should not use a static location in a DOM environment because the router will not be kept in sync with the current URL"):c(h||n.needsDOM===!1,"You cannot use %s without a DOM",n),n!==d||E()||(n=m);var H=u.createClass({displayName:"Router",statics:{isRunning:!1,cancelPendingTransition:function(){D&&(D.cancel(),D=null)},clearAllRoutes:function(){this.cancelPendingTransition(),this.namedRoutes={},this.routes=[]},addRoutes:function(t){x(t)&&(t=w(t)),i(t,this.namedRoutes),this.routes.push.apply(this.routes,t)},replaceRoutes:function(t){this.clearAllRoutes(),this.addRoutes(t),this.refresh()},match:function(t){return L.findMatchForPath(this.routes,t)},makePath:function(t,e,n){var r;if(S.isAbsolute(t))r=t;else{var o=t instanceof k?t:this.namedRoutes[t];c(o instanceof k,'Cannot find a route named "%s"',t),r=o.path}return S.withQuery(S.injectParams(r,e),n)},makeHref:function(t,e,r){var o=this.makePath(t,e,r);return n===l?"#"+o:o},transitionTo:function(t,e,r){var o=this.makePath(t,e,r);D?n.replace(o):n.push(o)},replaceWith:function(t,e,r){n.replace(this.makePath(t,e,r))},goBack:function(){return A.length>1||n===m?(n.pop(),!0):(s(!1,"goBack() was ignored because there is no router history"),!1)},handleAbort:t.onAbort||function(t){if(n instanceof y)throw new Error("Unhandled aborted transition! Reason: "+t);t instanceof O||(t instanceof b?n.replace(this.makePath(t.to,t.params,t.query)):n.pop())},handleError:t.onError||function(t){throw t},handleLocationChange:function(t){this.dispatch(t.path,t.type)},dispatch:function(t,n){this.cancelPendingTransition();var r=a.path,i=null==n;if(r!==t||i){r&&n===f.PUSH&&this.recordScrollPosition(r);var u=this.match(t);s(null!=u,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your routes',t,t),null==u&&(u={});var c,h,p=a.routes||[],l=a.params||{},d=a.query||{},m=u.routes||[],y=u.params||{},g=u.query||{};p.length?(c=p.filter(function(t){return!o(m,t,l,y,d,g)}),h=m.filter(function(t){return!o(p,t,l,y,d,g)})):(c=[],h=m);var v=new C(t,this.replaceWith.bind(this,t));D=v;var R=e.slice(p.length-c.length);C.from(v,c,R,function(e){return e||v.abortReason?N.call(H,e,v):void C.to(v,h,y,g,function(e){N.call(H,e,v,{path:t,action:n,pathname:u.pathname,routes:m,params:y,query:g})})})}},run:function(t){c(!this.isRunning,"Router is already running"),N=function(e,n,r){e&&H.handleError(e),D===n&&(D=null,n.abortReason?H.handleAbort(n.abortReason):t.call(this,this,p=r))},n instanceof y||(n.addChangeListener&&n.addChangeListener(H.handleLocationChange),this.isRunning=!0),this.refresh()},refresh:function(){H.dispatch(n.getCurrentPath(),null)},stop:function(){this.cancelPendingTransition(),n.removeChangeListener&&n.removeChangeListener(H.handleLocationChange),this.isRunning=!1},getScrollBehavior:function(){return r}},mixins:[g,R,v],propTypes:{children:P.falsy},childContextTypes:{getRouteAtDepth:u.PropTypes.func.isRequired,setRouteComponentAtDepth:u.PropTypes.func.isRequired,routeHandlers:u.PropTypes.array.isRequired},getChildContext:function(){return{getRouteAtDepth:this.getRouteAtDepth,setRouteComponentAtDepth:this.setRouteComponentAtDepth,routeHandlers:[this]}},getInitialState:function(){return a=p},componentWillReceiveProps:function(){this.setState(a=p)},componentWillUnmount:function(){H.stop()},getLocation:function(){return n},getRouteAtDepth:function(t){var e=this.state.routes;return e&&e[t]},setRouteComponentAtDepth:function(t,n){e[t]=n},render:function(){var t=this.getRouteAtDepth(0);return t?u.createElement(t.handler,this.props):null}});return H.clearAllRoutes(),t.routes&&H.addRoutes(t.routes),H}var u=n(21),s=n(39),c=n(37),h=n(38).canUseDOM,f=n(24),p=n(11),l=n(7),d=n(8),m=n(9),y=n(10),g=n(26),v=n(27),R=n(28),w=n(18),x=n(29),C=n(30),P=n(23),b=n(31),A=n(13),O=n(32),L=n(33),k=n(17),E=n(34),S=n(25),T=h?l:"/",q=h?p:null;t.exports=a},function(t,e,n){function r(t,e,n){"function"==typeof e&&(n=e,e=null);var r=o({routes:t,location:e});return r.run(n),r}var o=n(19);t.exports=r},function(e){e.exports=t},function(t,e,n){function r(t,e,n){for(var r in e)if(e.hasOwnProperty(r)){var i=e[r](n,r,t);i instanceof Error&&o(!1,i.message)}}var o=n(39),i=n(37),a={statics:{validateProps:function(t){r(this.displayName,this.propTypes,t)}},render:function(){i(!1,"%s elements are for router configuration only and should not be rendered",this.constructor.displayName)}};t.exports=a},function(t,e,n){var r=n(36),o=n(21).PropTypes,i=r({falsy:function(t,e,n){return t[e]?new Error("<"+n+'> may not have a "'+e+'" prop'):void 0}},o);t.exports=i},function(t){var e={PUSH:"push",REPLACE:"replace",POP:"pop"};t.exports=e},function(t,e,n){function r(t){if(!(t in f)){var e=[],n=t.replace(u,function(t,n){return n?(e.push(n),"([^/?#]+)"):"*"===t?(e.push("splat"),"(.*?)"):"\\"+t});f[t]={matcher:new RegExp("^"+n+"$","i"),paramNames:e}}return f[t]}var o=n(37),i=n(42).merge,a=n(41),u=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,s=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,c=/\/\/\?|\/\?\/|\/\?/g,h=/\?(.+)/,f={},p={isAbsolute:function(t){return"/"===t.charAt(0)},join:function(t,e){return t.replace(/\/*$/,"/")+e},extractParamNames:function(t){return r(t).paramNames},extractParams:function(t,e){var n=r(t),o=n.matcher,i=n.paramNames,a=e.match(o);if(!a)return null;var u={};return i.forEach(function(t,e){u[t]=a[e+1]}),u},injectParams:function(t,e){e=e||{};var n=0;return t.replace(s,function(r,i){if(i=i||"splat","?"===i.slice(-1)){if(i=i.slice(0,-1),null==e[i])return""}else o(null!=e[i],'Missing "%s" parameter for path "%s"',i,t);var a;return"splat"===i&&Array.isArray(e[i])?(a=e[i][n++],o(null!=a,'Missing splat # %s for path "%s"',n,t)):a=e[i],a}).replace(c,"/")},extractQuery:function(t){var e=t.match(h);return e&&a.parse(e[1])},withoutQuery:function(t){return t.replace(h,"")},withQuery:function(t,e){var n=p.extractQuery(t);n&&(e=e?i(n,e):n);var r=a.stringify(e,{indices:!1});return r?p.withoutQuery(t)+"?"+r:t}};t.exports=p},function(t,e,n){var r=n(23),o={childContextTypes:{makePath:r.func.isRequired,makeHref:r.func.isRequired,transitionTo:r.func.isRequired,replaceWith:r.func.isRequired,goBack:r.func.isRequired},getChildContext:function(){return{makePath:this.constructor.makePath.bind(this.constructor),makeHref:this.constructor.makeHref.bind(this.constructor),transitionTo:this.constructor.transitionTo.bind(this.constructor),replaceWith:this.constructor.replaceWith.bind(this.constructor),goBack:this.constructor.goBack.bind(this.constructor)}}};t.exports=o},function(t,e,n){function r(t,e){if(!e)return!0;if(t.pathname===e.pathname)return!1;var n=t.routes,r=e.routes,o=n.filter(function(t){return-1!==r.indexOf(t)});return!o.some(function(t){return t.ignoreScrollBehavior})}var o=n(37),i=n(38).canUseDOM,a=n(40),u={statics:{recordScrollPosition:function(t){this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[t]=a()},getScrollPosition:function(t){return this.scrollHistory||(this.scrollHistory={}),this.scrollHistory[t]||null}},componentWillMount:function(){o(null==this.constructor.getScrollBehavior()||i,"Cannot use scroll behavior without a DOM")},componentDidMount:function(){this._updateScroll()},componentDidUpdate:function(t,e){this._updateScroll(e)},_updateScroll:function(t){if(r(this.state,t)){var e=this.constructor.getScrollBehavior();e&&e.updateScrollPosition(this.constructor.getScrollPosition(this.state.path),this.state.action)}}};t.exports=u},function(t,e,n){function r(t,e){return t.some(function(t){return t.name===e})}function o(t,e){for(var n in e)if(String(t[n])!==String(e[n]))return!1;return!0}function i(t,e){for(var n in e)if(String(t[n])!==String(e[n]))return!1;return!0}var a=n(36),u=n(23),s=n(25),c={getCurrentPath:function(){return this.state.path},getCurrentRoutes:function(){return this.state.routes.slice(0)},getCurrentPathname:function(){return this.state.pathname},getCurrentParams:function(){return a({},this.state.params)},getCurrentQuery:function(){return a({},this.state.query)},isActive:function(t,e,n){return s.isAbsolute(t)?t===this.state.path:r(this.state.routes,t)&&o(this.state.params,e)&&(null==n||i(this.state.query,n))},childContextTypes:{getCurrentPath:u.func.isRequired,getCurrentRoutes:u.func.isRequired,getCurrentPathname:u.func.isRequired,getCurrentParams:u.func.isRequired,getCurrentQuery:u.func.isRequired,isActive:u.func.isRequired},getChildContext:function(){return{getCurrentPath:this.getCurrentPath,getCurrentRoutes:this.getCurrentRoutes,getCurrentPathname:this.getCurrentPathname,getCurrentParams:this.getCurrentParams,getCurrentQuery:this.getCurrentQuery,isActive:this.isActive}}};t.exports=c},function(t,e,n){function r(t){return null==t||i.isValidElement(t)}function o(t){return r(t)||Array.isArray(t)&&t.every(r)}var i=n(21);t.exports=o},function(t,e,n){function r(t,e){this.path=t,this.abortReason=null,this.retry=e.bind(this)}var o=n(32),i=n(31);r.prototype.abort=function(t){null==this.abortReason&&(this.abortReason=t||"ABORT")},r.prototype.redirect=function(t,e,n){this.abort(new i(t,e,n))},r.prototype.cancel=function(){this.abort(new o)},r.from=function(t,e,n,r){e.reduce(function(e,r,o){return function(i){if(i||t.abortReason)e(i);else if(r.onLeave)try{r.onLeave(t,n[o],e),r.onLeave.length<3&&e()}catch(a){e(a)}else e()}},r)()},r.to=function(t,e,n,r,o){e.reduceRight(function(e,o){return function(i){if(i||t.abortReason)e(i);else if(o.onEnter)try{o.onEnter(t,n,r,e),o.onEnter.length<4&&e()}catch(a){e(a)}else e()}},o)()},t.exports=r},function(t){function e(t,e,n){this.to=t,this.params=e,this.query=n}t.exports=e},function(t){function e(){}t.exports=e},function(t,e,n){function r(t,e,n,r){this.pathname=t,this.params=e,this.query=n,this.routes=r}function o(t,e,n){var a=t.childRoutes;if(a)for(var u,s,c=0,h=a.length;h>c;++c)if(s=a[c],!s.isDefault&&!s.isNotFound&&(u=o(s,e,n)))return u.routes.unshift(t),u;var f=t.defaultRoute;if(f&&(l=i.extractParams(f.path,e)))return new r(e,l,n,[t,f]);var p=t.notFoundRoute;if(p&&(l=i.extractParams(p.path,e)))return new r(e,l,n,[t,p]);var l=i.extractParams(t.path,e);return l?new r(e,l,n,[t]):null}var i=n(25);r.findMatchForPath=function(t,e){for(var n=i.withoutQuery(e),r=i.extractQuery(e),a=null,u=0,s=t.length;null==a&&s>u;++u)a=o(t[u],n,r);return a},t.exports=r},function(t){function e(){/*! taken from modernizr * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/rackt/react-router/issues/586 */ var t=navigator.userAgent;return-1===t.indexOf("Android 2.")&&-1===t.indexOf("Android 4.0")||-1===t.indexOf("Mobile Safari")||-1!==t.indexOf("Chrome")||-1!==t.indexOf("Windows Phone")?window.history&&"pushState"in window.history:!1}t.exports=e},function(t){function e(t){return"object"==typeof t?Object.keys(t).filter(function(e){return t[e]}).join(" "):Array.prototype.join.call(arguments," ")}t.exports=e},function(t){function e(t){if(null==t)throw new TypeError("Object.assign target cannot be null or undefined");for(var e=Object(t),n=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var o=arguments[r];if(null!=o){var i=Object(o);for(var a in i)n.call(i,a)&&(e[a]=i[a])}}return e}t.exports=e},function(t){"use strict";var e=function(t,e,n,r,o,i,a,u){if(!t){var s;if(void 0===e)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],h=0;s=new Error("Invariant Violation: "+e.replace(/%s/g,function(){return c[h++]}))}throw s.framesToPop=1,s}};t.exports=e},function(t){"use strict";var e=!("undefined"==typeof window||!window.document||!window.document.createElement),n={canUseDOM:e,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:e&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:e&&!!window.screen,isInWorker:!e};t.exports=n},function(t,e,n){"use strict";var r=n(43),o=r;t.exports=o},function(t,e,n){function r(){return o(i,"Cannot get current scroll position without a DOM"),{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}}var o=n(37),i=n(38).canUseDOM;t.exports=r},function(t,e,n){t.exports=n(44)},function(t,e){e.arrayToObject=function(t){for(var e={},n=0,r=t.length;r>n;++n)"undefined"!=typeof t[n]&&(e[n]=t[n]);return e},e.merge=function(t,n){if(!n)return t;if("object"!=typeof n)return Array.isArray(t)?t.push(n):t[n]=!0,t;if("object"!=typeof t)return t=[t].concat(n);Array.isArray(t)&&!Array.isArray(n)&&(t=e.arrayToObject(t));for(var r=Object.keys(n),o=0,i=r.length;i>o;++o){var a=r[o],u=n[a];t[a]=t[a]?e.merge(t[a],u):u}return t},e.decode=function(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch(e){return t}},e.compact=function(t,n){if("object"!=typeof t||null===t)return t;n=n||[];var r=n.indexOf(t);if(-1!==r)return n[r];if(n.push(t),Array.isArray(t)){for(var o=[],i=0,a=t.length;a>i;++i)"undefined"!=typeof t[i]&&o.push(t[i]);return o}var u=Object.keys(t);for(i=0,a=u.length;a>i;++i){var s=u[i];t[s]=e.compact(t[s],n)}return t},e.isRegExp=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},e.isBuffer=function(t){return null===t||"undefined"==typeof t?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}},function(t){function e(t){return function(){return t}}function n(){}n.thatReturns=e,n.thatReturnsFalse=e(!1),n.thatReturnsTrue=e(!0),n.thatReturnsNull=e(null),n.thatReturnsThis=function(){return this},n.thatReturnsArgument=function(t){return t},t.exports=n},function(t,e,n){var r=n(45),o=n(46);t.exports={stringify:r,parse:o}},function(t,e,n){var r=n(42),o={delimiter:"&",indices:!0};o.stringify=function(t,e,n){if(r.isBuffer(t)?t=t.toString():t instanceof Date?t=t.toISOString():null===t&&(t=""),"string"==typeof t||"number"==typeof t||"boolean"==typeof t)return[encodeURIComponent(e)+"="+encodeURIComponent(t)];var i=[];if("undefined"==typeof t)return i;for(var a=Object.keys(t),u=0,s=a.length;s>u;++u){var c=a[u];i=i.concat(!n.indices&&Array.isArray(t)?o.stringify(t[c],e,n):o.stringify(t[c],e+"["+c+"]",n))}return i},t.exports=function(t,e){e=e||{};var n="undefined"==typeof e.delimiter?o.delimiter:e.delimiter;e.indices="boolean"==typeof e.indices?e.indices:o.indices;var r=[];if("object"!=typeof t||null===t)return"";for(var i=Object.keys(t),a=0,u=i.length;u>a;++a){var s=i[a];r=r.concat(o.stringify(t[s],s,e))}return r.join(n)}},function(t,e,n){var r=n(42),o={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};o.parseValues=function(t,e){for(var n={},o=t.split(e.delimiter,1/0===e.parameterLimit?void 0:e.parameterLimit),i=0,a=o.length;a>i;++i){var u=o[i],s=-1===u.indexOf("]=")?u.indexOf("="):u.indexOf("]=")+1;if(-1===s)n[r.decode(u)]="";else{var c=r.decode(u.slice(0,s)),h=r.decode(u.slice(s+1));n[c]=n.hasOwnProperty(c)?[].concat(n[c]).concat(h):h}}return n},o.parseObject=function(t,e,n){if(!t.length)return e;var r=t.shift(),i={};if("[]"===r)i=[],i=i.concat(o.parseObject(t,e,n));else{var a="["===r[0]&&"]"===r[r.length-1]?r.slice(1,r.length-1):r,u=parseInt(a,10),s=""+u;!isNaN(u)&&r!==a&&s===a&&u>=0&&u<=n.arrayLimit?(i=[],i[u]=o.parseObject(t,e,n)):i[a]=o.parseObject(t,e,n)}return i},o.parseKeys=function(t,e,n){if(t){var r=/^([^\[\]]*)/,i=/(\[[^\[\]]*\])/g,a=r.exec(t);if(!Object.prototype.hasOwnProperty(a[1])){var u=[];a[1]&&u.push(a[1]);for(var s=0;null!==(a=i.exec(t))&&s<n.depth;)++s,Object.prototype.hasOwnProperty(a[1].replace(/\[|\]/g,""))||u.push(a[1]);return a&&u.push("["+t.slice(a.index)+"]"),o.parseObject(u,e,n)}}},t.exports=function(t,e){if(""===t||null===t||"undefined"==typeof t)return{};e=e||{},e.delimiter="string"==typeof e.delimiter||r.isRegExp(e.delimiter)?e.delimiter:o.delimiter,e.depth="number"==typeof e.depth?e.depth:o.depth,e.arrayLimit="number"==typeof e.arrayLimit?e.arrayLimit:o.arrayLimit,e.parameterLimit="number"==typeof e.parameterLimit?e.parameterLimit:o.parameterLimit;for(var n="string"==typeof t?o.parseValues(t,e):t,i={},a=Object.keys(n),u=0,s=a.length;s>u;++u){var c=a[u],h=o.parseKeys(c,n[c],e);i=r.merge(i,h)}return r.compact(i)}}])});
ajax/libs/yasr/2.2.1/yasr.bundled.min.js
JacquesMarais/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASR=e()}}(function(){var e;return function t(e,n,r){function i(a,s){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};e[a][0].call(c.exports,function(t){var n=e[a][1][t];return i(n?n:t)},c,c.exports,t,e,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(e,t){"use strict";var n=e("jquery"),r=e("yasgui-utils");console=console||{log:function(){}};var i=t.exports=function(t,s,l){var u={};u.options=n.extend(!0,{},i.defaults,s),u.container=n("<div class='yasr'></div>").appendTo(t),u.header=n("<div class='yasr_header'></div>").appendTo(u.container),u.resultsContainer=n("<div class='yasr_results'></div>").appendTo(u.container),u.plugins={};for(var c in i.plugins)u.plugins[c]=new i.plugins[c](u);if(u.draw=function(e){if(!u.results)return!1;if(e||(e=u.options.output),e in u.plugins&&u.plugins[e].canHandleResults(u))return n(u.resultsContainer).empty(),u.plugins[e].draw(),!0;var t=null,r=-1;for(var i in u.plugins)if(u.plugins[i].canHandleResults(u)){var o=u.plugins[i].getPriority;"function"==typeof o&&(o=o(u)),null!=o&&void 0!=o&&o>r&&(r=o,t=i)}return t?(n(u.resultsContainer).empty(),u.plugins[t].draw(),!0):!1},u.somethingDrawn=function(){return!u.resultsContainer.is(":empty")},u.setResponse=function(t){try{u.results=e("./parsers/wrapper.js")(t)}catch(n){u.results=n}if(u.draw(),u.options.persistency&&u.options.persistency.results&&u.results.getOriginalResponseAsString&&u.results.getOriginalResponseAsString().length<u.options.persistency.results.maxSize){var i="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);r.storage.set(i,u.results.getOriginalResponse(),"month")}},u.options.persistency&&u.options.persistency.outputSelector){var f="string"==typeof u.options.persistency.outputSelector?u.options.persistency.outputSelector:u.options.persistency.outputSelector(u);if(f){var d=r.storage.get(f);d&&(u.options.output=d)}}if(!l&&u.options.persistency&&u.options.persistency.results){var f="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);l=r.storage.get(f)}return a(u),l&&u.setResponse(l),o(u),u},o=function(e){var t=e.header.find(".yasr_downloadIcon");t.removeAttr("title");var n=e.plugins[e.options.output];if(n){var r=n.getDownloadInfo?n.getDownloadInfo():null;r?(r.buttonTitle&&t.attr(r.buttonTitle),t.prop("disabled",!1),t.find("path").each(function(){this.style.fill="black"})):(t.prop("disabled",!0).prop("title","Download not supported for this result representation"),t.find("path").each(function(){this.style.fill="gray"}))}},a=function(t){var i=function(){var e=n('<div class="yasr_btnGroup"></div>');n.each(t.plugins,function(i,a){if(!a.hideFromSelection){var s=a.name||i,l=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){if(e.find("button.selected").removeClass("selected"),n(this).addClass("selected"),t.options.output=i,t.options.persistency&&t.options.persistency.outputSelector){var a="string"==typeof t.options.persistency.outputSelector?t.options.persistency.outputSelector:t.options.persistency.outputSelector(t);r.storage.set(a,t.options.output,"month")}t.draw(),o(t)}).appendTo(e);t.options.output==i&&l.addClass("selected")}}),e.children().length>1&&t.header.append(e)},a=function(){var r=function(e,t){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([e],{type:t});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download,{width:"15px",height:"15px"})).click(function(){var e=t.plugins[t.options.output];if(e&&e.getDownloadInfo){var i=e.getDownloadInfo(),o=r(i.getContent(),i.contentType?i.contentType:"text/plain"),a=n("<a></a>");a.attr("href",o),a.attr("download",i.filename),a.get(0).click()}});t.header.append(i)};t.options.drawOutputSelector&&i(),t.options.drawDownloadIcon&&a()};i.plugins={},i.registerOutput=function(e,t){i.plugins[e]=t},i.registerOutput("boolean",e("./boolean.js")),i.registerOutput("table",e("./table.js")),i.registerOutput("rawResponse",e("./rawResponse.js")),i.registerOutput("error",e("./error.js")),i.defaults=e("./defaults.js"),i.version={YASR:e("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":e("yasgui-utils").version}},{"../package.json":14,"./boolean.js":16,"./defaults.js":17,"./error.js":18,"./imgs.js":19,"./parsers/wrapper.js":24,"./rawResponse.js":26,"./table.js":27,jquery:8,"yasgui-utils":11}],2:[function(t,n,r){!function(n,i,o){!function(n){"use strict";"function"==typeof e&&e.amd?e("datatables",["jquery"],n):"object"==typeof r?n(t("jquery")):jQuery&&!jQuery.fn.dataTable&&n(jQuery)}(function(e){"use strict";function t(n){var r,i,o="a aa ai ao as b fn i m o s ",a={};e.each(n,function(e){r=e.match(/^([^A-Z]+?)([A-Z])/),r&&-1!==o.indexOf(r[1]+" ")&&(i=e.replace(r[0],r[2].toLowerCase()),a[i]=e,"o"===r[1]&&t(n[e]))}),n._hungarianMap=a}function r(n,i,a){n._hungarianMap||t(n);var s;e.each(i,function(t){s=n._hungarianMap[t],s===o||!a&&i[s]!==o||("o"===s.charAt(0)?(i[s]||(i[s]={}),e.extend(!0,i[s],i[t]),r(n[s],i[s],a)):i[s]=i[t])})}function a(e){var t=$t.defaults.oLanguage,n=e.sZeroRecords;!e.sEmptyTable&&n&&"No data available in table"===t.sEmptyTable&&Rt(e,e,"sZeroRecords","sEmptyTable"),!e.sLoadingRecords&&n&&"Loading..."===t.sLoadingRecords&&Rt(e,e,"sZeroRecords","sLoadingRecords"),e.sInfoThousands&&(e.sThousands=e.sInfoThousands);var r=e.sDecimal;r&&Xt(r)}function s(e){yn(e,"ordering","bSort"),yn(e,"orderMulti","bSortMulti"),yn(e,"orderClasses","bSortClasses"),yn(e,"orderCellsTop","bSortCellsTop"),yn(e,"order","aaSorting"),yn(e,"orderFixed","aaSortingFixed"),yn(e,"paging","bPaginate"),yn(e,"pagingType","sPaginationType"),yn(e,"pageLength","iDisplayLength"),yn(e,"searching","bFilter");var t=e.aoSearchCols;if(t)for(var n=0,i=t.length;i>n;n++)t[n]&&r($t.models.oSearch,t[n])}function l(e){yn(e,"orderable","bSortable"),yn(e,"orderData","aDataSort"),yn(e,"orderSequence","asSorting"),yn(e,"orderDataType","sortDataType")}function u(t){var n=t.oBrowser,r=e("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(e("<div/>").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(e('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),i=r.find(".test");n.bScrollOversize=100===i[0].offsetWidth,n.bScrollbarLeft=1!==i.offset().left,r.remove()}function c(e,t,n,r,i,a){var s,l=r,u=!1;for(n!==o&&(s=n,u=!0);l!==i;)e.hasOwnProperty(l)&&(s=u?t(s,e[l],l,e):e[l],u=!0,l+=a);return s}function f(t,n){var r=$t.defaults.column,o=t.aoColumns.length,a=e.extend({},$t.models.oColumn,r,{nTh:n?n:i.createElement("th"),sTitle:r.sTitle?r.sTitle:n?n.innerHTML:"",aDataSort:r.aDataSort?r.aDataSort:[o],mData:r.mData?r.mData:o,idx:o});t.aoColumns.push(a);var s=t.aoPreSearchCols;s[o]=e.extend({},$t.models.oSearch,s[o]),d(t,o,null)}function d(t,n,i){var a=t.aoColumns[n],s=t.oClasses,u=e(a.nTh);if(!a.sWidthOrig){a.sWidthOrig=u.attr("width")||null;var c=(u.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);c&&(a.sWidthOrig=c[1])}i!==o&&null!==i&&(l(i),r($t.defaults.column,i),i.mDataProp===o||i.mData||(i.mData=i.mDataProp),i.sType&&(a._sManualType=i.sType),i.className&&!i.sClass&&(i.sClass=i.className),e.extend(a,i),Rt(a,i,"sWidth","sWidthOrig"),"number"==typeof i.iDataSort&&(a.aDataSort=[i.iDataSort]),Rt(a,i,"aDataSort"));var f=a.mData,d=L(f),h=a.mRender?L(a.mRender):null,p=function(e){return"string"==typeof e&&-1!==e.indexOf("@")};a._bAttrSrc=e.isPlainObject(f)&&(p(f.sort)||p(f.type)||p(f.filter)),a.fnGetData=function(e,t,n){var r=d(e,t,o,n);return h&&t?h(r,t,e,n):r},a.fnSetData=function(e,t,n){return A(f)(e,t,n)},t.oFeatures.bSort||(a.bSortable=!1,u.addClass(s.sSortableNone));var g=-1!==e.inArray("asc",a.asSorting),m=-1!==e.inArray("desc",a.asSorting);a.bSortable&&(g||m)?g&&!m?(a.sSortingClass=s.sSortableAsc,a.sSortingClassJUI=s.sSortJUIAscAllowed):!g&&m?(a.sSortingClass=s.sSortableDesc,a.sSortingClassJUI=s.sSortJUIDescAllowed):(a.sSortingClass=s.sSortable,a.sSortingClassJUI=s.sSortJUI):(a.sSortingClass=s.sSortableNone,a.sSortingClassJUI="")}function h(e){if(e.oFeatures.bAutoWidth!==!1){var t=e.aoColumns;yt(e);for(var n=0,r=t.length;r>n;n++)t[n].nTh.style.width=t[n].sWidth}var i=e.oScroll;(""!==i.sY||""!==i.sX)&&mt(e),zt(e,null,"column-sizing",[e])}function p(e,t){var n=v(e,"bVisible");return"number"==typeof n[t]?n[t]:null}function g(t,n){var r=v(t,"bVisible"),i=e.inArray(n,r);return-1!==i?i:null}function m(e){return v(e,"bVisible").length}function v(t,n){var r=[];return e.map(t.aoColumns,function(e,t){e[n]&&r.push(t)}),r}function y(e){var t,n,r,i,a,s,l,u,c,f=e.aoColumns,d=e.aoData,h=$t.ext.type.detect;for(t=0,n=f.length;n>t;t++)if(l=f[t],c=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){for(r=0,i=h.length;i>r;r++){for(a=0,s=d.length;s>a&&(c[a]===o&&(c[a]=T(e,a,t,"type")),u=h[r](c[a],e),u&&"html"!==u);a++);if(u){l.sType=u;break}}l.sType||(l.sType="string")}}function b(t,n,r,i){var a,s,l,u,c,d,h,p=t.aoColumns;if(n)for(a=n.length-1;a>=0;a--){h=n[a];var g=h.targets!==o?h.targets:h.aTargets;for(e.isArray(g)||(g=[g]),l=0,u=g.length;u>l;l++)if("number"==typeof g[l]&&g[l]>=0){for(;p.length<=g[l];)f(t);i(g[l],h)}else if("number"==typeof g[l]&&g[l]<0)i(p.length+g[l],h);else if("string"==typeof g[l])for(c=0,d=p.length;d>c;c++)("_all"==g[l]||e(p[c].nTh).hasClass(g[l]))&&i(c,h)}if(r)for(a=0,s=r.length;s>a;a++)i(a,r[a])}function x(t,n,r,i){var o=t.aoData.length,a=e.extend(!0,{},$t.models.oRow,{src:r?"dom":"data"});a._aData=n,t.aoData.push(a);for(var s=t.aoColumns,l=0,u=s.length;u>l;l++)r&&D(t,o,l,T(t,o,l)),s[l].sType=null;return t.aiDisplayMaster.push(o),(r||!t.oFeatures.bDeferRender)&&I(t,o,r,i),o}function w(t,n){var r;return n instanceof e||(n=e(n)),n.map(function(e,n){return r=j(t,n),x(t,r.data,n,r.cells)})}function S(e,t){return t._DT_RowIndex!==o?t._DT_RowIndex:null}function C(t,n,r){return e.inArray(r,t.aoData[n].anCells)}function T(e,t,n,r){var i=e.iDraw,a=e.aoColumns[n],s=e.aoData[t]._aData,l=a.sDefaultContent,u=a.fnGetData(s,r,{settings:e,row:t,col:n});if(u===o)return e.iDrawError!=i&&null===l&&(Ot(e,0,"Requested unknown parameter "+("function"==typeof a.mData?"{function}":"'"+a.mData+"'")+" for row "+t,4),e.iDrawError=i),l;if(u!==s&&null!==u||null===l){if("function"==typeof u)return u.call(s)}else u=l;return null===u&&"display"==r?"":u}function D(e,t,n,r){var i=e.aoColumns[n],o=e.aoData[t]._aData;i.fnSetData(o,r,{settings:e,row:t,col:n})}function k(t){return e.map(t.match(/(\\.|[^\.])+/g),function(e){return e.replace(/\\./g,".")})}function L(t){if(e.isPlainObject(t)){var n={};return e.each(t,function(e,t){t&&(n[e]=L(t))}),function(e,t,r,i){var a=n[t]||n._;return a!==o?a(e,t,r,i):e}}if(null===t)return function(e){return e};if("function"==typeof t)return function(e,n,r,i){return t(e,n,r,i)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e){return e[t]};var r=function(e,t,n){var i,a,s,l;if(""!==n)for(var u=k(n),c=0,f=u.length;f>c;c++){if(i=u[c].match(bn),a=u[c].match(xn),i){u[c]=u[c].replace(bn,""),""!==u[c]&&(e=e[u[c]]),s=[],u.splice(0,c+1),l=u.join(".");for(var d=0,h=e.length;h>d;d++)s.push(r(e[d],t,l));var p=i[0].substring(1,i[0].length-1);e=""===p?s:s.join(p);break}if(a)u[c]=u[c].replace(xn,""),e=e[u[c]]();else{if(null===e||e[u[c]]===o)return o;e=e[u[c]]}}return e};return function(e,n){return r(e,n,t)}}function A(t){if(e.isPlainObject(t))return A(t._);if(null===t)return function(){};if("function"==typeof t)return function(e,n,r){t(e,"set",n,r)};if("string"!=typeof t||-1===t.indexOf(".")&&-1===t.indexOf("[")&&-1===t.indexOf("("))return function(e,n){e[t]=n};var n=function(e,t,r){for(var i,a,s,l,u,c=k(r),f=c[c.length-1],d=0,h=c.length-1;h>d;d++){if(a=c[d].match(bn),s=c[d].match(xn),a){c[d]=c[d].replace(bn,""),e[c[d]]=[],i=c.slice(),i.splice(0,d+1),u=i.join(".");for(var p=0,g=t.length;g>p;p++)l={},n(l,t[p],u),e[c[d]].push(l);return}s&&(c[d]=c[d].replace(xn,""),e=e[c[d]](t)),(null===e[c[d]]||e[c[d]]===o)&&(e[c[d]]={}),e=e[c[d]]}f.match(xn)?e=e[f.replace(xn,"")](t):e[f.replace(bn,"")]=t};return function(e,r){return n(e,r,t)}}function N(e){return hn(e.aoData,"_aData")}function _(e){e.aoData.length=0,e.aiDisplayMaster.length=0,e.aiDisplay.length=0}function M(e,t,n){for(var r=-1,i=0,a=e.length;a>i;i++)e[i]==t?r=i:e[i]>t&&e[i]--;-1!=r&&n===o&&e.splice(r,1)}function E(e,t,n,r){var i,a,s=e.aoData[t];if("dom"!==n&&(n&&"auto"!==n||"dom"!==s.src)){var l,u=s.anCells;if(u)for(i=0,a=u.length;a>i;i++){for(l=u[i];l.childNodes.length;)l.removeChild(l.firstChild);u[i].innerHTML=T(e,t,i,"display")}}else s._aData=j(e,s).data;s._aSortData=null,s._aFilterData=null;var c=e.aoColumns;if(r!==o)c[r].sType=null;else for(i=0,a=c.length;a>i;i++)c[i].sType=null;H(s)}function j(t,n){var r,i,o,a,s=[],l=[],u=n.firstChild,c=0,f=t.aoColumns,d=function(e,t,n){if("string"==typeof e){var r=e.indexOf("@");if(-1!==r){var i=e.substring(r+1);o["@"+i]=n.getAttribute(i)}}},h=function(t){i=f[c],a=e.trim(t.innerHTML),i&&i._bAttrSrc?(o={display:a},d(i.mData.sort,o,t),d(i.mData.type,o,t),d(i.mData.filter,o,t),s.push(o)):s.push(a),c++};if(u)for(;u;)r=u.nodeName.toUpperCase(),("TD"==r||"TH"==r)&&(h(u),l.push(u)),u=u.nextSibling;else{l=n.anCells;for(var p=0,g=l.length;g>p;p++)h(l[p])}return{data:s,cells:l}}function I(e,t,n,r){var o,a,s,l,u,c=e.aoData[t],f=c._aData,d=[];if(null===c.nTr){for(o=n||i.createElement("tr"),c.nTr=o,c.anCells=d,o._DT_RowIndex=t,H(c),l=0,u=e.aoColumns.length;u>l;l++)s=e.aoColumns[l],a=n?r[l]:i.createElement(s.sCellType),d.push(a),(!n||s.mRender||s.mData!==l)&&(a.innerHTML=T(e,t,l,"display")),s.sClass&&(a.className+=" "+s.sClass),s.bVisible&&!n?o.appendChild(a):!s.bVisible&&n&&a.parentNode.removeChild(a),s.fnCreatedCell&&s.fnCreatedCell.call(e.oInstance,a,T(e,t,l),f,t,l);zt(e,"aoRowCreatedCallback",null,[o,f,t])}c.nTr.setAttribute("role","row")}function H(t){var n=t.nTr,r=t._aData;if(n){if(r.DT_RowId&&(n.id=r.DT_RowId),r.DT_RowClass){var i=r.DT_RowClass.split(" ");t.__rowc=t.__rowc?vn(t.__rowc.concat(i)):i,e(n).removeClass(t.__rowc.join(" ")).addClass(r.DT_RowClass)}r.DT_RowData&&e(n).data(r.DT_RowData)}}function O(t){var n,r,i,o,a,s=t.nTHead,l=t.nTFoot,u=0===e("th, td",s).length,c=t.oClasses,f=t.aoColumns;for(u&&(o=e("<tr/>").appendTo(s)),n=0,r=f.length;r>n;n++)a=f[n],i=e(a.nTh).addClass(a.sClass),u&&i.appendTo(o),t.oFeatures.bSort&&(i.addClass(a.sSortingClass),a.bSortable!==!1&&(i.attr("tabindex",t.iTabIndex).attr("aria-controls",t.sTableId),_t(t,a.nTh,n))),a.sTitle!=i.html()&&i.html(a.sTitle),qt(t,"header")(t,i,a,c);if(u&&z(t.aoHeader,s),e(s).find(">tr").attr("role","row"),e(s).find(">tr>th, >tr>td").addClass(c.sHeaderTH),e(l).find(">tr>th, >tr>td").addClass(c.sFooterTH),null!==l){var d=t.aoFooter[0];for(n=0,r=d.length;r>n;n++)a=f[n],a.nTf=d[n].cell,a.sClass&&e(a.nTf).addClass(a.sClass)}}function R(t,n,r){var i,a,s,l,u,c,f,d,h,p=[],g=[],m=t.aoColumns.length;if(n){for(r===o&&(r=!1),i=0,a=n.length;a>i;i++){for(p[i]=n[i].slice(),p[i].nTr=n[i].nTr,s=m-1;s>=0;s--)t.aoColumns[s].bVisible||r||p[i].splice(s,1);g.push([])}for(i=0,a=p.length;a>i;i++){if(f=p[i].nTr)for(;c=f.firstChild;)f.removeChild(c);for(s=0,l=p[i].length;l>s;s++)if(d=1,h=1,g[i][s]===o){for(f.appendChild(p[i][s].cell),g[i][s]=1;p[i+d]!==o&&p[i][s].cell==p[i+d][s].cell;)g[i+d][s]=1,d++;for(;p[i][s+h]!==o&&p[i][s].cell==p[i][s+h].cell;){for(u=0;d>u;u++)g[i+u][s+h]=1;h++}e(p[i][s].cell).attr("rowspan",d).attr("colspan",h)}}}}function P(t){var n=zt(t,"aoPreDrawCallback","preDraw",[t]);if(-1!==e.inArray(!1,n))return void pt(t,!1);var r=[],i=0,a=t.asStripeClasses,s=a.length,l=(t.aoOpenRows.length,t.oLanguage),u=t.iInitDisplayStart,c="ssp"==Ut(t),f=t.aiDisplay;t.bDrawing=!0,u!==o&&-1!==u&&(t._iDisplayStart=c?u:u>=t.fnRecordsDisplay()?0:u,t.iInitDisplayStart=-1);var d=t._iDisplayStart,h=t.fnDisplayEnd();if(t.bDeferLoading)t.bDeferLoading=!1,t.iDraw++,pt(t,!1);else if(c){if(!t.bDestroying&&!U(t))return}else t.iDraw++;if(0!==f.length)for(var p=c?0:d,g=c?t.aoData.length:h,v=p;g>v;v++){var y=f[v],b=t.aoData[y];null===b.nTr&&I(t,y);var x=b.nTr;if(0!==s){var w=a[i%s];b._sRowStripe!=w&&(e(x).removeClass(b._sRowStripe).addClass(w),b._sRowStripe=w)}zt(t,"aoRowCallback",null,[x,b._aData,i,v]),r.push(x),i++}else{var S=l.sZeroRecords;1==t.iDraw&&"ajax"==Ut(t)?S=l.sLoadingRecords:l.sEmptyTable&&0===t.fnRecordsTotal()&&(S=l.sEmptyTable),r[0]=e("<tr/>",{"class":s?a[0]:""}).append(e("<td />",{valign:"top",colSpan:m(t),"class":t.oClasses.sRowEmpty}).html(S))[0]}zt(t,"aoHeaderCallback","header",[e(t.nTHead).children("tr")[0],N(t),d,h,f]),zt(t,"aoFooterCallback","footer",[e(t.nTFoot).children("tr")[0],N(t),d,h,f]);var C=e(t.nTBody);C.children().detach(),C.append(e(r)),zt(t,"aoDrawCallback","draw",[t]),t.bSorted=!1,t.bFiltered=!1,t.bDrawing=!1}function F(e,t){var n=e.oFeatures,r=n.bSort,i=n.bFilter;r&&Lt(e),i?J(e,e.oPreviousSearch):e.aiDisplay=e.aiDisplayMaster.slice(),t!==!0&&(e._iDisplayStart=0),e._drawHold=t,P(e),e._drawHold=!1}function W(t){var n=t.oClasses,r=e(t.nTable),i=e("<div/>").insertBefore(r),o=t.oFeatures,a=e("<div/>",{id:t.sTableId+"_wrapper","class":n.sWrapper+(t.nTFoot?"":" "+n.sNoFooter)});t.nHolding=i[0],t.nTableWrapper=a[0],t.nTableReinsertBefore=t.nTable.nextSibling;for(var s,l,u,c,f,d,h=t.sDom.split(""),p=0;p<h.length;p++){if(s=null,l=h[p],"<"==l){if(u=e("<div/>")[0],c=h[p+1],"'"==c||'"'==c){for(f="",d=2;h[p+d]!=c;)f+=h[p+d],d++;if("H"==f?f=n.sJUIHeader:"F"==f&&(f=n.sJUIFooter),-1!=f.indexOf(".")){var g=f.split(".");u.id=g[0].substr(1,g[0].length-1),u.className=g[1]}else"#"==f.charAt(0)?u.id=f.substr(1,f.length-1):u.className=f;p+=d}a.append(u),a=e(u)}else if(">"==l)a=a.parent();else if("l"==l&&o.bPaginate&&o.bLengthChange)s=ct(t);else if("f"==l&&o.bFilter)s=$(t);else if("r"==l&&o.bProcessing)s=ht(t);else if("t"==l)s=gt(t);else if("i"==l&&o.bInfo)s=it(t);else if("p"==l&&o.bPaginate)s=ft(t);else if(0!==$t.ext.feature.length)for(var m=$t.ext.feature,v=0,y=m.length;y>v;v++)if(l==m[v].cFeature){s=m[v].fnInit(t);break}if(s){var b=t.aanFeatures;b[l]||(b[l]=[]),b[l].push(s),a.append(s)}}i.replaceWith(a)}function z(t,n){var r,i,o,a,s,l,u,c,f,d,h,p=e(n).children("tr"),g=function(e,t,n){for(var r=e[t];r[n];)n++;return n};for(t.splice(0,t.length),o=0,l=p.length;l>o;o++)t.push([]);for(o=0,l=p.length;l>o;o++)for(r=p[o],c=0,i=r.firstChild;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase())for(f=1*i.getAttribute("colspan"),d=1*i.getAttribute("rowspan"),f=f&&0!==f&&1!==f?f:1,d=d&&0!==d&&1!==d?d:1,u=g(t,o,c),h=1===f?!0:!1,s=0;f>s;s++)for(a=0;d>a;a++)t[o+a][u+s]={cell:i,unique:h},t[o+a].nTr=r;i=i.nextSibling}}function B(e,t,n){var r=[];n||(n=e.aoHeader,t&&(n=[],z(n,t)));for(var i=0,o=n.length;o>i;i++)for(var a=0,s=n[i].length;s>a;a++)!n[i][a].unique||r[a]&&e.bSortCellsTop||(r[a]=n[i][a].cell);return r}function q(t,n,r){if(zt(t,"aoServerParams","serverParams",[n]),n&&e.isArray(n)){var i={},o=/(.*?)\[\]$/;e.each(n,function(e,t){var n=t.name.match(o);if(n){var r=n[0];i[r]||(i[r]=[]),i[r].push(t.value)}else i[t.name]=t.value}),n=i}var a,s=t.ajax,l=t.oInstance;if(e.isPlainObject(s)&&s.data){a=s.data;var u=e.isFunction(a)?a(n):a;n=e.isFunction(a)&&u?u:e.extend(!0,n,u),delete s.data}var c={data:n,success:function(e){var n=e.error||e.sError;n&&t.oApi._fnLog(t,0,n),t.json=e,zt(t,null,"xhr",[t,e]),r(e)},dataType:"json",cache:!1,type:t.sServerMethod,error:function(e,n){var r=t.oApi._fnLog;"parsererror"==n?r(t,0,"Invalid JSON response",1):4===e.readyState&&r(t,0,"Ajax error",7),pt(t,!1)}};t.oAjaxData=n,zt(t,null,"preXhr",[t,n]),t.fnServerData?t.fnServerData.call(l,t.sAjaxSource,e.map(n,function(e,t){return{name:t,value:e}}),r,t):t.sAjaxSource||"string"==typeof s?t.jqXHR=e.ajax(e.extend(c,{url:s||t.sAjaxSource})):e.isFunction(s)?t.jqXHR=s.call(l,n,r,t):(t.jqXHR=e.ajax(e.extend(c,s)),s.data=a)}function U(e){return e.bAjaxDataGet?(e.iDraw++,pt(e,!0),q(e,V(e),function(t){X(e,t)}),!1):!0}function V(t){var n,r,i,o,a=t.aoColumns,s=a.length,l=t.oFeatures,u=t.oPreviousSearch,c=t.aoPreSearchCols,f=[],d=kt(t),h=t._iDisplayStart,p=l.bPaginate!==!1?t._iDisplayLength:-1,g=function(e,t){f.push({name:e,value:t})};g("sEcho",t.iDraw),g("iColumns",s),g("sColumns",hn(a,"sName").join(",")),g("iDisplayStart",h),g("iDisplayLength",p);var m={draw:t.iDraw,columns:[],order:[],start:h,length:p,search:{value:u.sSearch,regex:u.bRegex}};for(n=0;s>n;n++)i=a[n],o=c[n],r="function"==typeof i.mData?"function":i.mData,m.columns.push({data:r,name:i.sName,searchable:i.bSearchable,orderable:i.bSortable,search:{value:o.sSearch,regex:o.bRegex}}),g("mDataProp_"+n,r),l.bFilter&&(g("sSearch_"+n,o.sSearch),g("bRegex_"+n,o.bRegex),g("bSearchable_"+n,i.bSearchable)),l.bSort&&g("bSortable_"+n,i.bSortable);l.bFilter&&(g("sSearch",u.sSearch),g("bRegex",u.bRegex)),l.bSort&&(e.each(d,function(e,t){m.order.push({column:t.col,dir:t.dir}),g("iSortCol_"+e,t.col),g("sSortDir_"+e,t.dir)}),g("iSortingCols",d.length));var v=$t.ext.legacy.ajax;return null===v?t.sAjaxSource?f:m:v?f:m}function X(e,t){var n=function(e,n){return t[e]!==o?t[e]:t[n]},r=n("sEcho","draw"),i=n("iTotalRecords","recordsTotal"),a=n("iTotalDisplayRecords","recordsFiltered");if(r){if(1*r<e.iDraw)return;e.iDraw=1*r}_(e),e._iRecordsTotal=parseInt(i,10),e._iRecordsDisplay=parseInt(a,10);for(var s=G(e,t),l=0,u=s.length;u>l;l++)x(e,s[l]);e.aiDisplay=e.aiDisplayMaster.slice(),e.bAjaxDataGet=!1,P(e),e._bInitComplete||lt(e,t),e.bAjaxDataGet=!0,pt(e,!1)}function G(t,n){var r=e.isPlainObject(t.ajax)&&t.ajax.dataSrc!==o?t.ajax.dataSrc:t.sAjaxDataProp;return"data"===r?n.aaData||n[r]:""!==r?L(r)(n):n}function $(t){var n=t.oClasses,r=t.sTableId,o=t.oLanguage,a=t.oPreviousSearch,s=t.aanFeatures,l='<input type="search" class="'+n.sFilterInput+'"/>',u=o.sSearch;u=u.match(/_INPUT_/)?u.replace("_INPUT_",l):u+l;var c=e("<div/>",{id:s.f?null:r+"_filter","class":n.sFilter}).append(e("<label/>").append(u)),f=function(){var e=(s.f,this.value?this.value:"");e!=a.sSearch&&(J(t,{sSearch:e,bRegex:a.bRegex,bSmart:a.bSmart,bCaseInsensitive:a.bCaseInsensitive}),t._iDisplayStart=0,P(t))},d=e("input",c).val(a.sSearch).attr("placeholder",o.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===Ut(t)?bt(f,400):f).bind("keypress.DT",function(e){return 13==e.keyCode?!1:void 0}).attr("aria-controls",r);return e(t.nTable).on("search.dt.DT",function(e,n){if(t===n)try{d[0]!==i.activeElement&&d.val(a.sSearch)}catch(r){}}),c[0]}function J(e,t,n){var r=e.oPreviousSearch,i=e.aoPreSearchCols,a=function(e){r.sSearch=e.sSearch,r.bRegex=e.bRegex,r.bSmart=e.bSmart,r.bCaseInsensitive=e.bCaseInsensitive},s=function(e){return e.bEscapeRegex!==o?!e.bEscapeRegex:e.bRegex};if(y(e),"ssp"!=Ut(e)){Q(e,t.sSearch,n,s(t),t.bSmart,t.bCaseInsensitive),a(t);for(var l=0;l<i.length;l++)K(e,i[l].sSearch,l,s(i[l]),i[l].bSmart,i[l].bCaseInsensitive);Y(e)}else a(t);e.bFiltered=!0,zt(e,null,"search",[e])}function Y(e){for(var t,n,r=$t.ext.search,i=e.aiDisplay,o=0,a=r.length;a>o;o++){for(var s=[],l=0,u=i.length;u>l;l++)n=i[l],t=e.aoData[n],r[o](e,t._aFilterData,n,t._aData,l)&&s.push(n);i.length=0,i.push.apply(i,s)}}function K(e,t,n,r,i,o){if(""!==t)for(var a,s=e.aiDisplay,l=Z(t,r,i,o),u=s.length-1;u>=0;u--)a=e.aoData[s[u]]._aFilterData[n],l.test(a)||s.splice(u,1)}function Q(e,t,n,r,i,o){var a,s,l,u=Z(t,r,i,o),c=e.oPreviousSearch.sSearch,f=e.aiDisplayMaster;if(0!==$t.ext.search.length&&(n=!0),s=tt(e),t.length<=0)e.aiDisplay=f.slice();else for((s||n||c.length>t.length||0!==t.indexOf(c)||e.bSorted)&&(e.aiDisplay=f.slice()),a=e.aiDisplay,l=a.length-1;l>=0;l--)u.test(e.aoData[a[l]]._sFilterRow)||a.splice(l,1)}function Z(t,n,r,i){if(t=n?t:et(t),r){var o=e.map(t.match(/"[^"]+"|[^ ]+/g)||"",function(e){return'"'===e.charAt(0)?e.match(/^"(.*)"$/)[1]:e});t="^(?=.*?"+o.join(")(?=.*?")+").*$"}return new RegExp(t,i?"i":"")}function et(e){return e.replace(on,"\\$1")}function tt(e){var t,n,r,i,o,a,s,l,u=e.aoColumns,c=$t.ext.type.search,f=!1;for(n=0,i=e.aoData.length;i>n;n++)if(l=e.aoData[n],!l._aFilterData){for(a=[],r=0,o=u.length;o>r;r++)t=u[r],t.bSearchable?(s=T(e,n,r,"filter"),c[t.sType]&&(s=c[t.sType](s)),null===s&&(s=""),"string"!=typeof s&&s.toString&&(s=s.toString())):s="",s.indexOf&&-1!==s.indexOf("&")&&(wn.innerHTML=s,s=Sn?wn.textContent:wn.innerText),s.replace&&(s=s.replace(/[\r\n]/g,"")),a.push(s);l._aFilterData=a,l._sFilterRow=a.join(" "),f=!0}return f}function nt(e){return{search:e.sSearch,smart:e.bSmart,regex:e.bRegex,caseInsensitive:e.bCaseInsensitive}}function rt(e){return{sSearch:e.search,bSmart:e.smart,bRegex:e.regex,bCaseInsensitive:e.caseInsensitive}}function it(t){var n=t.sTableId,r=t.aanFeatures.i,i=e("<div/>",{"class":t.oClasses.sInfo,id:r?null:n+"_info"});return r||(t.aoDrawCallback.push({fn:ot,sName:"information"}),i.attr("role","status").attr("aria-live","polite"),e(t.nTable).attr("aria-describedby",n+"_info")),i[0]}function ot(t){var n=t.aanFeatures.i;if(0!==n.length){var r=t.oLanguage,i=t._iDisplayStart+1,o=t.fnDisplayEnd(),a=t.fnRecordsTotal(),s=t.fnRecordsDisplay(),l=s?r.sInfo:r.sInfoEmpty;s!==a&&(l+=" "+r.sInfoFiltered),l+=r.sInfoPostFix,l=at(t,l);var u=r.fnInfoCallback;null!==u&&(l=u.call(t.oInstance,t,i,o,a,s,l)),e(n).html(l)}}function at(e,t){var n=e.fnFormatNumber,r=e._iDisplayStart+1,i=e._iDisplayLength,o=e.fnRecordsDisplay(),a=-1===i;return t.replace(/_START_/g,n.call(e,r)).replace(/_END_/g,n.call(e,e.fnDisplayEnd())).replace(/_MAX_/g,n.call(e,e.fnRecordsTotal())).replace(/_TOTAL_/g,n.call(e,o)).replace(/_PAGE_/g,n.call(e,a?1:Math.ceil(r/i))).replace(/_PAGES_/g,n.call(e,a?1:Math.ceil(o/i)))}function st(e){var t,n,r,i=e.iInitDisplayStart,o=e.aoColumns,a=e.oFeatures;if(!e.bInitialised)return void setTimeout(function(){st(e)},200);for(W(e),O(e),R(e,e.aoHeader),R(e,e.aoFooter),pt(e,!0),a.bAutoWidth&&yt(e),t=0,n=o.length;n>t;t++)r=o[t],r.sWidth&&(r.nTh.style.width=Tt(r.sWidth));F(e);var s=Ut(e);"ssp"!=s&&("ajax"==s?q(e,[],function(n){var r=G(e,n);for(t=0;t<r.length;t++)x(e,r[t]);e.iInitDisplayStart=i,F(e),pt(e,!1),lt(e,n)},e):(pt(e,!1),lt(e)))}function lt(e,t){e._bInitComplete=!0,t&&h(e),zt(e,"aoInitComplete","init",[e,t])}function ut(e,t){var n=parseInt(t,10);e._iDisplayLength=n,Bt(e),zt(e,null,"length",[e,n])}function ct(t){for(var n=t.oClasses,r=t.sTableId,i=t.aLengthMenu,o=e.isArray(i[0]),a=o?i[0]:i,s=o?i[1]:i,l=e("<select/>",{name:r+"_length","aria-controls":r,"class":n.sLengthSelect}),u=0,c=a.length;c>u;u++)l[0][u]=new Option(s[u],a[u]);var f=e("<div><label/></div>").addClass(n.sLength);return t.aanFeatures.l||(f[0].id=r+"_length"),f.children().append(t.oLanguage.sLengthMenu.replace("_MENU_",l[0].outerHTML)),e("select",f).val(t._iDisplayLength).bind("change.DT",function(){ut(t,e(this).val()),P(t)}),e(t.nTable).bind("length.dt.DT",function(n,r,i){t===r&&e("select",f).val(i)}),f[0]}function ft(t){var n=t.sPaginationType,r=$t.ext.pager[n],i="function"==typeof r,o=function(e){P(e)},a=e("<div/>").addClass(t.oClasses.sPaging+n)[0],s=t.aanFeatures;return i||r.fnInit(t,a,o),s.p||(a.id=t.sTableId+"_paginate",t.aoDrawCallback.push({fn:function(e){if(i){var t,n,a=e._iDisplayStart,l=e._iDisplayLength,u=e.fnRecordsDisplay(),c=-1===l,f=c?0:Math.ceil(a/l),d=c?1:Math.ceil(u/l),h=r(f,d);for(t=0,n=s.p.length;n>t;t++)qt(e,"pageButton")(e,s.p[t],t,h,f,d)}else r.fnUpdate(e,o)},sName:"pagination"})),a}function dt(e,t,n){var r=e._iDisplayStart,i=e._iDisplayLength,o=e.fnRecordsDisplay();0===o||-1===i?r=0:"number"==typeof t?(r=t*i,r>o&&(r=0)):"first"==t?r=0:"previous"==t?(r=i>=0?r-i:0,0>r&&(r=0)):"next"==t?o>r+i&&(r+=i):"last"==t?r=Math.floor((o-1)/i)*i:Ot(e,0,"Unknown paging action: "+t,5);var a=e._iDisplayStart!==r;return e._iDisplayStart=r,a&&(zt(e,null,"page",[e]),n&&P(e)),a}function ht(t){return e("<div/>",{id:t.aanFeatures.r?null:t.sTableId+"_processing","class":t.oClasses.sProcessing}).html(t.oLanguage.sProcessing).insertBefore(t.nTable)[0]}function pt(t,n){t.oFeatures.bProcessing&&e(t.aanFeatures.r).css("display",n?"block":"none"),zt(t,null,"processing",[t,n])}function gt(t){var n=e(t.nTable);n.attr("role","grid");var r=t.oScroll;if(""===r.sX&&""===r.sY)return t.nTable;var i=r.sX,o=r.sY,a=t.oClasses,s=n.children("caption"),l=s.length?s[0]._captionSide:null,u=e(n[0].cloneNode(!1)),c=e(n[0].cloneNode(!1)),f=n.children("tfoot"),d="<div/>",h=function(e){return e?Tt(e):null};r.sX&&"100%"===n.attr("width")&&n.removeAttr("width"),f.length||(f=null);var p=e(d,{"class":a.sScrollWrapper}).append(e(d,{"class":a.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:i?h(i):"100%"}).append(e(d,{"class":a.sScrollHeadInner}).css({"box-sizing":"content-box",width:r.sXInner||"100%"}).append(u.removeAttr("id").css("margin-left",0).append(n.children("thead")))).append("top"===l?s:null)).append(e(d,{"class":a.sScrollBody}).css({overflow:"auto",height:h(o),width:h(i)}).append(n));f&&p.append(e(d,{"class":a.sScrollFoot}).css({overflow:"hidden",border:0,width:i?h(i):"100%"}).append(e(d,{"class":a.sScrollFootInner}).append(c.removeAttr("id").css("margin-left",0).append(n.children("tfoot")))).append("bottom"===l?s:null));var g=p.children(),m=g[0],v=g[1],y=f?g[2]:null;return i&&e(v).scroll(function(){var e=this.scrollLeft;m.scrollLeft=e,f&&(y.scrollLeft=e)}),t.nScrollHead=m,t.nScrollBody=v,t.nScrollFoot=y,t.aoDrawCallback.push({fn:mt,sName:"scrolling"}),p[0]}function mt(t){var n,r,i,o,a,s,l,u,c,f=t.oScroll,d=f.sX,h=f.sXInner,g=f.sY,m=f.iBarWidth,v=e(t.nScrollHead),y=v[0].style,b=v.children("div"),x=b[0].style,w=b.children("table"),S=t.nScrollBody,C=e(S),T=S.style,D=e(t.nScrollFoot),k=D.children("div"),L=k.children("table"),A=e(t.nTHead),N=e(t.nTable),_=N[0],M=_.style,E=t.nTFoot?e(t.nTFoot):null,j=t.oBrowser,I=j.bScrollOversize,H=[],O=[],R=[],P=function(e){var t=e.style;t.paddingTop="0",t.paddingBottom="0",t.borderTopWidth="0",t.borderBottomWidth="0",t.height=0};if(N.children("thead, tfoot").remove(),a=A.clone().prependTo(N),n=A.find("tr"),i=a.find("tr"),a.find("th, td").removeAttr("tabindex"),E&&(s=E.clone().prependTo(N),r=E.find("tr"),o=s.find("tr")),d||(T.width="100%",v[0].style.width="100%"),e.each(B(t,a),function(e,n){l=p(t,e),n.style.width=t.aoColumns[l].sWidth}),E&&vt(function(e){e.style.width=""},o),f.bCollapse&&""!==g&&(T.height=C[0].offsetHeight+A[0].offsetHeight+"px"),c=N.outerWidth(),""===d?(M.width="100%",I&&(N.find("tbody").height()>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(M.width=Tt(N.outerWidth()-m))):""!==h?M.width=Tt(h):c==C.width()&&C.height()<N.height()?(M.width=Tt(c-m),N.outerWidth()>c-m&&(M.width=Tt(c))):M.width=Tt(c),c=N.outerWidth(),vt(P,i),vt(function(t){R.push(t.innerHTML),H.push(Tt(e(t).css("width")))},i),vt(function(e,t){e.style.width=H[t]},n),e(i).height(0),E&&(vt(P,o),vt(function(t){O.push(Tt(e(t).css("width")))},o),vt(function(e,t){e.style.width=O[t]},r),e(o).height(0)),vt(function(e,t){e.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+R[t]+"</div>",e.style.width=H[t]},i),E&&vt(function(e,t){e.innerHTML="",e.style.width=O[t]},o),N.outerWidth()<c?(u=S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y")?c+m:c,I&&(S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(M.width=Tt(u-m)),(""===d||""!==h)&&Ot(t,1,"Possible column misalignment",6)):u="100%",T.width=Tt(u),y.width=Tt(u),E&&(t.nScrollFoot.style.width=Tt(u)),g||I&&(T.height=Tt(_.offsetHeight+m)),g&&f.bCollapse){T.height=Tt(g);var F=d&&_.offsetWidth>S.offsetWidth?m:0;_.offsetHeight<S.offsetHeight&&(T.height=Tt(_.offsetHeight+F))}var W=N.outerWidth();w[0].style.width=Tt(W),x.width=Tt(W);var z=N.height()>S.clientHeight||"scroll"==C.css("overflow-y"),q="padding"+(j.bScrollbarLeft?"Left":"Right"); x[q]=z?m+"px":"0px",E&&(L[0].style.width=Tt(W),k[0].style.width=Tt(W),k[0].style[q]=z?m+"px":"0px"),C.scroll(),!t.bSorted&&!t.bFiltered||t._drawHold||(S.scrollTop=0)}function vt(e,t,n){for(var r,i,o=0,a=0,s=t.length;s>a;){for(r=t[a].firstChild,i=n?n[a].firstChild:null;r;)1===r.nodeType&&(n?e(r,i,o):e(r,o),o++),r=r.nextSibling,i=n?i.nextSibling:null;a++}}function yt(t){var r,i,o,a,s,l=t.nTable,u=t.aoColumns,c=t.oScroll,f=c.sY,d=c.sX,p=c.sXInner,g=u.length,y=v(t,"bVisible"),b=e("th",t.nTHead),x=l.getAttribute("width"),w=l.parentNode,S=!1;for(r=0;r<y.length;r++)i=u[y[r]],null!==i.sWidth&&(i.sWidth=xt(i.sWidthOrig,w),S=!0);if(S||d||f||g!=m(t)||g!=b.length){var C=e(l).clone().empty().css("visibility","hidden").removeAttr("id").append(e(t.nTHead).clone(!1)).append(e(t.nTFoot).clone(!1)).append(e("<tbody><tr/></tbody>"));C.find("tfoot th, tfoot td").css("width","");var T=C.find("tbody tr");for(b=B(t,C.find("thead")[0]),r=0;r<y.length;r++)i=u[y[r]],b[r].style.width=null!==i.sWidthOrig&&""!==i.sWidthOrig?Tt(i.sWidthOrig):"";if(t.aoData.length)for(r=0;r<y.length;r++)o=y[r],i=u[o],e(St(t,o)).clone(!1).append(i.sContentPadding).appendTo(T);if(C.appendTo(w),d&&p?C.width(p):d?(C.css("width","auto"),C.width()<w.offsetWidth&&C.width(w.offsetWidth)):f?C.width(w.offsetWidth):x&&C.width(x),wt(t,C[0]),d){var D=0;for(r=0;r<y.length;r++)i=u[y[r]],s=e(b[r]).outerWidth(),D+=null===i.sWidthOrig?s:parseInt(i.sWidth,10)+s-e(b[r]).width();C.width(Tt(D)),l.style.width=Tt(D)}for(r=0;r<y.length;r++)i=u[y[r]],a=e(b[r]).width(),a&&(i.sWidth=Tt(a));l.style.width=Tt(C.css("width")),C.remove()}else for(r=0;g>r;r++)u[r].sWidth=Tt(b.eq(r).width());x&&(l.style.width=Tt(x)),!x&&!d||t._reszEvt||(e(n).bind("resize.DT-"+t.sInstance,bt(function(){h(t)})),t._reszEvt=!0)}function bt(e,t){var n,r,i=t||200;return function(){var t=this,a=+new Date,s=arguments;n&&n+i>a?(clearTimeout(r),r=setTimeout(function(){n=o,e.apply(t,s)},i)):n?(n=a,e.apply(t,s)):n=a}}function xt(t,n){if(!t)return 0;var r=e("<div/>").css("width",Tt(t)).appendTo(n||i.body),o=r[0].offsetWidth;return r.remove(),o}function wt(t,n){var r=t.oScroll;if(r.sX||r.sY){var i=r.sX?0:r.iBarWidth;n.style.width=Tt(e(n).outerWidth()-i)}}function St(t,n){var r=Ct(t,n);if(0>r)return null;var i=t.aoData[r];return i.nTr?i.anCells[n]:e("<td/>").html(T(t,r,n,"display"))[0]}function Ct(e,t){for(var n,r=-1,i=-1,o=0,a=e.aoData.length;a>o;o++)n=T(e,o,t,"display")+"",n=n.replace(Cn,""),n.length>r&&(r=n.length,i=o);return i}function Tt(e){return null===e?"0px":"number"==typeof e?0>e?"0px":e+"px":e.match(/\d$/)?e+"px":e}function Dt(){if(!$t.__scrollbarWidth){var t=e("<p/>").css({width:"100%",height:200,padding:0})[0],n=e("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(t).appendTo("body"),r=t.offsetWidth;n.css("overflow","scroll");var i=t.offsetWidth;r===i&&(i=n[0].clientWidth),n.remove(),$t.__scrollbarWidth=r-i}return $t.__scrollbarWidth}function kt(t){var n,r,i,o,a,s,l,u=[],c=t.aoColumns,f=t.aaSortingFixed,d=e.isPlainObject(f),h=[],p=function(t){t.length&&!e.isArray(t[0])?h.push(t):h.push.apply(h,t)};for(e.isArray(f)&&p(f),d&&f.pre&&p(f.pre),p(t.aaSorting),d&&f.post&&p(f.post),n=0;n<h.length;n++)for(l=h[n][0],o=c[l].aDataSort,r=0,i=o.length;i>r;r++)a=o[r],s=c[a].sType||"string",u.push({src:l,col:a,dir:h[n][1],index:h[n][2],type:s,formatter:$t.ext.type.order[s+"-pre"]});return u}function Lt(e){var t,n,r,i,o,a=[],s=$t.ext.type.order,l=e.aoData,u=(e.aoColumns,0),c=e.aiDisplayMaster;for(y(e),o=kt(e),t=0,n=o.length;n>t;t++)i=o[t],i.formatter&&u++,Et(e,i.col);if("ssp"!=Ut(e)&&0!==o.length){for(t=0,r=c.length;r>t;t++)a[c[t]]=t;c.sort(u===o.length?function(e,t){var n,r,i,s,u,c=o.length,f=l[e]._aSortData,d=l[t]._aSortData;for(i=0;c>i;i++)if(u=o[i],n=f[u.col],r=d[u.col],s=r>n?-1:n>r?1:0,0!==s)return"asc"===u.dir?s:-s;return n=a[e],r=a[t],r>n?-1:n>r?1:0}:function(e,t){var n,r,i,u,c,f,d=o.length,h=l[e]._aSortData,p=l[t]._aSortData;for(i=0;d>i;i++)if(c=o[i],n=h[c.col],r=p[c.col],f=s[c.type+"-"+c.dir]||s["string-"+c.dir],u=f(n,r),0!==u)return u;return n=a[e],r=a[t],r>n?-1:n>r?1:0})}e.bSorted=!0}function At(e){for(var t,n,r=e.aoColumns,i=kt(e),o=e.oLanguage.oAria,a=0,s=r.length;s>a;a++){var l=r[a],u=l.asSorting,c=l.sTitle.replace(/<.*?>/g,""),f=l.nTh;f.removeAttribute("aria-sort"),l.bSortable?(i.length>0&&i[0].col==a?(f.setAttribute("aria-sort","asc"==i[0].dir?"ascending":"descending"),n=u[i[0].index+1]||u[0]):n=u[0],t=c+("asc"===n?o.sSortAscending:o.sSortDescending)):t=c,f.setAttribute("aria-label",t)}}function Nt(t,n,r,i){var a,s=t.aoColumns[n],l=t.aaSorting,u=s.asSorting,c=function(t){var n=t._idx;return n===o&&(n=e.inArray(t[1],u)),n+1>=u.length?0:n+1};if("number"==typeof l[0]&&(l=t.aaSorting=[l]),r&&t.oFeatures.bSortMulti){var f=e.inArray(n,hn(l,"0"));-1!==f?(a=c(l[f]),l[f][1]=u[a],l[f]._idx=a):(l.push([n,u[0],0]),l[l.length-1]._idx=0)}else l.length&&l[0][0]==n?(a=c(l[0]),l.length=1,l[0][1]=u[a],l[0]._idx=a):(l.length=0,l.push([n,u[0]]),l[0]._idx=0);F(t),"function"==typeof i&&i(t)}function _t(e,t,n,r){var i=e.aoColumns[n];Ft(t,{},function(t){i.bSortable!==!1&&(e.oFeatures.bProcessing?(pt(e,!0),setTimeout(function(){Nt(e,n,t.shiftKey,r),"ssp"!==Ut(e)&&pt(e,!1)},0)):Nt(e,n,t.shiftKey,r))})}function Mt(t){var n,r,i,o=t.aLastSort,a=t.oClasses.sSortColumn,s=kt(t),l=t.oFeatures;if(l.bSort&&l.bSortClasses){for(n=0,r=o.length;r>n;n++)i=o[n].src,e(hn(t.aoData,"anCells",i)).removeClass(a+(2>n?n+1:3));for(n=0,r=s.length;r>n;n++)i=s[n].src,e(hn(t.aoData,"anCells",i)).addClass(a+(2>n?n+1:3))}t.aLastSort=s}function Et(e,t){var n,r=e.aoColumns[t],i=$t.ext.order[r.sSortDataType];i&&(n=i.call(e.oInstance,e,t,g(e,t)));for(var o,a,s=$t.ext.type.order[r.sType+"-pre"],l=0,u=e.aoData.length;u>l;l++)o=e.aoData[l],o._aSortData||(o._aSortData=[]),(!o._aSortData[t]||i)&&(a=i?n[l]:T(e,l,t,"sort"),o._aSortData[t]=s?s(a):a)}function jt(t){if(t.oFeatures.bStateSave&&!t.bDestroying){var n={time:+new Date,start:t._iDisplayStart,length:t._iDisplayLength,order:e.extend(!0,[],t.aaSorting),search:nt(t.oPreviousSearch),columns:e.map(t.aoColumns,function(e,n){return{visible:e.bVisible,search:nt(t.aoPreSearchCols[n])}})};zt(t,"aoStateSaveParams","stateSaveParams",[t,n]),t.oSavedState=n,t.fnStateSaveCallback.call(t.oInstance,t,n)}}function It(t){var n,r,i=t.aoColumns;if(t.oFeatures.bStateSave){var o=t.fnStateLoadCallback.call(t.oInstance,t);if(o&&o.time){var a=zt(t,"aoStateLoadParams","stateLoadParams",[t,o]);if(-1===e.inArray(!1,a)){var s=t.iStateDuration;if(!(s>0&&o.time<+new Date-1e3*s)&&i.length===o.columns.length){for(t.oLoadedState=e.extend(!0,{},o),t._iDisplayStart=o.start,t.iInitDisplayStart=o.start,t._iDisplayLength=o.length,t.aaSorting=[],e.each(o.order,function(e,n){t.aaSorting.push(n[0]>=i.length?[0,n[1]]:n)}),e.extend(t.oPreviousSearch,rt(o.search)),n=0,r=o.columns.length;r>n;n++){var l=o.columns[n];i[n].bVisible=l.visible,e.extend(t.aoPreSearchCols[n],rt(l.search))}zt(t,"aoStateLoaded","stateLoaded",[t,o])}}}}}function Ht(t){var n=$t.settings,r=e.inArray(t,hn(n,"nTable"));return-1!==r?n[r]:null}function Ot(e,t,r,i){if(r="DataTables warning: "+(null!==e?"table id="+e.sTableId+" - ":"")+r,i&&(r+=". For more information about this error, please see http://datatables.net/tn/"+i),t)n.console&&console.log&&console.log(r);else{var o=$t.ext,a=o.sErrMode||o.errMode;if("alert"!=a)throw new Error(r);alert(r)}}function Rt(t,n,r,i){return e.isArray(r)?void e.each(r,function(r,i){e.isArray(i)?Rt(t,n,i[0],i[1]):Rt(t,n,i)}):(i===o&&(i=r),void(n[r]!==o&&(t[i]=n[r])))}function Pt(t,n,r){var i;for(var o in n)n.hasOwnProperty(o)&&(i=n[o],e.isPlainObject(i)?(e.isPlainObject(t[o])||(t[o]={}),e.extend(!0,t[o],i)):t[o]=r&&"data"!==o&&"aaData"!==o&&e.isArray(i)?i.slice():i);return t}function Ft(t,n,r){e(t).bind("click.DT",n,function(e){t.blur(),r(e)}).bind("keypress.DT",n,function(e){13===e.which&&(e.preventDefault(),r(e))}).bind("selectstart.DT",function(){return!1})}function Wt(e,t,n,r){n&&e[t].push({fn:n,sName:r})}function zt(t,n,r,i){var o=[];return n&&(o=e.map(t[n].slice().reverse(),function(e){return e.fn.apply(t.oInstance,i)})),null!==r&&e(t.nTable).trigger(r+".dt",i),o}function Bt(e){var t=e._iDisplayStart,n=e.fnDisplayEnd(),r=e._iDisplayLength;n===e.fnRecordsDisplay()&&(t=n-r),(-1===r||0>t)&&(t=0),e._iDisplayStart=t}function qt(t,n){var r=t.renderer,i=$t.ext.renderer[n];return e.isPlainObject(r)&&r[n]?i[r[n]]||i._:"string"==typeof r?i[r]||i._:i._}function Ut(e){return e.oFeatures.bServerSide?"ssp":e.ajax||e.sAjaxSource?"ajax":"dom"}function Vt(e,t){var n=[],r=Vn.numbers_length,i=Math.floor(r/2);return r>=t?n=gn(0,t):i>=e?(n=gn(0,r-2),n.push("ellipsis"),n.push(t-1)):e>=t-1-i?(n=gn(t-(r-2),t),n.splice(0,0,"ellipsis"),n.splice(0,0,0)):(n=gn(e-1,e+2),n.push("ellipsis"),n.push(t-1),n.splice(0,0,"ellipsis"),n.splice(0,0,0)),n.DT_el="span",n}function Xt(t){e.each({num:function(e){return Xn(e,t)},"num-fmt":function(e){return Xn(e,t,an)},"html-num":function(e){return Xn(e,t,tn)},"html-num-fmt":function(e){return Xn(e,t,tn,an)}},function(e,n){Jt.type.order[e+t+"-pre"]=n})}function Gt(e){return function(){var t=[Ht(this[$t.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return $t.ext.internal[e].apply(this,t)}}var $t,Jt,Yt,Kt,Qt,Zt={},en=/[\r\n]/g,tn=/<.*?>/g,nn=/^[\w\+\-]/,rn=/[\w\+\-]$/,on=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g"),an=/[',$£€¥%\u2009\u202F]/g,sn=function(e){return e&&e!==!0&&"-"!==e?!1:!0},ln=function(e){var t=parseInt(e,10);return!isNaN(t)&&isFinite(e)?t:null},un=function(e,t){return Zt[t]||(Zt[t]=new RegExp(et(t),"g")),"string"==typeof e?e.replace(/\./g,"").replace(Zt[t],"."):e},cn=function(e,t,n){var r="string"==typeof e;return t&&r&&(e=un(e,t)),n&&r&&(e=e.replace(an,"")),sn(e)||!isNaN(parseFloat(e))&&isFinite(e)},fn=function(e){return sn(e)||"string"==typeof e},dn=function(e,t,n){if(sn(e))return!0;var r=fn(e);return r&&cn(mn(e),t,n)?!0:null},hn=function(e,t,n){var r=[],i=0,a=e.length;if(n!==o)for(;a>i;i++)e[i]&&e[i][t]&&r.push(e[i][t][n]);else for(;a>i;i++)e[i]&&r.push(e[i][t]);return r},pn=function(e,t,n,r){var i=[],a=0,s=t.length;if(r!==o)for(;s>a;a++)i.push(e[t[a]][n][r]);else for(;s>a;a++)i.push(e[t[a]][n]);return i},gn=function(e,t){var n,r=[];t===o?(t=0,n=e):(n=t,t=e);for(var i=t;n>i;i++)r.push(i);return r},mn=function(e){return e.replace(tn,"")},vn=function(e){var t,n,r,i=[],o=e.length,a=0;e:for(n=0;o>n;n++){for(t=e[n],r=0;a>r;r++)if(i[r]===t)continue e;i.push(t),a++}return i},yn=function(e,t,n){e[t]!==o&&(e[n]=e[t])},bn=/\[.*?\]$/,xn=/\(\)$/,wn=e("<div>")[0],Sn=wn.textContent!==o,Cn=/<.*?>/g;$t=function(t){this.$=function(e,t){return this.api(!0).$(e,t)},this._=function(e,t){return this.api(!0).rows(e,t).data()},this.api=function(e){return new Yt(e?Ht(this[Jt.iApiIndex]):this)},this.fnAddData=function(t,n){var r=this.api(!0),i=e.isArray(t)&&(e.isArray(t[0])||e.isPlainObject(t[0]))?r.rows.add(t):r.row.add(t);return(n===o||n)&&r.draw(),i.flatten().toArray()},this.fnAdjustColumnSizing=function(e){var t=this.api(!0).columns.adjust(),n=t.settings()[0],r=n.oScroll;e===o||e?t.draw(!1):(""!==r.sX||""!==r.sY)&&mt(n)},this.fnClearTable=function(e){var t=this.api(!0).clear();(e===o||e)&&t.draw()},this.fnClose=function(e){this.api(!0).row(e).child.hide()},this.fnDeleteRow=function(e,t,n){var r=this.api(!0),i=r.rows(e),a=i.settings()[0],s=a.aoData[i[0][0]];return i.remove(),t&&t.call(this,a,s),(n===o||n)&&r.draw(),s},this.fnDestroy=function(e){this.api(!0).destroy(e)},this.fnDraw=function(e){this.api(!0).draw(!e)},this.fnFilter=function(e,t,n,r,i,a){var s=this.api(!0);null===t||t===o?s.search(e,n,r,a):s.column(t).search(e,n,r,a),s.draw()},this.fnGetData=function(e,t){var n=this.api(!0);if(e!==o){var r=e.nodeName?e.nodeName.toLowerCase():"";return t!==o||"td"==r||"th"==r?n.cell(e,t).data():n.row(e).data()||null}return n.data().toArray()},this.fnGetNodes=function(e){var t=this.api(!0);return e!==o?t.row(e).node():t.rows().nodes().flatten().toArray()},this.fnGetPosition=function(e){var t=this.api(!0),n=e.nodeName.toUpperCase();if("TR"==n)return t.row(e).index();if("TD"==n||"TH"==n){var r=t.cell(e).index();return[r.row,r.columnVisible,r.column]}return null},this.fnIsOpen=function(e){return this.api(!0).row(e).child.isShown()},this.fnOpen=function(e,t,n){return this.api(!0).row(e).child(t,n).show().child()[0]},this.fnPageChange=function(e,t){var n=this.api(!0).page(e);(t===o||t)&&n.draw(!1)},this.fnSetColumnVis=function(e,t,n){var r=this.api(!0).column(e).visible(t);(n===o||n)&&r.columns.adjust().draw()},this.fnSettings=function(){return Ht(this[Jt.iApiIndex])},this.fnSort=function(e){this.api(!0).order(e).draw()},this.fnSortListener=function(e,t,n){this.api(!0).order.listener(e,t,n)},this.fnUpdate=function(e,t,n,r,i){var a=this.api(!0);return n===o||null===n?a.row(t).data(e):a.cell(t,n).data(e),(i===o||i)&&a.columns.adjust(),(r===o||r)&&a.draw(),0},this.fnVersionCheck=Jt.fnVersionCheck;var n=this,i=t===o,c=this.length;i&&(t={}),this.oApi=this.internal=Jt.internal;for(var h in $t.ext.internal)h&&(this[h]=Gt(h));return this.each(function(){var h,p={},g=c>1?Pt(p,t,!0):t,m=0,v=this.getAttribute("id"),y=!1,S=$t.defaults;if("table"!=this.nodeName.toLowerCase())return void Ot(null,0,"Non-table node initialisation ("+this.nodeName+")",2);s(S),l(S.column),r(S,S,!0),r(S.column,S.column,!0),r(S,g);var C=$t.settings;for(m=0,h=C.length;h>m;m++){if(C[m].nTable==this){var T=g.bRetrieve!==o?g.bRetrieve:S.bRetrieve,D=g.bDestroy!==o?g.bDestroy:S.bDestroy;if(i||T)return C[m].oInstance;if(D){C[m].oInstance.fnDestroy();break}return void Ot(C[m],0,"Cannot reinitialise DataTable",3)}if(C[m].sTableId==this.id){C.splice(m,1);break}}(null===v||""===v)&&(v="DataTables_Table_"+$t.ext._unique++,this.id=v);var k=e.extend(!0,{},$t.models.oSettings,{nTable:this,oApi:n.internal,oInit:g,sDestroyWidth:e(this)[0].style.width,sInstance:v,sTableId:v});C.push(k),k.oInstance=1===n.length?n:e(this).dataTable(),s(g),g.oLanguage&&a(g.oLanguage),g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=e.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]),g=Pt(e.extend(!0,{},S),g),Rt(k.oFeatures,g,["bPaginate","bLengthChange","bFilter","bSort","bSortMulti","bInfo","bProcessing","bAutoWidth","bSortClasses","bServerSide","bDeferRender"]),Rt(k,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]),Rt(k.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]),Rt(k.oLanguage,g,"fnInfoCallback"),Wt(k,"aoDrawCallback",g.fnDrawCallback,"user"),Wt(k,"aoServerParams",g.fnServerParams,"user"),Wt(k,"aoStateSaveParams",g.fnStateSaveParams,"user"),Wt(k,"aoStateLoadParams",g.fnStateLoadParams,"user"),Wt(k,"aoStateLoaded",g.fnStateLoaded,"user"),Wt(k,"aoRowCallback",g.fnRowCallback,"user"),Wt(k,"aoRowCreatedCallback",g.fnCreatedRow,"user"),Wt(k,"aoHeaderCallback",g.fnHeaderCallback,"user"),Wt(k,"aoFooterCallback",g.fnFooterCallback,"user"),Wt(k,"aoInitComplete",g.fnInitComplete,"user"),Wt(k,"aoPreDrawCallback",g.fnPreDrawCallback,"user");var L=k.oClasses;if(g.bJQueryUI?(e.extend(L,$t.ext.oJUIClasses,g.oClasses),g.sDom===S.sDom&&"lfrtip"===S.sDom&&(k.sDom='<"H"lfr>t<"F"ip>'),k.renderer?e.isPlainObject(k.renderer)&&!k.renderer.header&&(k.renderer.header="jqueryui"):k.renderer="jqueryui"):e.extend(L,$t.ext.classes,g.oClasses),e(this).addClass(L.sTable),(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(k.oScroll.iBarWidth=Dt()),k.oScroll.sX===!0&&(k.oScroll.sX="100%"),k.iInitDisplayStart===o&&(k.iInitDisplayStart=g.iDisplayStart,k._iDisplayStart=g.iDisplayStart),null!==g.iDeferLoading){k.bDeferLoading=!0;var A=e.isArray(g.iDeferLoading);k._iRecordsDisplay=A?g.iDeferLoading[0]:g.iDeferLoading,k._iRecordsTotal=A?g.iDeferLoading[1]:g.iDeferLoading}""!==g.oLanguage.sUrl?(k.oLanguage.sUrl=g.oLanguage.sUrl,e.getJSON(k.oLanguage.sUrl,null,function(t){a(t),r(S.oLanguage,t),e.extend(!0,k.oLanguage,g.oLanguage,t),st(k)}),y=!0):e.extend(!0,k.oLanguage,g.oLanguage),null===g.asStripeClasses&&(k.asStripeClasses=[L.sStripeOdd,L.sStripeEven]);var N=k.asStripeClasses,_=e("tbody tr:eq(0)",this);-1!==e.inArray(!0,e.map(N,function(e){return _.hasClass(e)}))&&(e("tbody tr",this).removeClass(N.join(" ")),k.asDestroyStripes=N.slice());var M,E=[],I=this.getElementsByTagName("thead");if(0!==I.length&&(z(k.aoHeader,I[0]),E=B(k)),null===g.aoColumns)for(M=[],m=0,h=E.length;h>m;m++)M.push(null);else M=g.aoColumns;for(m=0,h=M.length;h>m;m++)f(k,E?E[m]:null);if(b(k,g.aoColumnDefs,M,function(e,t){d(k,e,t)}),_.length){var H=function(e,t){return e.getAttribute("data-"+t)?t:null};e.each(j(k,_[0]).cells,function(e,t){var n=k.aoColumns[e];if(n.mData===e){var r=H(t,"sort")||H(t,"order"),i=H(t,"filter")||H(t,"search");(null!==r||null!==i)&&(n.mData={_:e+".display",sort:null!==r?e+".@data-"+r:o,type:null!==r?e+".@data-"+r:o,filter:null!==i?e+".@data-"+i:o},d(k,e))}})}var O=k.oFeatures;if(g.bStateSave&&(O.bStateSave=!0,It(k,g),Wt(k,"aoDrawCallback",jt,"state_save")),g.aaSorting===o){var R=k.aaSorting;for(m=0,h=R.length;h>m;m++)R[m][1]=k.aoColumns[m].asSorting[0]}Mt(k),O.bSort&&Wt(k,"aoDrawCallback",function(){if(k.bSorted){var t=kt(k),n={};e.each(t,function(e,t){n[t.src]=t.dir}),zt(k,null,"order",[k,t,n]),At(k)}}),Wt(k,"aoDrawCallback",function(){(k.bSorted||"ssp"===Ut(k)||O.bDeferRender)&&Mt(k)},"sc"),u(k);var P=e(this).children("caption").each(function(){this._captionSide=e(this).css("caption-side")}),F=e(this).children("thead");0===F.length&&(F=e("<thead/>").appendTo(this)),k.nTHead=F[0];var W=e(this).children("tbody");0===W.length&&(W=e("<tbody/>").appendTo(this)),k.nTBody=W[0];var q=e(this).children("tfoot");if(0===q.length&&P.length>0&&(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(q=e("<tfoot/>").appendTo(this)),0===q.length||0===q.children().length?e(this).addClass(L.sNoFooter):q.length>0&&(k.nTFoot=q[0],z(k.aoFooter,k.nTFoot)),g.aaData)for(m=0;m<g.aaData.length;m++)x(k,g.aaData[m]);else(k.bDeferLoading||"dom"==Ut(k))&&w(k,e(k.nTBody).children("tr"));k.aiDisplay=k.aiDisplayMaster.slice(),k.bInitialised=!0,y===!1&&st(k)}),n=null,this};var Tn=[],Dn=Array.prototype,kn=function(t){var n,r,i=$t.settings,o=e.map(i,function(e){return e.nTable});return t?t.nTable&&t.oApi?[t]:t.nodeName&&"table"===t.nodeName.toLowerCase()?(n=e.inArray(t,o),-1!==n?[i[n]]:null):t&&"function"==typeof t.settings?t.settings().toArray():("string"==typeof t?r=e(t):t instanceof e&&(r=t),r?r.map(function(){return n=e.inArray(this,o),-1!==n?i[n]:null}).toArray():void 0):[]};Yt=function(t,n){if(!this instanceof Yt)throw"DT API must be constructed as a new object";var r=[],i=function(e){var t=kn(e);t&&r.push.apply(r,t)};if(e.isArray(t))for(var o=0,a=t.length;a>o;o++)i(t[o]);else i(t);this.context=vn(r),n&&this.push.apply(this,n.toArray?n.toArray():n),this.selector={rows:null,cols:null,opts:null},Yt.extend(this,this,Tn)},$t.Api=Yt,Yt.prototype={concat:Dn.concat,context:[],each:function(e){for(var t=0,n=this.length;n>t;t++)e.call(this,this[t],t,this);return this},eq:function(e){var t=this.context;return t.length>e?new Yt(t[e],this[e]):null},filter:function(e){var t=[];if(Dn.filter)t=Dn.filter.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)e.call(this,this[n],n,this)&&t.push(this[n]);return new Yt(this.context,t)},flatten:function(){var e=[];return new Yt(this.context,e.concat.apply(e,this.toArray()))},join:Dn.join,indexOf:Dn.indexOf||function(e,t){for(var n=t||0,r=this.length;r>n;n++)if(this[n]===e)return n;return-1},iterator:function(e,t,n){var r,i,a,s,l,u,c,f,d=[],h=this.context,p=this.selector;for("string"==typeof e&&(n=t,t=e,e=!1),i=0,a=h.length;a>i;i++)if("table"===t)r=n(h[i],i),r!==o&&d.push(r);else if("columns"===t||"rows"===t)r=n(h[i],this[i],i),r!==o&&d.push(r);else if("column"===t||"column-rows"===t||"row"===t||"cell"===t)for(c=this[i],"column-rows"===t&&(u=En(h[i],p.opts)),s=0,l=c.length;l>s;s++)f=c[s],r="cell"===t?n(h[i],f.row,f.column,i,s):n(h[i],f,i,s,u),r!==o&&d.push(r);if(d.length){var g=new Yt(h,e?d.concat.apply([],d):d),m=g.selector;return m.rows=p.rows,m.cols=p.cols,m.opts=p.opts,g}return this},lastIndexOf:Dn.lastIndexOf||function(){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(e){var t=[];if(Dn.map)t=Dn.map.call(this,e,this);else for(var n=0,r=this.length;r>n;n++)t.push(e.call(this,this[n],n));return new Yt(this.context,t)},pluck:function(e){return this.map(function(t){return t[e]})},pop:Dn.pop,push:Dn.push,reduce:Dn.reduce||function(e,t){return c(this,e,t,0,this.length,1)},reduceRight:Dn.reduceRight||function(e,t){return c(this,e,t,this.length-1,-1,-1)},reverse:Dn.reverse,selector:null,shift:Dn.shift,sort:Dn.sort,splice:Dn.splice,toArray:function(){return Dn.slice.call(this)},to$:function(){return e(this)},toJQuery:function(){return e(this)},unique:function(){return new Yt(this.context,vn(this))},unshift:Dn.unshift},Yt.extend=function(t,n,r){if(n&&(n instanceof Yt||n.__dt_wrapper)){var i,o,a,s=function(e,t,n){return function(){var r=t.apply(e,arguments);return Yt.extend(r,r,n.methodExt),r}};for(i=0,o=r.length;o>i;i++)a=r[i],n[a.name]="function"==typeof a.val?s(t,a.val,a):e.isPlainObject(a.val)?{}:a.val,n[a.name].__dt_wrapper=!0,Yt.extend(t,n[a.name],a.propExt)}},Yt.register=Kt=function(t,n){if(e.isArray(t))for(var r=0,i=t.length;i>r;r++)Yt.register(t[r],n);else{var o,a,s,l,u=t.split("."),c=Tn,f=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n].name===t)return e[n];return null};for(o=0,a=u.length;a>o;o++){l=-1!==u[o].indexOf("()"),s=l?u[o].replace("()",""):u[o];var d=f(c,s);d||(d={name:s,val:{},methodExt:[],propExt:[]},c.push(d)),o===a-1?d.val=n:c=l?d.methodExt:d.propExt}}},Yt.registerPlural=Qt=function(t,n,r){Yt.register(t,r),Yt.register(n,function(){var t=r.apply(this,arguments);return t===this?this:t instanceof Yt?t.length?e.isArray(t[0])?new Yt(t.context,t[0]):t[0]:o:t})};var Ln=function(t,n){if("number"==typeof t)return[n[t]];var r=e.map(n,function(e){return e.nTable});return e(r).filter(t).map(function(){var t=e.inArray(this,r);return n[t]}).toArray()};Kt("tables()",function(e){return e?new Yt(Ln(e,this.context)):this}),Kt("table()",function(e){var t=this.tables(e),n=t.context;return n.length?new Yt(n[0]):t}),Qt("tables().nodes()","table().node()",function(){return this.iterator("table",function(e){return e.nTable})}),Qt("tables().body()","table().body()",function(){return this.iterator("table",function(e){return e.nTBody})}),Qt("tables().header()","table().header()",function(){return this.iterator("table",function(e){return e.nTHead})}),Qt("tables().footer()","table().footer()",function(){return this.iterator("table",function(e){return e.nTFoot})}),Qt("tables().containers()","table().container()",function(){return this.iterator("table",function(e){return e.nTableWrapper})}),Kt("draw()",function(e){return this.iterator("table",function(t){F(t,e===!1)})}),Kt("page()",function(e){return e===o?this.page.info().page:this.iterator("table",function(t){dt(t,e)})}),Kt("page.info()",function(){if(0===this.context.length)return o;var e=this.context[0],t=e._iDisplayStart,n=e._iDisplayLength,r=e.fnRecordsDisplay(),i=-1===n;return{page:i?0:Math.floor(t/n),pages:i?1:Math.ceil(r/n),start:t,end:e.fnDisplayEnd(),length:n,recordsTotal:e.fnRecordsTotal(),recordsDisplay:r}}),Kt("page.len()",function(e){return e===o?0!==this.context.length?this.context[0]._iDisplayLength:o:this.iterator("table",function(t){ut(t,e)})});var An=function(e,t,n){if("ssp"==Ut(e)?F(e,t):(pt(e,!0),q(e,[],function(n){_(e);for(var r=G(e,n),i=0,o=r.length;o>i;i++)x(e,r[i]);F(e,t),pt(e,!1)})),n){var r=new Yt(e);r.one("draw",function(){n(r.ajax.json())})}};Kt("ajax.json()",function(){var e=this.context;return e.length>0?e[0].json:void 0}),Kt("ajax.params()",function(){var e=this.context;return e.length>0?e[0].oAjaxData:void 0}),Kt("ajax.reload()",function(e,t){return this.iterator("table",function(n){An(n,t===!1,e)})}),Kt("ajax.url()",function(t){var n=this.context;return t===o?0===n.length?o:(n=n[0],n.ajax?e.isPlainObject(n.ajax)?n.ajax.url:n.ajax:n.sAjaxSource):this.iterator("table",function(n){e.isPlainObject(n.ajax)?n.ajax.url=t:n.ajax=t})}),Kt("ajax.url().load()",function(e,t){return this.iterator("table",function(n){An(n,t===!1,e)})});var Nn=function(t,n){var r,i,a,s,l,u,c=[];for(t&&"string"!=typeof t&&t.length!==o||(t=[t]),a=0,s=t.length;s>a;a++)for(i=t[a]&&t[a].split?t[a].split(","):[t[a]],l=0,u=i.length;u>l;l++)r=n("string"==typeof i[l]?e.trim(i[l]):i[l]),r&&r.length&&c.push.apply(c,r);return c},_n=function(e){return e||(e={}),e.filter&&!e.search&&(e.search=e.filter),{search:e.search||"none",order:e.order||"current",page:e.page||"all"}},Mn=function(e){for(var t=0,n=e.length;n>t;t++)if(e[t].length>0)return e[0]=e[t],e.length=1,e.context=[e.context[t]],e;return e.length=0,e},En=function(t,n){var r,i,o,a=[],s=t.aiDisplay,l=t.aiDisplayMaster,u=n.search,c=n.order,f=n.page;if("ssp"==Ut(t))return"removed"===u?[]:gn(0,l.length);if("current"==f)for(r=t._iDisplayStart,i=t.fnDisplayEnd();i>r;r++)a.push(s[r]);else if("current"==c||"applied"==c)a="none"==u?l.slice():"applied"==u?s.slice():e.map(l,function(t){return-1===e.inArray(t,s)?t:null});else if("index"==c||"original"==c)for(r=0,i=t.aoData.length;i>r;r++)"none"==u?a.push(r):(o=e.inArray(r,s),(-1===o&&"removed"==u||o>=0&&"applied"==u)&&a.push(r));return a},jn=function(t,n,r){return Nn(n,function(n){var i=ln(n);if(null!==i&&!r)return[i];var o=En(t,r);if(null!==i&&-1!==e.inArray(i,o))return[i];if(!n)return o;for(var a=[],s=0,l=o.length;l>s;s++)a.push(t.aoData[o[s]].nTr);return n.nodeName&&-1!==e.inArray(n,a)?[n._DT_RowIndex]:e(a).filter(n).map(function(){return this._DT_RowIndex}).toArray()})};Kt("rows()",function(t,n){t===o?t="":e.isPlainObject(t)&&(n=t,t=""),n=_n(n);var r=this.iterator("table",function(e){return jn(e,t,n)});return r.selector.rows=t,r.selector.opts=n,r}),Kt("rows().nodes()",function(){return this.iterator("row",function(e,t){return e.aoData[t].nTr||o})}),Kt("rows().data()",function(){return this.iterator(!0,"rows",function(e,t){return pn(e.aoData,t,"_aData")})}),Qt("rows().cache()","row().cache()",function(e){return this.iterator("row",function(t,n){var r=t.aoData[n];return"search"===e?r._aFilterData:r._aSortData})}),Qt("rows().invalidate()","row().invalidate()",function(e){return this.iterator("row",function(t,n){E(t,n,e)})}),Qt("rows().indexes()","row().index()",function(){return this.iterator("row",function(e,t){return t})}),Qt("rows().remove()","row().remove()",function(){var t=this;return this.iterator("row",function(n,r,i){var o=n.aoData;o.splice(r,1);for(var a=0,s=o.length;s>a;a++)null!==o[a].nTr&&(o[a].nTr._DT_RowIndex=a);e.inArray(r,n.aiDisplay);M(n.aiDisplayMaster,r),M(n.aiDisplay,r),M(t[i],r,!1),Bt(n)})}),Kt("rows.add()",function(e){var t=this.iterator("table",function(t){var n,r,i,o=[];for(r=0,i=e.length;i>r;r++)n=e[r],o.push(n.nodeName&&"TR"===n.nodeName.toUpperCase()?w(t,n)[0]:x(t,n));return o}),n=this.rows(-1);return n.pop(),n.push.apply(n,t.toArray()),n}),Kt("row()",function(e,t){return Mn(this.rows(e,t))}),Kt("row().data()",function(e){var t=this.context;return e===o?t.length&&this.length?t[0].aoData[this[0]]._aData:o:(t[0].aoData[this[0]]._aData=e,E(t[0],this[0],"data"),this)}),Kt("row().node()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]].nTr||null:null}),Kt("row.add()",function(t){t instanceof e&&t.length&&(t=t[0]);var n=this.iterator("table",function(e){return t.nodeName&&"TR"===t.nodeName.toUpperCase()?w(e,t)[0]:x(e,t)});return this.row(n[0])});var In=function(t,n,r,i){var o=[],a=function(n,r){if(n.nodeName&&"tr"===n.nodeName.toLowerCase())o.push(n);else{var i=e("<tr><td/></tr>").addClass(r);e("td",i).addClass(r).html(n)[0].colSpan=m(t),o.push(i[0])}};if(e.isArray(r)||r instanceof e)for(var s=0,l=r.length;l>s;s++)a(r[s],i);else a(r,i);n._details&&n._details.remove(),n._details=e(o),n._detailsShow&&n._details.insertAfter(n.nTr)},Hn=function(e){var t=e.context;if(t.length&&e.length){var n=t[0].aoData[e[0]];n._details&&(n._details.remove(),n._detailsShow=o,n._details=o)}},On=function(e,t){var n=e.context;if(n.length&&e.length){var r=n[0].aoData[e[0]];r._details&&(r._detailsShow=t,t?r._details.insertAfter(r.nTr):r._details.detach(),Rn(n[0]))}},Rn=function(e){var t=new Yt(e),n=".dt.DT_details",r="draw"+n,i="column-visibility"+n,o="destroy"+n,a=e.aoData;t.off(r+" "+i+" "+o),hn(a,"_details").length>0&&(t.on(r,function(n,r){e===r&&t.rows({page:"current"}).eq(0).each(function(e){var t=a[e];t._detailsShow&&t._details.insertAfter(t.nTr)})}),t.on(i,function(t,n){if(e===n)for(var r,i=m(n),o=0,s=a.length;s>o;o++)r=a[o],r._details&&r._details.children("td[colspan]").attr("colspan",i)}),t.on(o,function(t,n){if(e===n)for(var r=0,i=a.length;i>r;r++)a[r]._details&&Hn(a[r])}))},Pn="",Fn=Pn+"row().child",Wn=Fn+"()";Kt(Wn,function(e,t){var n=this.context;return e===o?n.length&&this.length?n[0].aoData[this[0]]._details:o:(e===!0?this.child.show():e===!1?Hn(this):n.length&&this.length&&In(n[0],n[0].aoData[this[0]],e,t),this)}),Kt([Fn+".show()",Wn+".show()"],function(){return On(this,!0),this}),Kt([Fn+".hide()",Wn+".hide()"],function(){return On(this,!1),this}),Kt([Fn+".remove()",Wn+".remove()"],function(){return Hn(this),this}),Kt(Fn+".isShown()",function(){var e=this.context;return e.length&&this.length?e[0].aoData[this[0]]._detailsShow||!1:!1});var zn=/^(.+):(name|visIdx|visible)$/,Bn=function(t,n){var r=t.aoColumns,i=hn(r,"sName"),o=hn(r,"nTh");return Nn(n,function(n){var a=ln(n);if(""===n)return gn(r.length);if(null!==a)return[a>=0?a:r.length+a];var s="string"==typeof n?n.match(zn):"";if(!s)return e(o).filter(n).map(function(){return e.inArray(this,o)}).toArray();switch(s[2]){case"visIdx":case"visible":var l=parseInt(s[1],10);if(0>l){var u=e.map(r,function(e,t){return e.bVisible?t:null});return[u[u.length+l]]}return[p(t,l)];case"name":return e.map(i,function(e,t){return e===s[1]?t:null})}})},qn=function(t,n,r,i){var a,s,l,u,c=t.aoColumns,f=c[n],d=t.aoData;if(r===o)return f.bVisible;if(f.bVisible!==r){if(r){var p=e.inArray(!0,hn(c,"bVisible"),n+1);for(s=0,l=d.length;l>s;s++)u=d[s].nTr,a=d[s].anCells,u&&u.insertBefore(a[n],a[p]||null)}else e(hn(t.aoData,"anCells",n)).detach();f.bVisible=r,R(t,t.aoHeader),R(t,t.aoFooter),(i===o||i)&&(h(t),(t.oScroll.sX||t.oScroll.sY)&&mt(t)),zt(t,null,"column-visibility",[t,n,r]),jt(t)}};Kt("columns()",function(t,n){t===o?t="":e.isPlainObject(t)&&(n=t,t=""),n=_n(n);var r=this.iterator("table",function(e){return Bn(e,t,n)});return r.selector.cols=t,r.selector.opts=n,r}),Qt("columns().header()","column().header()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTh})}),Qt("columns().footer()","column().footer()",function(){return this.iterator("column",function(e,t){return e.aoColumns[t].nTf})}),Qt("columns().data()","column().data()",function(){return this.iterator("column-rows",function(e,t,n,r,i){for(var o=[],a=0,s=i.length;s>a;a++)o.push(T(e,i[a],t,""));return o})}),Qt("columns().cache()","column().cache()",function(e){return this.iterator("column-rows",function(t,n,r,i,o){return pn(t.aoData,o,"search"===e?"_aFilterData":"_aSortData",n)})}),Qt("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(e,t,n,r,i){return pn(e.aoData,i,"anCells",t)})}),Qt("columns().visible()","column().visible()",function(e,t){return this.iterator("column",function(n,r){return e===o?n.aoColumns[r].bVisible:qn(n,r,e,t)})}),Qt("columns().indexes()","column().index()",function(e){return this.iterator("column",function(t,n){return"visible"===e?g(t,n):n})}),Kt("columns.adjust()",function(){return this.iterator("table",function(e){h(e)})}),Kt("column.index()",function(e,t){if(0!==this.context.length){var n=this.context[0]; if("fromVisible"===e||"toData"===e)return p(n,t);if("fromData"===e||"toVisible"===e)return g(n,t)}}),Kt("column()",function(e,t){return Mn(this.columns(e,t))});var Un=function(t,n,r){var i,a,s,l,u,c=t.aoData,f=En(t,r),d=pn(c,f,"anCells"),h=e([].concat.apply([],d)),p=t.aoColumns.length;return Nn(n,function(t){if(null===t||t===o){for(a=[],s=0,l=f.length;l>s;s++)for(i=f[s],u=0;p>u;u++)a.push({row:i,column:u});return a}return e.isPlainObject(t)?[t]:h.filter(t).map(function(t,n){return i=n.parentNode._DT_RowIndex,{row:i,column:e.inArray(n,c[i].anCells)}}).toArray()})};Kt("cells()",function(t,n,r){if(e.isPlainObject(t)&&(typeof t.row!==o?(r=n,n=null):(r=t,t=null)),e.isPlainObject(n)&&(r=n,n=null),null===n||n===o)return this.iterator("table",function(e){return Un(e,t,_n(r))});var i,a,s,l,u,c=this.columns(n,r),f=this.rows(t,r),d=this.iterator("table",function(e,t){for(i=[],a=0,s=f[t].length;s>a;a++)for(l=0,u=c[t].length;u>l;l++)i.push({row:f[t][a],column:c[t][l]});return i});return e.extend(d.selector,{cols:n,rows:t,opts:r}),d}),Qt("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(e,t,n){return e.aoData[t].anCells[n]})}),Kt("cells().data()",function(){return this.iterator("cell",function(e,t,n){return T(e,t,n)})}),Qt("cells().cache()","cell().cache()",function(e){return e="search"===e?"_aFilterData":"_aSortData",this.iterator("cell",function(t,n,r){return t.aoData[n][e][r]})}),Qt("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(e,t,n){return{row:t,column:n,columnVisible:g(e,n)}})}),Kt(["cells().invalidate()","cell().invalidate()"],function(e){var t=this.selector;return this.rows(t.rows,t.opts).invalidate(e),this}),Kt("cell()",function(e,t,n){return Mn(this.cells(e,t,n))}),Kt("cell().data()",function(e){var t=this.context,n=this[0];return e===o?t.length&&n.length?T(t[0],n[0].row,n[0].column):o:(D(t[0],n[0].row,n[0].column,e),E(t[0],n[0].row,"data",n[0].column),this)}),Kt("order()",function(t,n){var r=this.context;return t===o?0!==r.length?r[0].aaSorting:o:("number"==typeof t?t=[[t,n]]:e.isArray(t[0])||(t=Array.prototype.slice.call(arguments)),this.iterator("table",function(e){e.aaSorting=t.slice()}))}),Kt("order.listener()",function(e,t,n){return this.iterator("table",function(r){_t(r,e,t,n)})}),Kt(["columns().order()","column().order()"],function(t){var n=this;return this.iterator("table",function(r,i){var o=[];e.each(n[i],function(e,n){o.push([n,t])}),r.aaSorting=o})}),Kt("search()",function(t,n,r,i){var a=this.context;return t===o?0!==a.length?a[0].oPreviousSearch.sSearch:o:this.iterator("table",function(o){o.oFeatures.bFilter&&J(o,e.extend({},o.oPreviousSearch,{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),1)})}),Qt("columns().search()","column().search()",function(t,n,r,i){return this.iterator("column",function(a,s){var l=a.aoPreSearchCols;return t===o?l[s].sSearch:void(a.oFeatures.bFilter&&(e.extend(l[s],{sSearch:t+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),J(a,a.oPreviousSearch,1)))})}),Kt("state()",function(){return this.context.length?this.context[0].oSavedState:null}),Kt("state.clear()",function(){return this.iterator("table",function(e){e.fnStateSaveCallback.call(e.oInstance,e,{})})}),Kt("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null}),Kt("state.save()",function(){return this.iterator("table",function(e){jt(e)})}),$t.versionCheck=$t.fnVersionCheck=function(e){for(var t,n,r=$t.version.split("."),i=e.split("."),o=0,a=i.length;a>o;o++)if(t=parseInt(r[o],10)||0,n=parseInt(i[o],10)||0,t!==n)return t>n;return!0},$t.isDataTable=$t.fnIsDataTable=function(t){var n=e(t).get(0),r=!1;return e.each($t.settings,function(e,t){(t.nTable===n||t.nScrollHead===n||t.nScrollFoot===n)&&(r=!0)}),r},$t.tables=$t.fnTables=function(t){return jQuery.map($t.settings,function(n){return!t||t&&e(n.nTable).is(":visible")?n.nTable:void 0})},$t.camelToHungarian=r,Kt("$()",function(t,n){var r=this.rows(n).nodes(),i=e(r);return e([].concat(i.filter(t).toArray(),i.find(t).toArray()))}),e.each(["on","one","off"],function(t,n){Kt(n+"()",function(){var t=Array.prototype.slice.call(arguments);t[0].match(/\.dt\b/)||(t[0]+=".dt");var r=e(this.tables().nodes());return r[n].apply(r,t),this})}),Kt("clear()",function(){return this.iterator("table",function(e){_(e)})}),Kt("settings()",function(){return new Yt(this.context,this.context)}),Kt("data()",function(){return this.iterator("table",function(e){return hn(e.aoData,"_aData")}).flatten()}),Kt("destroy()",function(t){return t=t||!1,this.iterator("table",function(r){var i,o=r.nTableWrapper.parentNode,a=r.oClasses,s=r.nTable,l=r.nTBody,u=r.nTHead,c=r.nTFoot,f=e(s),d=e(l),h=e(r.nTableWrapper),p=e.map(r.aoData,function(e){return e.nTr});r.bDestroying=!0,zt(r,"aoDestroyCallback","destroy",[r]),t||new Yt(r).columns().visible(!0),h.unbind(".DT").find(":not(tbody *)").unbind(".DT"),e(n).unbind(".DT-"+r.sInstance),s!=u.parentNode&&(f.children("thead").detach(),f.append(u)),c&&s!=c.parentNode&&(f.children("tfoot").detach(),f.append(c)),f.detach(),h.detach(),r.aaSorting=[],r.aaSortingFixed=[],Mt(r),e(p).removeClass(r.asStripeClasses.join(" ")),e("th, td",u).removeClass(a.sSortable+" "+a.sSortableAsc+" "+a.sSortableDesc+" "+a.sSortableNone),r.bJUI&&(e("th span."+a.sSortIcon+", td span."+a.sSortIcon,u).detach(),e("th, td",u).each(function(){var t=e("div."+a.sSortJUIWrapper,this);e(this).append(t.contents()),t.detach()})),!t&&o&&o.insertBefore(s,r.nTableReinsertBefore),d.children().detach(),d.append(p),f.css("width",r.sDestroyWidth).removeClass(a.sTable),i=r.asDestroyStripes.length,i&&d.children().each(function(t){e(this).addClass(r.asDestroyStripes[t%i])});var g=e.inArray(r,$t.settings);-1!==g&&$t.settings.splice(g,1)})}),$t.version="1.10.2",$t.settings=[],$t.models={},$t.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0},$t.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null},$t.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null},$t.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(e){return e.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(e){try{return JSON.parse((-1===e.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+e.sInstance+"_"+location.pathname))}catch(t){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(e,t){try{(-1===e.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+e.sInstance+"_"+location.pathname,JSON.stringify(t))}catch(n){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:e.extend({},$t.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null},t($t.defaults),$t.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null},t($t.defaults.column),$t.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:o,oAjaxData:o,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Ut(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Ut(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var e=this._iDisplayLength,t=this._iDisplayStart,n=t+e,r=this.aiDisplay.length,i=this.oFeatures,o=i.bPaginate;return i.bServerSide?o===!1||-1===e?t+r:Math.min(t+e,this._iRecordsDisplay):!o||n>r||-1===e?r:n},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}},$t.ext=Jt={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:$t.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:$t.version},e.extend(Jt,{afnFiltering:Jt.search,aTypes:Jt.type.detect,ofnSearch:Jt.type.search,oSort:Jt.type.order,afnSortData:Jt.order,aoFeatures:Jt.feature,oApi:Jt.internal,oStdClasses:Jt.classes,oPagination:Jt.pager}),e.extend($t.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""}),function(){var t="";t="";var n=t+"ui-state-default",r=t+"css_right ui-icon ui-icon-",i=t+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";e.extend($t.ext.oJUIClasses,$t.ext.classes,{sPageButton:"fg-button ui-button "+n,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:n+" sorting_asc",sSortDesc:n+" sorting_desc",sSortable:n+" sorting",sSortableAsc:n+" sorting_asc_disabled",sSortableDesc:n+" sorting_desc_disabled",sSortableNone:n+" sorting_disabled",sSortJUIAsc:r+"triangle-1-n",sSortJUIDesc:r+"triangle-1-s",sSortJUI:r+"carat-2-n-s",sSortJUIAscAllowed:r+"carat-1-n",sSortJUIDescAllowed:r+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+n,sScrollFoot:"dataTables_scrollFoot "+n,sHeaderTH:n,sFooterTH:n,sJUIHeader:i+" ui-corner-tl ui-corner-tr",sJUIFooter:i+" ui-corner-bl ui-corner-br"})}();var Vn=$t.ext.pager;e.extend(Vn,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(e,t){return["previous",Vt(e,t),"next"]},full_numbers:function(e,t){return["first","previous",Vt(e,t),"next","last"]},_numbers:Vt,numbers_length:7}),e.extend(!0,$t.ext.renderer,{pageButton:{_:function(t,n,r,o,a,s){var l,u,c=t.oClasses,f=t.oLanguage.oPaginate,d=0,h=function(n,i){var o,p,g,m,v=function(e){dt(t,e.data.action,!0)};for(o=0,p=i.length;p>o;o++)if(m=i[o],e.isArray(m)){var y=e("<"+(m.DT_el||"div")+"/>").appendTo(n);h(y,m)}else{switch(l="",u="",m){case"ellipsis":n.append("<span>&hellip;</span>");break;case"first":l=f.sFirst,u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"previous":l=f.sPrevious,u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"next":l=f.sNext,u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;case"last":l=f.sLast,u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;default:l=m+1,u=a===m?c.sPageButtonActive:""}l&&(g=e("<a>",{"class":c.sPageButton+" "+u,"aria-controls":t.sTableId,"data-dt-idx":d,tabindex:t.iTabIndex,id:0===r&&"string"==typeof m?t.sTableId+"_"+m:null}).html(l).appendTo(n),Ft(g,{action:m},v),d++)}};try{var p=e(i.activeElement).data("dt-idx");h(e(n).empty(),o),null!==p&&e(n).find("[data-dt-idx="+p+"]").focus()}catch(g){}}}});var Xn=function(e,t,n,r){return e&&"-"!==e?(t&&(e=un(e,t)),e.replace&&(n&&(e=e.replace(n,"")),r&&(e=e.replace(r,""))),1*e):-1/0};return e.extend(Jt.type.order,{"date-pre":function(e){return Date.parse(e)||0},"html-pre":function(e){return sn(e)?"":e.replace?e.replace(/<.*?>/g,"").toLowerCase():e+""},"string-pre":function(e){return sn(e)?"":"string"==typeof e?e.toLowerCase():e.toString?e.toString():""},"string-asc":function(e,t){return t>e?-1:e>t?1:0},"string-desc":function(e,t){return t>e?1:e>t?-1:0}}),Xt(""),e.extend($t.ext.type.detect,[function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n)?"num"+n:null},function(e){if(e&&(!nn.test(e)||!rn.test(e)))return null;var t=Date.parse(e);return null!==t&&!isNaN(t)||sn(e)?"date":null},function(e,t){var n=t.oLanguage.sDecimal;return cn(e,n,!0)?"num-fmt"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n)?"html-num"+n:null},function(e,t){var n=t.oLanguage.sDecimal;return dn(e,n,!0)?"html-num-fmt"+n:null},function(e){return sn(e)||"string"==typeof e&&-1!==e.indexOf("<")?"html":null}]),e.extend($t.ext.type.search,{html:function(e){return sn(e)?e:"string"==typeof e?e.replace(en," ").replace(tn,""):""},string:function(e){return sn(e)?e:"string"==typeof e?e.replace(en," "):e}}),e.extend(!0,$t.ext.renderer,{header:{_:function(t,n,r,i){e(t.nTable).on("order.dt.DT",function(e,o,a,s){if(t===o){var l=r.idx;n.removeClass(r.sSortingClass+" "+i.sSortAsc+" "+i.sSortDesc).addClass("asc"==s[l]?i.sSortAsc:"desc"==s[l]?i.sSortDesc:r.sSortingClass)}})},jqueryui:function(t,n,r,i){var o=r.idx;e("<div/>").addClass(i.sSortJUIWrapper).append(n.contents()).append(e("<span/>").addClass(i.sSortIcon+" "+r.sSortingClassJUI)).appendTo(n),e(t.nTable).on("order.dt.DT",function(e,a,s,l){t===a&&(n.removeClass(i.sSortAsc+" "+i.sSortDesc).addClass("asc"==l[o]?i.sSortAsc:"desc"==l[o]?i.sSortDesc:r.sSortingClass),n.find("span."+i.sSortIcon).removeClass(i.sSortJUIAsc+" "+i.sSortJUIDesc+" "+i.sSortJUI+" "+i.sSortJUIAscAllowed+" "+i.sSortJUIDescAllowed).addClass("asc"==l[o]?i.sSortJUIAsc:"desc"==l[o]?i.sSortJUIDesc:r.sSortingClassJUI))})}}}),$t.render={number:function(e,t,n,r){return{display:function(i){var o=0>i?"-":"";i=Math.abs(parseFloat(i));var a=parseInt(i,10),s=n?t+(i-a).toFixed(n).substring(2):"";return o+(r||"")+a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,e)+s}}}},e.extend($t.ext.internal,{_fnExternApiFunc:Gt,_fnBuildAjax:q,_fnAjaxUpdate:U,_fnAjaxParameters:V,_fnAjaxUpdateDraw:X,_fnAjaxDataSrc:G,_fnAddColumn:f,_fnColumnOptions:d,_fnAdjustColumnSizing:h,_fnVisibleToColumnIndex:p,_fnColumnIndexToVisible:g,_fnVisbleColumns:m,_fnGetColumns:v,_fnColumnTypes:y,_fnApplyColumnDefs:b,_fnHungarianMap:t,_fnCamelToHungarian:r,_fnLanguageCompat:a,_fnBrowserDetect:u,_fnAddData:x,_fnAddTr:w,_fnNodeToDataIndex:S,_fnNodeToColumnIndex:C,_fnGetCellData:T,_fnSetCellData:D,_fnSplitObjNotation:k,_fnGetObjectDataFn:L,_fnSetObjectDataFn:A,_fnGetDataMaster:N,_fnClearTable:_,_fnDeleteIndex:M,_fnInvalidateRow:E,_fnGetRowElements:j,_fnCreateTr:I,_fnBuildHead:O,_fnDrawHead:R,_fnDraw:P,_fnReDraw:F,_fnAddOptionsHtml:W,_fnDetectHeader:z,_fnGetUniqueThs:B,_fnFeatureHtmlFilter:$,_fnFilterComplete:J,_fnFilterCustom:Y,_fnFilterColumn:K,_fnFilter:Q,_fnFilterCreateSearch:Z,_fnEscapeRegex:et,_fnFilterData:tt,_fnFeatureHtmlInfo:it,_fnUpdateInfo:ot,_fnInfoMacros:at,_fnInitialise:st,_fnInitComplete:lt,_fnLengthChange:ut,_fnFeatureHtmlLength:ct,_fnFeatureHtmlPaginate:ft,_fnPageChange:dt,_fnFeatureHtmlProcessing:ht,_fnProcessingDisplay:pt,_fnFeatureHtmlTable:gt,_fnScrollDraw:mt,_fnApplyToChildren:vt,_fnCalculateColumnWidths:yt,_fnThrottle:bt,_fnConvertToWidth:xt,_fnScrollingWidthAdjust:wt,_fnGetWidestNode:St,_fnGetMaxLenString:Ct,_fnStringToCss:Tt,_fnScrollBarWidth:Dt,_fnSortFlatten:kt,_fnSort:Lt,_fnSortAria:At,_fnSortListener:Nt,_fnSortAttachListener:_t,_fnSortingClasses:Mt,_fnSortData:Et,_fnSaveState:jt,_fnLoadState:It,_fnSettingsFromNode:Ht,_fnLog:Ot,_fnMap:Rt,_fnBindAction:Ft,_fnCallbackReg:Wt,_fnCallbackFire:zt,_fnLengthOverflow:Bt,_fnRenderer:qt,_fnDataSource:Ut,_fnRowAttributes:H,_fnCalculateEnd:function(){}}),e.fn.dataTable=$t,e.fn.dataTableSettings=$t.settings,e.fn.dataTableExt=$t.ext,e.fn.DataTable=function(t){return e(this).dataTable(t).api()},e.each($t,function(t,n){e.fn.DataTable[t]=n}),e.fn.dataTable})}(window,document)},{jquery:8}],3:[function(){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")},function(e){"use strict";e.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var n=parseInt(e);return isNaN(n)?null:n}},parsers:{parse:function(e,t){function n(){if(l=0,u="",t.start&&t.state.rowNum<t.start)return s=[],t.state.rowNum++,void(t.state.colNum=1);if(void 0===t.onParseEntry)a.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&a.push(e)}s=[],t.end&&t.state.rowNum>=t.end&&(c=!0),t.state.rowNum++,t.state.colNum=1}function r(){if(void 0===t.onParseValue)s.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&s.push(e)}u="",l=0,t.state.colNum++}var i=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var a=[],s=[],l=0,u="",c=!1,f=RegExp.escape(i),d=RegExp.escape(o),h=/(D|S|\n|\r|[^DS\r\n]+)/,p=h.source;return p=p.replace(/S/g,f),p=p.replace(/D/g,d),h=RegExp(p,"gm"),e.replace(h,function(e){if(!c)switch(l){case 0:if(e===i){u+="",r();break}if(e===o){l=1;break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;u+=e,l=3;break;case 1:if(e===o){l=2;break}u+=e,l=1;break;case 2:if(e===o){u+=e,l=1;break}if(e===i){r();break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===i){r();break}if("\n"===e){r(),n();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),0!==s.length&&(r(),n()),a},splitLines:function(e,t){function n(){if(a=0,t.start&&t.state.rowNum<t.start)return s="",void t.state.rowNum++;if(void 0===t.onParseEntry)o.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&o.push(e)}s="",t.end&&t.state.rowNum>=t.end&&(l=!0),t.state.rowNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],a=0,s="",l=!1,u=RegExp.escape(r),c=RegExp.escape(i),f=/(D|S|\n|\r|[^DS\r\n]+)/,d=f.source;return d=d.replace(/S/g,u),d=d.replace(/D/g,c),f=RegExp(d,"gm"),e.replace(f,function(e){if(!l)switch(a){case 0:if(e===r){s+=e,a=0;break}if(e===i){s+=e,a=1;break}if("\n"===e){n();break}if(/^\r$/.test(e))break;s+=e,a=3;break;case 1:if(e===i){s+=e,a=2;break}s+=e,a=1;break;case 2:var o=s.substr(s.length-1);if(e===i&&o===i){s+=e,a=1;break}if(e===r){s+=e,a=0;break}if("\n"===e){n();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===r){s+=e,a=0;break}if("\n"===e){n();break}if("\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}}),""!==s&&n(),o},parseEntry:function(e,t){function n(){if(void 0===t.onParseValue)o.push(s);else{var e=t.onParseValue(s,t.state);e!==!1&&o.push(e)}s="",a=0,t.state.colNum++}var r=t.separator,i=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var o=[],a=0,s="";if(!t.match){var l=RegExp.escape(r),u=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,f=c.source;f=f.replace(/S/g,l),f=f.replace(/D/g,u),t.match=RegExp(f,"gm")}return e.replace(t.match,function(e){switch(a){case 0:if(e===r){s+="",n();break}if(e===i){a=1;break}if("\n"===e||"\r"===e)break;s+=e,a=3;break;case 1:if(e===i){a=2;break}s+=e,a=1;break;case 2:if(e===i){s+=e,a=1;break}if(e===r){n();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===r){n();break}if("\n"===e||"\r"===e)break;if(e===i)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),n(),o}},toArray:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},a=e.csv.parsers.parseEntry(t,n);return i.callback?void i.callback("",a):a},toArrays:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};return o=e.csv.parsers.parse(t,n),i.callback?void i.callback("",o):o},toObjects:function(t,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1,i.separator="separator"in n?n.separator:e.csv.defaults.separator,i.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,i.headers="headers"in n?n.headers:e.csv.defaults.headers,n.start="start"in n?n.start:1,i.headers&&n.start++,n.end&&i.headers&&n.end++;var o=[],a=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},s={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=e.csv.parsers.splitLines(t,s),u=e.csv.toArray(l[0],n),o=e.csv.parsers.splitLines(t,n);n.state.colNum=1,n.state.rowNum=u?2:1;for(var c=0,f=o.length;f>c;c++){var d=e.csv.toArray(o[c],n),h={};for(var p in u)h[u[p]]=d[p];a.push(h),n.state.rowNum++}return i.callback?void i.callback("",a):a},fromArrays:function(t,n,r){var n=void 0!==n?n:{},o={};if(o.callback=void 0!==r&&"function"==typeof r?r:!1,o.separator="separator"in n?n.separator:e.csv.defaults.separator,o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,o.escaper="escaper"in n?n.escaper:e.csv.defaults.escaper,o.experimental="experimental"in n?n.experimental:!1,!o.experimental)throw new Error("not implemented");var a=[];for(i in t)a.push(t[i]);return o.callback?void o.callback("",a):a},fromObjects2CSV:function(t,n,r){var n=void 0!==n?n:{},o={};if(o.callback=void 0!==r&&"function"==typeof r?r:!1,o.separator="separator"in n?n.separator:e.csv.defaults.separator,o.delimiter="delimiter"in n?n.delimiter:e.csv.defaults.delimiter,o.experimental="experimental"in n?n.experimental:!1,!o.experimental)throw new Error("not implemented");var a=[];for(i in t)a.push(arrays[i]);return o.callback?void o.callback("",a):a}},e.csvEntry2Array=e.csv.toArray,e.csv2Array=e.csv.toArrays,e.csv2Dictionary=e.csv.toObjects}(jQuery)},{}],4:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){function t(e,t,r,i){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&s[o.text.charAt(l)]||s[o.text.charAt(++l)];if(!u)return null;var c=">"==u.charAt(1)?1:-1;if(r&&c>0!=(l==t.ch))return null;var f=e.getTokenTypeAt(a(t.line,l+1)),d=n(e,a(t.line,l+(c>0?1:0)),c,f||null,i);return null==d?null:{from:a(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:c>0}}function n(e,t,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],c=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,f=n>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=f;d+=n){var h=e.getLine(d);if(h){var p=n>0?0:h.length-1,g=n>0?h.length:-1;if(!(h.length>o))for(d==t.line&&(p=t.ch-(0>n?1:0));p!=g;p+=n){var m=h.charAt(p);if(c.test(m)&&(void 0===r||e.getTokenTypeAt(a(d,p+1))==r)){var v=s[m];if(">"==v.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:a(d,p),ch:m};u.pop()}}}}}return d-n==(n>0?e.lastLine():e.firstLine())?!1:null}function r(e,n,r){for(var i=e.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=e.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&t(e,l[u].head,!1,r);if(c&&e.getLine(c.from.line).length<=i){var f=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";s.push(e.markText(c.from,a(c.from.line,c.from.ch+1),{className:f})),c.to&&e.getLine(c.to.line).length<=i&&s.push(e.markText(c.to,a(c.to.line,c.to.ch+1),{className:f}))}}if(s.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<s.length;e++)s[e].clear()})};if(!n)return d;setTimeout(d,800)}}function i(e){e.operation(function(){l&&(l(),l=null),l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),a=e.Pos,s={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,n,r){r&&r!=e.Init&&t.off("cursorActivity",i),n&&(t.state.matchBrackets="object"==typeof n?n:{},t.on("cursorActivity",i))}),e.defineExtension("matchBrackets",function(){r(this,!0)}),e.defineExtension("findMatchingBracket",function(e,n,r){return t(this,e,n,r)}),e.defineExtension("scanForBracket",function(e,t,r,i){return n(this,e,t,r,i)})})},{"../../lib/codemirror":5}],5:[function(t,n,r){!function(t){if("object"==typeof r&&"object"==typeof n)n.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}}(function(){"use strict";function e(n,r){if(!(this instanceof e))return new e(n,r);this.options=r=r?mo(r):{},mo(ja,r,!1),p(r);var i=r.value;"string"==typeof i&&(i=new rs(i,r.mode)),this.doc=i;var o=this.display=new t(n,i);o.wrapper.CodeMirror=this,c(this),l(this),r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),r.autofocus&&!ca&&kn(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new lo},Zo&&11>ea&&setTimeout(vo(Dn,this,!0),20),Nn(this),Mo(),Zt(this),this.curOp.forceUpdate=!0,Ni(this,i),r.autofocus&&!ca||Do()==o.input?setTimeout(vo(Qn,this),20):Zn(this);for(var a in Ia)Ia.hasOwnProperty(a)&&Ia[a](this,r[a],Ha);x(this);for(var s=0;s<Fa.length;++s)Fa[s](this);tn(this)}function t(e,t){var n=this,r=n.input=wo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ta?r.style.width="1000px":r.setAttribute("wrap","off"),ua&&(r.style.border="1px solid black"),r.setAttribute("autocorrect","off"),r.setAttribute("autocapitalize","off"),r.setAttribute("spellcheck","false"),n.inputDiv=wo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),n.scrollbarH=wo("div",[wo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar"),n.scrollbarV=wo("div",[wo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n.scrollbarFiller=wo("div",null,"CodeMirror-scrollbar-filler"),n.gutterFiller=wo("div",null,"CodeMirror-gutter-filler"),n.lineDiv=wo("div",null,"CodeMirror-code"),n.selectionDiv=wo("div",null,null,"position: relative; z-index: 1"),n.cursorDiv=wo("div",null,"CodeMirror-cursors"),n.measure=wo("div",null,"CodeMirror-measure"),n.lineMeasure=wo("div",null,"CodeMirror-measure"),n.lineSpace=wo("div",[n.measure,n.lineMeasure,n.selectionDiv,n.cursorDiv,n.lineDiv],null,"position: relative; outline: none"),n.mover=wo("div",[wo("div",[n.lineSpace],"CodeMirror-lines")],null,"position: relative"),n.sizer=wo("div",[n.mover],"CodeMirror-sizer"),n.heightForcer=wo("div",null,null,"position: absolute; height: "+hs+"px; width: 1px;"),n.gutters=wo("div",null,"CodeMirror-gutters"),n.lineGutter=null,n.scroller=wo("div",[n.sizer,n.heightForcer,n.gutters],"CodeMirror-scroll"),n.scroller.setAttribute("tabIndex","-1"),n.wrapper=wo("div",[n.inputDiv,n.scrollbarH,n.scrollbarV,n.scrollbarFiller,n.gutterFiller,n.scroller],"CodeMirror"),Zo&&8>ea&&(n.gutters.style.zIndex=-1,n.scroller.style.paddingRight=0),ua&&(r.style.width="0px"),ta||(n.scroller.draggable=!0),aa&&(n.inputDiv.style.height="1px",n.inputDiv.style.position="absolute"),Zo&&8>ea&&(n.scrollbarH.style.minHeight=n.scrollbarV.style.minWidth="18px"),e.appendChild?e.appendChild(n.wrapper):e(n.wrapper),n.viewFrom=n.viewTo=t.first,n.view=[],n.externalMeasured=null,n.viewOffset=0,n.lastSizeC=0,n.updateLineNumbers=null,n.lineNumWidth=n.lineNumInnerWidth=n.lineNumChars=null,n.prevInput="",n.alignWidgets=!1,n.pollingFast=!1,n.poll=new lo,n.cachedCharWidth=n.cachedTextHeight=n.cachedPaddingH=null,n.inaccurateSelection=!1,n.maxLine=null,n.maxLineLength=0,n.maxLineChanged=!1,n.wheelDX=n.wheelDY=n.wheelStartX=n.wheelStartY=null,n.shift=!1,n.selForContextMenu=null}function n(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption),r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.frontier=e.doc.first,St(e,100),e.state.modeGen++,e.curOp&&gn(e) }function i(e){e.options.lineWrapping?(Ao(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth=""):(Lo(e.display.wrapper,"CodeMirror-wrap"),h(e)),a(e),gn(e),Wt(e),setTimeout(function(){v(e)},100)}function o(e){var t=Kt(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/Qt(e.display)-3);return function(i){if(ni(e.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a<i.widgets.length;a++)i.widgets[a].height&&(o+=i.widgets[a].height);return n?o+(Math.ceil(i.text.length/r)||1)*t:o+t}}function a(e){var t=e.doc,n=o(e);t.iter(function(e){var t=n(e);t!=e.height&&ji(e,t)})}function s(e){var t=Ua[e.options.keyMap],n=t.style;e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(n?" cm-keymap-"+n:"")}function l(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Wt(e)}function u(e){c(e),gn(e),setTimeout(function(){b(e)},20)}function c(e){var t=e.display.gutters,n=e.options.gutters;So(t);for(var r=0;r<n.length;++r){var i=n[r],o=t.appendChild(wo("div",null,"CodeMirror-gutter "+i));"CodeMirror-linenumbers"==i&&(e.display.lineGutter=o,o.style.width=(e.display.lineNumWidth||1)+"px")}t.style.display=r?"":"none",f(e)}function f(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px",e.display.scrollbarH.style.left=e.options.fixedGutter?t+"px":0}function d(e){if(0==e.height)return 0;for(var t,n=e.text.length,r=e;t=Jr(r);){var i=t.find(0,!0);r=i.from.line,n+=i.from.ch-i.to.ch}for(r=e;t=Yr(r);){var i=t.find(0,!0);n-=r.text.length-i.from.ch,r=i.to.line,n+=r.text.length-i.to.ch}return n}function h(e){var t=e.display,n=e.doc;t.maxLine=_i(n,n.first),t.maxLineLength=d(t.maxLine),t.maxLineChanged=!0,n.iter(function(e){var n=d(e);n>t.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}function p(e){var t=ho(e.gutters,"CodeMirror-linenumbers");-1==t&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function g(e){return e.display.scroller.clientHeight-e.display.wrapper.clientHeight<hs-3}function m(e){var t=e.display.scroller;return{clientHeight:t.clientHeight,barHeight:e.display.scrollbarV.clientHeight,scrollWidth:t.scrollWidth,clientWidth:t.clientWidth,hScrollbarTakesSpace:g(e),barWidth:e.display.scrollbarH.clientWidth,docHeight:Math.round(e.doc.height+Lt(e.display))}}function v(e,t){t||(t=m(e));var n=e.display,r=jo(n.measure),i=t.docHeight+hs,o=t.scrollWidth>t.clientWidth;o&&t.scrollWidth<=t.clientWidth+1&&r>0&&!t.hScrollbarTakesSpace&&(o=!1);var a=i>t.clientHeight;if(a?(n.scrollbarV.style.display="block",n.scrollbarV.style.bottom=o?r+"px":"0",n.scrollbarV.firstChild.style.height=Math.max(0,i-t.clientHeight+(t.barHeight||n.scrollbarV.clientHeight))+"px"):(n.scrollbarV.style.display="",n.scrollbarV.firstChild.style.height="0"),o?(n.scrollbarH.style.display="block",n.scrollbarH.style.right=a?r+"px":"0",n.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||n.scrollbarH.clientWidth)+"px"):(n.scrollbarH.style.display="",n.scrollbarH.firstChild.style.width="0"),o&&a?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"):n.scrollbarFiller.style.display="",o&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r+"px",n.gutterFiller.style.width=n.gutters.offsetWidth+"px"):n.gutterFiller.style.display="",!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(0===r){var s=fa&&!sa?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=s;var l=function(t){eo(t)!=n.scrollbarV&&eo(t)!=n.scrollbarH&&cn(e,jn)(t)};us(n.scrollbarV,"mousedown",l),us(n.scrollbarH,"mousedown",l)}e.state.checkedOverlayScrollbar=!0}}function y(e,t,n){var r=n&&null!=n.top?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-kt(e));var i=n&&null!=n.bottom?n.bottom:r+e.wrapper.clientHeight,o=Hi(t,r),a=Hi(t,i);if(n&&n.ensure){var s=n.ensure.from.line,l=n.ensure.to.line;if(o>s)return{from:s,to:Hi(t,Oi(_i(t,s))+e.wrapper.clientHeight)};if(Math.min(l,t.lastLine())>=a)return{from:Hi(t,Oi(_i(t,l))-e.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(a,o+1)}}function b(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=S(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",a=0;a<n.length;a++)if(!n[a].hidden){e.options.fixedGutter&&n[a].gutter&&(n[a].gutter.style.left=o);var s=n[a].alignable;if(s)for(var l=0;l<s.length;l++)s[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+i+"px")}}function x(e){if(!e.options.lineNumbers)return!1;var t=e.doc,n=w(e.options,t.first+t.size-1),r=e.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(wo("div",[wo("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,a=i.offsetWidth-o;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-a),r.lineNumWidth=r.lineNumInnerWidth+a,r.lineNumChars=r.lineNumInnerWidth?n.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",f(e),!0}return!1}function w(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function S(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function C(e,t,n){var r=e.display;this.viewport=t,this.visible=y(r,e.doc,t),this.editorIsHidden=!r.wrapper.offsetWidth,this.wrapperHeight=r.wrapper.clientHeight,this.oldViewFrom=r.viewFrom,this.oldViewTo=r.viewTo,this.oldScrollerWidth=r.scroller.clientWidth,this.force=n,this.dims=M(e)}function T(e,t){var n=e.display,r=e.doc;if(t.editorIsHidden)return vn(e),!1;if(!t.force&&t.visible.from>=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&0==wn(e))return!1;x(e)&&(vn(e),t.dims=M(e));var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom)),n.viewTo>a&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo)),va&&(o=ei(e.doc,o),a=ti(e.doc,a));var s=o!=n.viewFrom||a!=n.viewTo||n.lastSizeC!=t.wrapperHeight;xn(e,o,a),n.viewOffset=Oi(_i(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var l=wn(e);if(!s&&0==l&&!t.force&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=Do();return l>4&&(n.lineDiv.style.display="none"),E(e,n.updateLineNumbers,t.dims),l>4&&(n.lineDiv.style.display=""),u&&Do()!=u&&u.offsetHeight&&u.focus(),So(n.cursorDiv),So(n.selectionDiv),s&&(n.lastSizeC=t.wrapperHeight,St(e,400)),n.updateLineNumbers=null,!0}function D(e,t){for(var n=t.force,r=t.viewport,i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldScrollerWidth!=e.display.scroller.clientWidth)n=!0;else if(n=!1,r&&null!=r.top&&(r={top:Math.min(e.doc.height+Lt(e.display)-hs-e.display.scroller.clientHeight,r.top)}),t.visible=y(e.display,e.doc,r),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!T(e,t))break;N(e);var o=m(e);yt(e),L(e,o),v(e,o)}no(e,"update",e),(e.display.viewFrom!=t.oldViewFrom||e.display.viewTo!=t.oldViewTo)&&no(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)}function k(e,t){var n=new C(e,t);if(T(e,n)){N(e),D(e,n);var r=m(e);yt(e),L(e,r),v(e,r)}}function L(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-hs)+"px"}function A(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth<e.display.scroller.clientWidth-1&&(e.display.sizer.style.minHeight=e.display.heightForcer.style.top="0px",e.display.gutters.style.height=t.docHeight+"px")}function N(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var i,o=t.view[r];if(!o.hidden){if(Zo&&8>ea){var a=o.node.offsetTop+o.node.offsetHeight;i=a-n,n=a}else{var s=o.node.getBoundingClientRect();i=s.bottom-s.top}var l=o.line.height-i;if(2>i&&(i=Kt(t)),(l>.001||-.001>l)&&(ji(o.line,i),_(o.line),o.rest))for(var u=0;u<o.rest.length;u++)_(o.rest[u])}}}function _(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function M(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a)n[e.options.gutters[a]]=o.offsetLeft+o.clientLeft+i,r[e.options.gutters[a]]=o.clientWidth;return{fixedPos:S(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function E(e,t,n){function r(t){var n=t.nextSibling;return ta&&fa&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var i=e.display,o=e.options.lineNumbers,a=i.lineDiv,s=a.firstChild,l=i.view,u=i.viewFrom,c=0;c<l.length;c++){var f=l[c];if(f.hidden);else if(f.node){for(;s!=f.node;)s=r(s);var d=o&&null!=t&&u>=t&&f.lineNumber;f.changes&&(ho(f.changes,"gutter")>-1&&(d=!1),j(e,f,u,n)),d&&(So(f.lineNumber),f.lineNumber.appendChild(document.createTextNode(w(e.options,u)))),s=f.node.nextSibling}else{var h=z(e,f,u,n);a.insertBefore(h,s)}u+=f.size}for(;s;)s=r(s)}function j(e,t,n,r){for(var i=0;i<t.changes.length;i++){var o=t.changes[i];"text"==o?R(e,t):"gutter"==o?F(e,t,n,r):"class"==o?P(t):"widget"==o&&W(t,r)}t.changes=null}function I(e){return e.node==e.text&&(e.node=wo("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),Zo&&8>ea&&(e.node.style.zIndex=2)),e.node}function H(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;if(t&&(t+=" CodeMirror-linebackground"),e.background)t?e.background.className=t:(e.background.parentNode.removeChild(e.background),e.background=null);else if(t){var n=I(e);e.background=n.insertBefore(wo("div",null,t),n.firstChild)}}function O(e,t){var n=e.display.externalMeasured;return n&&n.line==t.line?(e.display.externalMeasured=null,t.measure=n.measure,n.built):vi(e,t)}function R(e,t){var n=t.text.className,r=O(e,t);t.text==t.node&&(t.node=r.pre),t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,P(t)):n&&(t.text.className=n)}function P(e){H(e),e.line.wrapClass?I(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,n,r){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null);var i=t.line.gutterMarkers;if(e.options.lineNumbers||i){var o=I(t),a=t.gutter=o.insertBefore(wo("div",null,"CodeMirror-gutter-wrapper","position: absolute; left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px"),t.text);if(!e.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(t.lineNumber=a.appendChild(wo("div",w(e.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),i)for(var s=0;s<e.options.gutters.length;++s){var l=e.options.gutters[s],u=i.hasOwnProperty(l)&&i[l];u&&a.appendChild(wo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function W(e,t){e.alignable&&(e.alignable=null);for(var n,r=e.node.firstChild;r;r=n){var n=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}B(e,t)}function z(e,t,n,r){var i=O(e,t);return t.text=t.node=i.pre,i.bgClass&&(t.bgClass=i.bgClass),i.textClass&&(t.textClass=i.textClass),P(t),F(e,t,n,r),B(t,r),t.node}function B(e,t){if(q(e.line,e,t,!0),e.rest)for(var n=0;n<e.rest.length;n++)q(e.rest[n],e,t,!1)}function q(e,t,n,r){if(e.widgets)for(var i=I(t),o=0,a=e.widgets;o<a.length;++o){var s=a[o],l=wo("div",[s.node],"CodeMirror-linewidget");s.handleMouseEvents||(l.ignoreEvents=!0),U(s,l,t,n),r&&s.above?i.insertBefore(l,t.gutter||t.text):i.appendChild(l),no(s,"redraw")}}function U(e,t,n,r){if(e.noHScroll){(n.alignable||(n.alignable=[])).push(t);var i=r.wrapperWidth;t.style.left=r.fixedPos+"px",e.coverGutter||(i-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=i+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}function V(e){return ya(e.line,e.ch)}function X(e,t){return ba(e,t)<0?t:e}function G(e,t){return ba(e,t)<0?e:t}function $(e,t){this.ranges=e,this.primIndex=t}function J(e,t){this.anchor=e,this.head=t}function Y(e,t){var n=e[t];e.sort(function(e,t){return ba(e.from(),t.from())}),t=ho(e,n);for(var r=1;r<e.length;r++){var i=e[r],o=e[r-1];if(ba(o.to(),i.from())>=0){var a=G(o.from(),i.from()),s=X(o.to(),i.to()),l=o.empty()?i.from()==i.head:o.from()==o.head;t>=r&&--t,e.splice(--r,2,new J(l?s:a,l?a:s))}}return new $(e,t)}function K(e,t){return new $([new J(e,t||e)],0)}function Q(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function Z(e,t){if(t.line<e.first)return ya(e.first,0);var n=e.first+e.size-1;return t.line>n?ya(n,_i(e,n).text.length):et(t,_i(e,t.line).text.length)}function et(e,t){var n=e.ch;return null==n||n>t?ya(e.line,t):0>n?ya(e.line,0):e}function tt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var n=[],r=0;r<t.length;r++)n[r]=Z(e,t[r]);return n}function rt(e,t,n,r){if(e.cm&&e.cm.display.shift||e.extend){var i=t.anchor;if(r){var o=ba(n,i)<0;o!=ba(r,i)<0?(i=n,n=r):o!=ba(n,r)<0&&(n=r)}return new J(i,n)}return new J(r||n,n)}function it(e,t,n,r){ct(e,new $([rt(e,e.sel.primary(),t,n)],0),r)}function ot(e,t,n){for(var r=[],i=0;i<e.sel.ranges.length;i++)r[i]=rt(e,e.sel.ranges[i],t[i],null);var o=Y(r,e.sel.primIndex);ct(e,o,n)}function at(e,t,n,r){var i=e.sel.ranges.slice(0);i[t]=n,ct(e,Y(i,e.sel.primIndex),r)}function st(e,t,n,r){ct(e,K(t,n),r)}function lt(e,t){var n={ranges:t.ranges,update:function(t){this.ranges=[];for(var n=0;n<t.length;n++)this.ranges[n]=new J(Z(e,t[n].anchor),Z(e,t[n].head))}};return fs(e,"beforeSelectionChange",e,n),e.cm&&fs(e.cm,"beforeSelectionChange",e.cm,n),n.ranges!=t.ranges?Y(n.ranges,n.ranges.length-1):t}function ut(e,t,n){var r=e.history.done,i=fo(r);i&&i.ranges?(r[r.length-1]=t,ft(e,t,n)):ct(e,t,n)}function ct(e,t,n){ft(e,t,n),Ui(e,e.sel,e.cm?e.cm.curOp.id:0/0,n)}function ft(e,t,n){(ao(e,"beforeSelectionChange")||e.cm&&ao(e.cm,"beforeSelectionChange"))&&(t=lt(e,t));var r=n&&n.bias||(ba(t.primary().head,e.sel.primary().head)<0?-1:1);dt(e,pt(e,t,r,!0)),n&&n.scroll===!1||!e.cm||br(e.cm)}function dt(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0,oo(e.cm)),no(e,"cursorActivity",e))}function ht(e){dt(e,pt(e,e.sel,null,!1),gs)}function pt(e,t,n,r){for(var i,o=0;o<t.ranges.length;o++){var a=t.ranges[o],s=gt(e,a.anchor,n,r),l=gt(e,a.head,n,r);(i||s!=a.anchor||l!=a.head)&&(i||(i=t.ranges.slice(0,o)),i[o]=new J(s,l))}return i?Y(i,t.primIndex):t}function gt(e,t,n,r){var i=!1,o=t,a=n||1;e.cantEdit=!1;e:for(;;){var s=_i(e,o.line);if(s.markedSpans)for(var l=0;l<s.markedSpans.length;++l){var u=s.markedSpans[l],c=u.marker;if((null==u.from||(c.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(c.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r&&(fs(c,"beforeCursorEnter"),c.explicitlyCleared)){if(s.markedSpans){--l;continue}break}if(!c.atomic)continue;var f=c.find(0>a?-1:1);if(0==ba(f,o)&&(f.ch+=a,f.ch<0?f=f.line>e.first?Z(e,ya(f.line-1)):null:f.ch>s.text.length&&(f=f.line<e.first+e.size-1?ya(f.line+1,0):null),!f)){if(i)return r?(e.cantEdit=!0,ya(e.first,0)):gt(e,t,n,!0);i=!0,f=t,a=-a}o=f;continue e}}return o}}function mt(e){for(var t=e.display,n=e.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),a=0;a<n.sel.ranges.length;a++){var s=n.sel.ranges[a],l=s.empty();(l||e.options.showCursorWhenSelecting)&&bt(e,s,i),l||xt(e,s,o)}if(e.options.moveInputWithCursor){var u=Xt(e,n.sel.primary().head,"div"),c=t.wrapper.getBoundingClientRect(),f=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+f.top-c.top)),r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+f.left-c.left))}return r}function vt(e,t){Co(e.display.cursorDiv,t.cursors),Co(e.display.selectionDiv,t.selection),null!=t.teTop&&(e.display.inputDiv.style.top=t.teTop+"px",e.display.inputDiv.style.left=t.teLeft+"px")}function yt(e){vt(e,mt(e))}function bt(e,t,n){var r=Xt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),i=n.appendChild(wo("div"," ","CodeMirror-cursor"));if(i.style.left=r.left+"px",i.style.top=r.top+"px",i.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",r.other){var o=n.appendChild(wo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=r.other.left+"px",o.style.top=r.other.top+"px",o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function xt(e,t,n){function r(e,t,n,r){0>t&&(t=0),t=Math.round(t),r=Math.round(r),s.appendChild(wo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==n?c-e:n)+"px; height: "+(r-t)+"px"))}function i(t,n,i){function o(n,r){return Vt(e,ya(t,n),"div",f,r)}var s,l,f=_i(a,t),d=f.text.length;return Ro(Ri(f),n||0,null==i?d:i,function(e,t,a){var f,h,p,g=o(e,"left");if(e==t)f=g,h=p=g.left;else{if(f=o(t-1,"right"),"rtl"==a){var m=g;g=f,f=m}h=g.left,p=f.right}null==n&&0==e&&(h=u),f.top-g.top>3&&(r(h,g.top,null,g.bottom),h=u,g.bottom<f.top&&r(h,g.bottom,null,f.top)),null==i&&t==d&&(p=c),(!s||g.top<s.top||g.top==s.top&&g.left<s.left)&&(s=g),(!l||f.bottom>l.bottom||f.bottom==l.bottom&&f.right>l.right)&&(l=f),u+1>h&&(h=u),r(h,f.top,p-h,f.bottom)}),{start:s,end:l}}var o=e.display,a=e.doc,s=document.createDocumentFragment(),l=At(e.display),u=l.left,c=o.lineSpace.offsetWidth-l.right,f=t.from(),d=t.to();if(f.line==d.line)i(f.line,f.ch,d.ch);else{var h=_i(a,f.line),p=_i(a,d.line),g=Qr(h)==Qr(p),m=i(f.line,f.ch,g?h.text.length+1:null).end,v=i(d.line,g?0:null,d.ch).start;g&&(m.top<v.top-2?(r(m.right,m.top,null,m.bottom),r(u,v.top,v.left,v.bottom)):r(m.right,m.top,v.left-m.right,m.bottom)),m.bottom<v.top&&r(u,m.bottom,null,v.top)}n.appendChild(s)}function wt(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var n=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function St(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,vo(Ct,e))}function Ct(e){var t=e.doc;if(t.frontier<t.first&&(t.frontier=t.first),!(t.frontier>=e.display.viewTo)){var n=+new Date+e.options.workTime,r=za(t.mode,Dt(e,t.frontier)),i=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var a=o.styles,s=hi(e,o,r,!0);o.styles=s.styles;var l=o.styleClasses,u=s.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var c=!a||a.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),f=0;!c&&f<a.length;++f)c=a[f]!=o.styles[f];c&&i.push(t.frontier),o.stateAfter=za(t.mode,r)}else gi(e,o.text,r),o.stateAfter=t.frontier%5==0?za(t.mode,r):null;return++t.frontier,+new Date>n?(St(e,e.options.workDelay),!0):void 0}),i.length&&un(e,function(){for(var t=0;t<i.length;t++)mn(e,i[t],"text")})}}function Tt(e,t,n){for(var r,i,o=e.doc,a=n?-1:t-(e.doc.mode.innerMode?1e3:100),s=t;s>a;--s){if(s<=o.first)return o.first;var l=_i(o,s-1);if(l.stateAfter&&(!n||s<=o.frontier))return s;var u=ys(l.text,null,e.options.tabSize);(null==i||r>u)&&(i=s-1,r=u)}return i}function Dt(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return!0;var o=Tt(e,t,n),a=o>r.first&&_i(r,o-1).stateAfter;return a=a?za(r.mode,a):Ba(r.mode),r.iter(o,t,function(n){gi(e,n.text,a);var s=o==t-1||o%5==0||o>=i.viewFrom&&o<i.viewTo;n.stateAfter=s?za(r.mode,a):null,++o}),n&&(r.frontier=o),a}function kt(e){return e.lineSpace.offsetTop}function Lt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function At(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Co(e.measure,wo("pre","x")),n=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};return isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r),r}function Nt(e,t,n){var r=e.options.lineWrapping,i=r&&e.display.scroller.clientWidth;if(!t.measure.heights||r&&t.measure.width!=i){var o=t.measure.heights=[];if(r){t.measure.width=i;for(var a=t.text.firstChild.getClientRects(),s=0;s<a.length-1;s++){var l=a[s],u=a[s+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-n.top)}}o.push(n.bottom-n.top)}}function _t(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Ii(e.rest[r])>n)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Mt(e,t){t=Qr(t);var n=Ii(t),r=e.display.externalMeasured=new hn(e.doc,t,n);r.lineN=n;var i=r.built=vi(e,r);return r.text=i.pre,Co(e.display.lineMeasure,i.pre),r}function Et(e,t,n,r){return Ht(e,It(e,t),n,r)}function jt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[yn(e,t)];var n=e.display.externalMeasured;return n&&t>=n.lineN&&t<n.lineN+n.size?n:void 0}function It(e,t){var n=Ii(t),r=jt(e,n);r&&!r.text?r=null:r&&r.changes&&j(e,r,n,M(e)),r||(r=Mt(e,t));var i=_t(r,t,n);return{line:t,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Ht(e,t,n,r,i){t.before&&(n=-1);var o,a=n+(r||"");return t.cache.hasOwnProperty(a)?o=t.cache[a]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(Nt(e,t.view,t.rect),t.hasHeights=!0),o=Ot(e,t,n,r),o.bogus||(t.cache[a]=o)),{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}function Ot(e,t,n,r){for(var i,o,a,s,l=t.map,u=0;u<l.length;u+=3){var c=l[u],f=l[u+1];if(c>n?(o=0,a=1,s="left"):f>n?(o=n-c,a=o+1):(u==l.length-3||n==f&&l[u+3]>n)&&(a=f-c,o=a-1,n>=f&&(s="right")),null!=o){if(i=l[u+2],c==f&&r==(i.insertLeft?"left":"right")&&(s=r),"left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;)i=l[(u-=3)+2],s="left";if("right"==r&&o==f-c)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;)i=l[(u+=3)+2],s="right";break}}var d;if(3==i.nodeType){for(var u=0;4>u;u++){for(;o&&xo(t.line.text.charAt(c+o));)--o;for(;f>c+a&&xo(t.line.text.charAt(c+a));)++a;if(Zo&&9>ea&&0==o&&a==f-c)d=i.parentNode.getBoundingClientRect();else if(Zo&&e.options.lineWrapping){var h=ws(i,o,a).getClientRects();d=h.length?h["right"==r?h.length-1:0]:Ca}else d=ws(i,o,a).getBoundingClientRect()||Ca;if(d.left||d.right||0==o)break;a=o,o-=1,s="right"}Zo&&11>ea&&(d=Rt(e.display.measure,d))}else{o>0&&(s=r="right");var h;d=e.options.lineWrapping&&(h=i.getClientRects()).length>1?h["right"==r?h.length-1:0]:i.getBoundingClientRect()}if(Zo&&9>ea&&!o&&(!d||!d.left&&!d.right)){var p=i.parentNode.getClientRects()[0];d=p?{left:p.left,right:p.left+Qt(e.display),top:p.top,bottom:p.bottom}:Ca}for(var g=d.top-t.rect.top,m=d.bottom-t.rect.top,v=(g+m)/2,y=t.view.measure.heights,u=0;u<y.length-1&&!(v<y[u]);u++);var b=u?y[u-1]:0,x=y[u],w={left:("right"==s?d.right:d.left)-t.rect.left,right:("left"==s?d.left:d.right)-t.rect.left,top:b,bottom:x};return d.left||d.right||(w.bogus=!0),e.options.singleCursorHeightPerLine||(w.rtop=g,w.rbottom=m),w}function Rt(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Oo(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*r,bottom:t.bottom*r}}function Pt(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Ft(e){e.display.externalMeasure=null,So(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)Pt(e.display.view[t])}function Wt(e){Ft(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Bt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function qt(e,t,n,r){if(t.widgets)for(var i=0;i<t.widgets.length;++i)if(t.widgets[i].above){var o=oi(t.widgets[i]);n.top+=o,n.bottom+=o}if("line"==r)return n;r||(r="local");var a=Oi(t);if("local"==r?a+=kt(e.display):a-=e.display.viewOffset,"page"==r||"window"==r){var s=e.display.lineSpace.getBoundingClientRect();a+=s.top+("window"==r?0:Bt());var l=s.left+("window"==r?0:zt());n.left+=l,n.right+=l}return n.top+=a,n.bottom+=a,n}function Ut(e,t,n){if("div"==n)return t;var r=t.left,i=t.top;if("page"==n)r-=zt(),i-=Bt();else if("local"==n||!n){var o=e.display.sizer.getBoundingClientRect();r+=o.left,i+=o.top}var a=e.display.lineSpace.getBoundingClientRect();return{left:r-a.left,top:i-a.top}}function Vt(e,t,n,r,i){return r||(r=_i(e.doc,t.line)),qt(e,r,Et(e,r,t.ch,i),n)}function Xt(e,t,n,r,i,o){function a(t,a){var s=Ht(e,i,t,a?"right":"left",o);return a?s.left=s.right:s.right=s.left,qt(e,r,s,n)}function s(e,t){var n=l[t],r=n.level%2;return e==Po(n)&&t&&n.level<l[t-1].level?(n=l[--t],e=Fo(n)-(n.level%2?0:1),r=!0):e==Fo(n)&&t<l.length-1&&n.level<l[t+1].level&&(n=l[++t],e=Po(n)-n.level%2,r=!1),r&&e==n.to&&e>n.from?a(e-1):a(e,r)}r=r||_i(e.doc,t.line),i||(i=It(e,r));var l=Ri(r),u=t.ch;if(!l)return a(u);var c=Xo(l,u),f=s(u,c);return null!=Hs&&(f.other=s(u,Hs)),f}function Gt(e,t){var n=0,t=Z(e.doc,t);e.options.lineWrapping||(n=Qt(e.display)*t.ch);var r=_i(e.doc,t.line),i=Oi(r)+kt(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function $t(e,t,n,r){var i=ya(e,t);return i.xRel=r,n&&(i.outside=!0),i}function Jt(e,t,n){var r=e.doc;if(n+=e.display.viewOffset,0>n)return $t(r.first,0,!0,-1);var i=Hi(r,n),o=r.first+r.size-1;if(i>o)return $t(r.first+r.size-1,_i(r,o).text.length,!0,1);0>t&&(t=0);for(var a=_i(r,i);;){var s=Yt(e,a,i,t,n),l=Yr(a),u=l&&l.find(0,!0);if(!l||!(s.ch>u.from.ch||s.ch==u.from.ch&&s.xRel>0))return s;i=Ii(a=u.to.line)}}function Yt(e,t,n,r,i){function o(r){var i=Xt(e,ya(n,r),"line",t,u);return s=!0,a>i.bottom?i.left-l:a<i.top?i.left+l:(s=!1,i.left)}var a=i-Oi(t),s=!1,l=2*e.display.wrapper.clientWidth,u=It(e,t),c=Ri(t),f=t.text.length,d=Wo(t),h=zo(t),p=o(d),g=s,m=o(h),v=s;if(r>m)return $t(n,h,v,1);for(;;){if(c?h==d||h==$o(t,d,1):1>=h-d){for(var y=p>r||m-r>=r-p?d:h,b=r-(y==d?p:m);xo(t.text.charAt(y));)++y;var x=$t(n,y,y==d?g:v,-1>b?-1:b>1?1:0);return x}var w=Math.ceil(f/2),S=d+w;if(c){S=d;for(var C=0;w>C;++C)S=$o(t,S,1)}var T=o(S);T>r?(h=S,m=T,(v=s)&&(m+=1e3),f=w):(d=S,p=T,g=s,f-=w)}}function Kt(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==xa){xa=wo("pre");for(var t=0;49>t;++t)xa.appendChild(document.createTextNode("x")),xa.appendChild(wo("br"));xa.appendChild(document.createTextNode("x"))}Co(e.measure,xa);var n=xa.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),So(e.measure),n||1}function Qt(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=wo("span","xxxxxxxxxx"),n=wo("pre",[t]);Co(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function Zt(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Da},Ta?Ta.ops.push(e.curOp):e.curOp.ownsGroup=Ta={ops:[e.curOp],delayedCallbacks:[]}}function en(e){var t=e.delayedCallbacks,n=0;do{for(;n<t.length;n++)t[n]();for(var r=0;r<e.ops.length;r++){var i=e.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++](i.cm)}}while(n<t.length)}function tn(e){var t=e.curOp,n=t.ownsGroup;if(n)try{en(n)}finally{Ta=null;for(var r=0;r<n.ops.length;r++)n.ops[r].cm.curOp=null;nn(n)}}function nn(e){for(var t=e.ops,n=0;n<t.length;n++)rn(t[n]);for(var n=0;n<t.length;n++)on(t[n]);for(var n=0;n<t.length;n++)an(t[n]);for(var n=0;n<t.length;n++)sn(t[n]);for(var n=0;n<t.length;n++)ln(t[n])}function rn(e){var t=e.cm,n=t.display;e.updateMaxLine&&h(t),e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<n.viewFrom||e.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new C(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function on(e){e.updatedDisplay=e.mustUpdate&&T(e.cm,e.update)}function an(e){var t=e.cm,n=t.display;e.updatedDisplay&&N(t),e.barMeasure=m(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Et(t,n.maxLine,n.maxLine.text.length).left+3,e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo+hs-n.scroller.clientWidth)),(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=mt(t))}function sn(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft<t.doc.scrollLeft&&Bn(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0),t.display.maxLineChanged=!1),e.newSelectionNodes&&vt(t,e.newSelectionNodes),e.updatedDisplay&&L(t,e.barMeasure),(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure),e.selectionChanged&&wt(t),t.state.focused&&e.updateInput&&Dn(t,e.typing)}function ln(e){var t=e.cm,n=t.display,r=t.doc;if(null!=e.adjustWidthTo&&Math.abs(e.barMeasure.scrollWidth-t.display.scroller.scrollWidth)>1&&v(t),e.updatedDisplay&&D(t,e.update),null==n.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(n.wheelStartX=n.wheelStartY=null),null!=e.scrollTop&&(n.scroller.scrollTop!=e.scrollTop||e.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,e.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(null!=e.scrollLeft&&(n.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,e.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o,b(t)}if(e.scrollToPos){var a=gr(t,Z(r,e.scrollToPos.from),Z(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&pr(t,a)}var s=e.maybeHiddenMarkers,l=e.maybeUnhiddenMarkers;if(s)for(var u=0;u<s.length;++u)s[u].lines.length||fs(s[u],"hide");if(l)for(var u=0;u<l.length;++u)l[u].lines.length&&fs(l[u],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop),e.updatedDisplay&&ta&&(t.options.lineWrapping&&A(t,e.barMeasure),e.barMeasure.scrollWidth>e.barMeasure.clientWidth&&e.barMeasure.scrollWidth<e.barMeasure.clientWidth+1&&!g(t)&&v(t)),e.changeObjs&&fs(t,"changes",t,e.changeObjs)}function un(e,t){if(e.curOp)return t();Zt(e);try{return t()}finally{tn(e)}}function cn(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Zt(e);try{return t.apply(e,arguments)}finally{tn(e)}}}function fn(e){return function(){if(this.curOp)return e.apply(this,arguments);Zt(this);try{return e.apply(this,arguments)}finally{tn(this)}}}function dn(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Zt(t);try{return e.apply(this,arguments)}finally{tn(t)}}}function hn(e,t,n){this.line=t,this.rest=Zr(t),this.size=this.rest?Ii(fo(this.rest))-n+1:1,this.node=this.text=null,this.hidden=ni(e,t)}function pn(e,t,n){for(var r,i=[],o=t;n>o;o=r){var a=new hn(e.doc,_i(e.doc,o),o);r=o+a.size,i.push(a)}return i}function gn(e,t,n,r){null==t&&(t=e.doc.first),null==n&&(n=e.doc.first+e.doc.size),r||(r=0);var i=e.display;if(r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>t)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)va&&ei(e.doc,t)<i.viewTo&&vn(e);else if(n<=i.viewFrom)va&&ti(e.doc,n+r)>i.viewFrom?vn(e):(i.viewFrom+=r,i.viewTo+=r); else if(t<=i.viewFrom&&n>=i.viewTo)vn(e);else if(t<=i.viewFrom){var o=bn(e,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):vn(e)}else if(n>=i.viewTo){var o=bn(e,t,t,-1);o?(i.view=i.view.slice(0,o.index),i.viewTo=o.lineN):vn(e)}else{var a=bn(e,t,t,-1),s=bn(e,n,n+r,1);a&&s?(i.view=i.view.slice(0,a.index).concat(pn(e,a.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=r):vn(e)}var l=i.externalMeasured;l&&(n<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(i.externalMeasured=null))}function mn(e,t,n){e.curOp.viewChanged=!0;var r=e.display,i=e.display.externalMeasured;if(i&&t>=i.lineN&&t<i.lineN+i.size&&(r.externalMeasured=null),!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[yn(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==ho(a,n)&&a.push(n)}}}function vn(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function yn(e,t){if(t>=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var n=e.display.view,r=0;r<n.length;r++)if(t-=n[r].size,0>t)return r}function bn(e,t,n,r){var i,o=yn(e,t),a=e.display.view;if(!va||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var s=0,l=e.display.viewFrom;o>s;s++)l+=a[s].size;if(l!=t){if(r>0){if(o==a.length-1)return null;i=l+a[o].size-t,o++}else i=l-t;t+=i,n+=i}for(;ei(e.doc,n)!=n;){if(o==(0>r?0:a.length-1))return null;n+=r*a[o-(0>r?1:0)].size,o+=r}return{index:o,lineN:n}}function xn(e,t,n){var r=e.display,i=r.view;0==i.length||t>=r.viewTo||n<=r.viewFrom?(r.view=pn(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=pn(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(yn(e,t))),r.viewFrom=t,r.viewTo<n?r.view=r.view.concat(pn(e,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,yn(e,n)))),r.viewTo=n}function wn(e){for(var t=e.display.view,n=0,r=0;r<t.length;r++){var i=t[r];i.hidden||i.node&&!i.changes||++n}return n}function Sn(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Tn(e),e.state.focused&&Sn(e)})}function Cn(e){function t(){var r=Tn(e);r||n?(e.display.pollingFast=!1,Sn(e)):(n=!0,e.display.poll.set(60,t))}var n=!1;e.display.pollingFast=!0,e.display.poll.set(20,t)}function Tn(e){var t=e.display.input,n=e.display.prevInput,r=e.doc;if(!e.state.focused||Ms(t)&&!n||An(e)||e.options.disableInput)return!1;e.state.pasteIncoming&&e.state.fakedLastChar&&(t.value=t.value.substring(0,t.value.length-1),e.state.fakedLastChar=!1);var i=t.value;if(i==n&&!e.somethingSelected())return!1;if(Zo&&ea>=9&&e.display.inputHasSelection===i||fa&&/[\uf700-\uf7ff]/.test(i))return Dn(e),!1;var o=!e.curOp;o&&Zt(e),e.display.shift=!1,8203!=i.charCodeAt(0)||r.sel!=e.display.selForContextMenu||n||(n="​");for(var a=0,s=Math.min(n.length,i.length);s>a&&n.charCodeAt(a)==i.charCodeAt(a);)++a;var l=i.slice(a),u=_s(l),c=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(ka&&ka.join("\n")==l?c=r.sel.ranges.length%ka.length==0&&po(ka,_s):u.length==r.sel.ranges.length&&(c=po(u,function(e){return[e]})));for(var f=r.sel.ranges.length-1;f>=0;f--){var d=r.sel.ranges[f],h=d.from(),p=d.to();a<n.length?h=ya(h.line,h.ch-(n.length-a)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(p=ya(p.line,Math.min(_i(r,p.line).text.length,p.ch+fo(u).length)));var g=e.curOp.updateInput,m={from:h,to:p,text:c?c[f%c.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};if(sr(e.doc,m),no(e,"inputRead",e,m),l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!f||r.sel.ranges[f-1].head.line!=d.head.line)){var v=e.getModeAt(d.head),y=Ea(m);if(v.electricChars){for(var b=0;b<v.electricChars.length;b++)if(l.indexOf(v.electricChars.charAt(b))>-1){wr(e,y.line,"smart");break}}else v.electricInput&&v.electricInput.test(_i(r,y.line).text.slice(0,y.ch))&&wr(e,y.line,"smart")}}return br(e),e.curOp.updateInput=g,e.curOp.typing=!0,i.length>1e3||i.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=i,o&&tn(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function Dn(e,t){var n,r,i=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=i.sel.primary();n=Es&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var a=n?"-":r||e.getSelection();e.display.input.value=a,e.state.focused&&xs(e.display.input),Zo&&ea>=9&&(e.display.inputHasSelection=a)}else t||(e.display.prevInput=e.display.input.value="",Zo&&ea>=9&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=n}function kn(e){"nocursor"==e.options.readOnly||ca&&Do()==e.display.input||e.display.input.focus()}function Ln(e){e.state.focused||(kn(e),Qn(e))}function An(e){return e.options.readOnly||e.doc.cantEdit}function Nn(e){function t(){e.state.focused&&setTimeout(vo(kn,e),0)}function n(t){io(e,t)||ls(t)}function r(t){if(e.somethingSelected())ka=e.getSelections(),i.inaccurateSelection&&(i.prevInput="",i.inaccurateSelection=!1,i.input.value=ka.join("\n"),xs(i.input));else{for(var n=[],r=[],o=0;o<e.doc.sel.ranges.length;o++){var a=e.doc.sel.ranges[o].head.line,s={anchor:ya(a,0),head:ya(a+1,0)};r.push(s),n.push(e.getRange(s.anchor,s.head))}"cut"==t.type?e.setSelections(r,null,gs):(i.prevInput="",i.input.value=n.join("\n"),xs(i.input)),ka=n}"cut"==t.type&&(e.state.cutIncoming=!0)}var i=e.display;us(i.scroller,"mousedown",cn(e,jn)),Zo&&11>ea?us(i.scroller,"dblclick",cn(e,function(t){if(!io(e,t)){var n=En(e,t);if(n&&!Pn(e,t)&&!Mn(e.display,t)){as(t);var r=e.findWordAt(n);it(e.doc,r.anchor,r.head)}}})):us(i.scroller,"dblclick",function(t){io(e,t)||as(t)}),us(i.lineSpace,"selectstart",function(e){Mn(i,e)||as(e)}),ga||us(i.scroller,"contextmenu",function(t){er(e,t)}),us(i.scroller,"scroll",function(){i.scroller.clientHeight&&(zn(e,i.scroller.scrollTop),Bn(e,i.scroller.scrollLeft,!0),fs(e,"scroll",e))}),us(i.scrollbarV,"scroll",function(){i.scroller.clientHeight&&zn(e,i.scrollbarV.scrollTop)}),us(i.scrollbarH,"scroll",function(){i.scroller.clientHeight&&Bn(e,i.scrollbarH.scrollLeft)}),us(i.scroller,"mousewheel",function(t){qn(e,t)}),us(i.scroller,"DOMMouseScroll",function(t){qn(e,t)}),us(i.scrollbarH,"mousedown",t),us(i.scrollbarV,"mousedown",t),us(i.wrapper,"scroll",function(){i.wrapper.scrollTop=i.wrapper.scrollLeft=0}),us(i.input,"keyup",function(t){Yn.call(e,t)}),us(i.input,"input",function(){Zo&&ea>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),Cn(e)}),us(i.input,"keydown",cn(e,$n)),us(i.input,"keypress",cn(e,Kn)),us(i.input,"focus",vo(Qn,e)),us(i.input,"blur",vo(Zn,e)),e.options.dragDrop&&(us(i.scroller,"dragstart",function(t){Wn(e,t)}),us(i.scroller,"dragenter",n),us(i.scroller,"dragover",n),us(i.scroller,"drop",cn(e,Fn))),us(i.scroller,"paste",function(t){Mn(i,t)||(e.state.pasteIncoming=!0,kn(e),Cn(e))}),us(i.input,"paste",function(){if(ta&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=i.input.selectionStart,n=i.input.selectionEnd;i.input.value+="$",i.input.selectionEnd=n,i.input.selectionStart=t,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,Cn(e)}),us(i.input,"cut",r),us(i.input,"copy",r),aa&&us(i.sizer,"mouseup",function(){Do()==i.input&&i.input.blur(),kn(e)})}function _n(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function Mn(e,t){for(var n=eo(t);n!=e.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==e.sizer&&n!=e.mover)return!0}function En(e,t,n,r){var i=e.display;if(!n){var o=eo(t);if(o==i.scrollbarH||o==i.scrollbarV||o==i.scrollbarFiller||o==i.gutterFiller)return null}var a,s,l=i.lineSpace.getBoundingClientRect();try{a=t.clientX-l.left,s=t.clientY-l.top}catch(t){return null}var u,c=Jt(e,a,s);if(r&&1==c.xRel&&(u=_i(e.doc,c.line).text).length==c.ch){var f=ys(u,u.length,e.options.tabSize)-u.length;c=ya(c.line,Math.max(0,Math.round((a-At(e.display).left)/Qt(e.display))-f))}return c}function jn(e){if(!io(this,e)){var t=this,n=t.display;if(n.shift=e.shiftKey,Mn(n,e))return void(ta||(n.scroller.draggable=!1,setTimeout(function(){n.scroller.draggable=!0},100)));if(!Pn(t,e)){var r=En(t,e);switch(window.focus(),to(e)){case 1:r?In(t,e,r):eo(e)==n.scroller&&as(e);break;case 2:ta&&(t.state.lastMiddleDown=+new Date),r&&it(t.doc,r),setTimeout(vo(kn,t),20),as(e);break;case 3:ga&&er(t,e)}}}}function In(e,t,n){setTimeout(vo(Ln,e),0);var r,i=+new Date;Sa&&Sa.time>i-400&&0==ba(Sa.pos,n)?r="triple":wa&&wa.time>i-400&&0==ba(wa.pos,n)?(r="double",Sa={time:i,pos:n}):(r="single",wa={time:i,pos:n});var o=e.doc.sel,a=fa?t.metaKey:t.ctrlKey;e.options.dragDrop&&Ns&&!An(e)&&"single"==r&&o.contains(n)>-1&&o.somethingSelected()?Hn(e,t,n,a):On(e,t,n,r,a)}function Hn(e,t,n,r){var i=e.display,o=cn(e,function(a){ta&&(i.scroller.draggable=!1),e.state.draggingText=!1,cs(document,"mouseup",o),cs(i.scroller,"drop",o),Math.abs(t.clientX-a.clientX)+Math.abs(t.clientY-a.clientY)<10&&(as(a),r||it(e.doc,n),kn(e),Zo&&9==ea&&setTimeout(function(){document.body.focus(),kn(e)},20))});ta&&(i.scroller.draggable=!0),e.state.draggingText=o,i.scroller.dragDrop&&i.scroller.dragDrop(),us(document,"mouseup",o),us(i.scroller,"drop",o)}function On(e,t,n,r,i){function o(t){if(0!=ba(g,t))if(g=t,"rect"==r){for(var i=[],o=e.options.tabSize,a=ys(_i(u,n.line).text,n.ch,o),s=ys(_i(u,t.line).text,t.ch,o),l=Math.min(a,s),h=Math.max(a,s),p=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));m>=p;p++){var v=_i(u,p).text,y=uo(v,l,o);l==h?i.push(new J(ya(p,y),ya(p,y))):v.length>y&&i.push(new J(ya(p,y),ya(p,uo(v,h,o))))}i.length||i.push(new J(n,n)),ct(u,Y(d.ranges.slice(0,f).concat(i),f),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b=c,x=b.anchor,w=t;if("single"!=r){if("double"==r)var S=e.findWordAt(t);else var S=new J(ya(t.line,0),Z(u,ya(t.line+1,0)));ba(S.anchor,x)>0?(w=S.head,x=G(b.from(),S.anchor)):(w=S.anchor,x=X(b.to(),S.head))}var i=d.ranges.slice(0);i[f]=new J(Z(u,x),w),ct(u,Y(i,f),ms)}}function a(t){var n=++v,i=En(e,t,!0,"rect"==r);if(i)if(0!=ba(i,g)){Ln(e),o(i);var s=y(l,u);(i.line>=s.to||i.line<s.from)&&setTimeout(cn(e,function(){v==n&&a(t)}),150)}else{var c=t.clientY<m.top?-20:t.clientY>m.bottom?20:0;c&&setTimeout(cn(e,function(){v==n&&(l.scroller.scrollTop+=c,a(t))}),50)}}function s(t){v=1/0,as(t),kn(e),cs(document,"mousemove",b),cs(document,"mouseup",x),u.history.lastSelOrigin=null}var l=e.display,u=e.doc;as(t);var c,f,d=u.sel;if(i&&!t.shiftKey?(f=u.sel.contains(n),c=f>-1?u.sel.ranges[f]:new J(n,n)):c=u.sel.primary(),t.altKey)r="rect",i||(c=new J(n,n)),n=En(e,t,!0,!0),f=-1;else if("double"==r){var h=e.findWordAt(n);c=e.display.shift||u.extend?rt(u,c,h.anchor,h.head):h}else if("triple"==r){var p=new J(ya(n.line,0),Z(u,ya(n.line+1,0)));c=e.display.shift||u.extend?rt(u,c,p.anchor,p.head):p}else c=rt(u,c,n);i?f>-1?at(u,f,c,ms):(f=u.sel.ranges.length,ct(u,Y(u.sel.ranges.concat([c]),f),{scroll:!1,origin:"*mouse"})):(f=0,ct(u,new $([c],0),ms),d=u.sel);var g=n,m=l.wrapper.getBoundingClientRect(),v=0,b=cn(e,function(e){to(e)?a(e):s(e)}),x=cn(e,s);us(document,"mousemove",b),us(document,"mouseup",x)}function Rn(e,t,n,r,i){try{var o=t.clientX,a=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&as(t);var s=e.display,l=s.lineDiv.getBoundingClientRect();if(a>l.bottom||!ao(e,n))return Zi(t);a-=l.top-s.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var c=s.gutters.childNodes[u];if(c&&c.getBoundingClientRect().right>=o){var f=Hi(e.doc,a),d=e.options.gutters[u];return i(e,n,e,f,d,t),Zi(t)}}}function Pn(e,t){return Rn(e,t,"gutterClick",!0,no)}function Fn(e){var t=this;if(!io(t,e)&&!Mn(t.display,e)){as(e),Zo&&(La=+new Date);var n=En(t,e,!0),r=e.dataTransfer.files;if(n&&!An(t))if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),a=0,s=function(e,r){var s=new FileReader;s.onload=cn(t,function(){if(o[r]=s.result,++a==i){n=Z(t.doc,n);var e={from:n,to:n,text:_s(o.join("\n")),origin:"paste"};sr(t.doc,e),ut(t.doc,K(n,Ea(e)))}}),s.readAsText(e)},l=0;i>l;++l)s(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(n)>-1)return t.state.draggingText(e),void setTimeout(vo(kn,t),20);try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(fa?e.metaKey:e.ctrlKey))var u=t.listSelections();if(ft(t.doc,K(n,n)),u)for(var l=0;l<u.length;++l)hr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste"),kn(t)}}catch(e){}}}}function Wn(e,t){if(Zo&&(!e.state.draggingText||+new Date-La<100))return void ls(t);if(!io(e,t)&&!Mn(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.setDragImage&&!oa)){var n=wo("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",ia&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),ia&&n.parentNode.removeChild(n)}}function zn(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,Yo||k(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbarV.scrollTop!=t&&(e.display.scrollbarV.scrollTop=t),Yo&&k(e),St(e,100))}function Bn(e,t,n){(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)||(t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),e.doc.scrollLeft=t,b(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbarH.scrollLeft!=t&&(e.display.scrollbarH.scrollLeft=t))}function qn(e,t){var n=t.wheelDeltaX,r=t.wheelDeltaY;null==n&&t.detail&&t.axis==t.HORIZONTAL_AXIS&&(n=t.detail),null==r&&t.detail&&t.axis==t.VERTICAL_AXIS?r=t.detail:null==r&&(r=t.wheelDelta);var i=e.display,o=i.scroller;if(n&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&fa&&ta)e:for(var a=t.target,s=i.view;a!=o;a=a.parentNode)for(var l=0;l<s.length;l++)if(s[l].node==a){e.display.currentWheelTarget=a;break e}if(n&&!Yo&&!ia&&null!=Na)return r&&zn(e,Math.max(0,Math.min(o.scrollTop+r*Na,o.scrollHeight-o.clientHeight))),Bn(e,Math.max(0,Math.min(o.scrollLeft+n*Na,o.scrollWidth-o.clientWidth))),as(t),void(i.wheelStartX=null);if(r&&null!=Na){var u=r*Na,c=e.doc.scrollTop,f=c+i.wrapper.clientHeight;0>u?c=Math.max(0,c+u-50):f=Math.min(e.doc.height,f+u+50),k(e,{top:c,bottom:f})}20>Aa&&(null==i.wheelStartX?(i.wheelStartX=o.scrollLeft,i.wheelStartY=o.scrollTop,i.wheelDX=n,i.wheelDY=r,setTimeout(function(){if(null!=i.wheelStartX){var e=o.scrollLeft-i.wheelStartX,t=o.scrollTop-i.wheelStartY,n=t&&i.wheelDY&&t/i.wheelDY||e&&i.wheelDX&&e/i.wheelDX;i.wheelStartX=i.wheelStartY=null,n&&(Na=(Na*Aa+n)/(Aa+1),++Aa)}},200)):(i.wheelDX+=n,i.wheelDY+=r))}}function Un(e,t,n){if("string"==typeof t&&(t=qa[t],!t))return!1;e.display.pollingFast&&Tn(e)&&(e.display.pollingFast=!1);var r=e.display.shift,i=!1;try{An(e)&&(e.state.suppressEdits=!0),n&&(e.display.shift=!1),i=t(e)!=ps}finally{e.display.shift=r,e.state.suppressEdits=!1}return i}function Vn(e){var t=e.state.keyMaps.slice(0);return e.options.extraKeys&&t.push(e.options.extraKeys),t.push(e.options.keyMap),t}function Xn(e,t){var n=Lr(e.options.keyMap),r=n.auto;clearTimeout(_a),r&&!Xa(t)&&(_a=setTimeout(function(){Lr(e.options.keyMap)==n&&(e.options.keyMap=r.call?r.call(null,e):r,s(e))},50));var i=Ga(t,!0),o=!1;if(!i)return!1;var a=Vn(e);return o=t.shiftKey?Va("Shift-"+i,a,function(t){return Un(e,t,!0)})||Va(i,a,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Un(e,t):void 0}):Va(i,a,function(t){return Un(e,t)}),o&&(as(t),wt(e),no(e,"keyHandled",e,i,t)),o}function Gn(e,t,n){var r=Va("'"+n+"'",Vn(e),function(t){return Un(e,t,!0)});return r&&(as(t),wt(e),no(e,"keyHandled",e,"'"+n+"'",t)),r}function $n(e){var t=this;if(Ln(t),!io(t,e)){Zo&&11>ea&&27==e.keyCode&&(e.returnValue=!1);var n=e.keyCode;t.display.shift=16==n||e.shiftKey;var r=Xn(t,e);ia&&(Ma=r?n:null,!r&&88==n&&!Es&&(fa?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=n||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||Jn(t)}}function Jn(e){function t(e){18!=e.keyCode&&e.altKey||(Lo(n,"CodeMirror-crosshair"),cs(document,"keyup",t),cs(document,"mouseover",t))}var n=e.display.lineDiv;Ao(n,"CodeMirror-crosshair"),us(document,"keyup",t),us(document,"mouseover",t)}function Yn(e){16==e.keyCode&&(this.doc.sel.shift=!1),io(this,e)}function Kn(e){var t=this;if(!(io(t,e)||e.ctrlKey&&!e.altKey||fa&&e.metaKey)){var n=e.keyCode,r=e.charCode;if(ia&&n==Ma)return Ma=null,void as(e);if(!(ia&&(!e.which||e.which<10)||aa)||!Xn(t,e)){var i=String.fromCharCode(null==r?n:r);Gn(t,e,i)||(Zo&&ea>=9&&(t.display.inputHasSelection=null),Cn(t))}}}function Qn(e){"nocursor"!=e.options.readOnly&&(e.state.focused||(fs(e,"focus",e),e.state.focused=!0,Ao(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(Dn(e),ta&&setTimeout(vo(Dn,e,!0),0))),Sn(e),wt(e))}function Zn(e){e.state.focused&&(fs(e,"blur",e),e.state.focused=!1,Lo(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function er(e,t){function n(){if(null!=i.input.selectionStart){var t=e.somethingSelected(),n=i.input.value="​"+(t?i.input.value:"");i.prevInput=t?"":"​",i.input.selectionStart=1,i.input.selectionEnd=n.length,i.selForContextMenu=e.doc.sel}}function r(){if(i.inputDiv.style.position="relative",i.input.style.cssText=l,Zo&&9>ea&&(i.scrollbarV.scrollTop=i.scroller.scrollTop=a),Sn(e),null!=i.input.selectionStart){(!Zo||Zo&&9>ea)&&n();var t=0,r=function(){i.selForContextMenu==e.doc.sel&&0==i.input.selectionStart?cn(e,qa.selectAll)(e):t++<10?i.detectingSelectAll=setTimeout(r,500):Dn(e)};i.detectingSelectAll=setTimeout(r,200)}}if(!io(e,t,"contextmenu")){var i=e.display;if(!Mn(i,t)&&!tr(e,t)){var o=En(e,t),a=i.scroller.scrollTop;if(o&&!ia){var s=e.options.resetSelectionOnContextMenu;s&&-1==e.doc.sel.contains(o)&&cn(e,ct)(e.doc,K(o),gs);var l=i.input.style.cssText;if(i.inputDiv.style.position="absolute",i.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(Zo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",ta)var u=window.scrollY;if(kn(e),ta&&window.scrollTo(null,u),Dn(e),e.somethingSelected()||(i.input.value=i.prevInput=" "),i.selForContextMenu=e.doc.sel,clearTimeout(i.detectingSelectAll),Zo&&ea>=9&&n(),ga){ls(t);var c=function(){cs(window,"mouseup",c),setTimeout(r,20)};us(window,"mouseup",c)}else setTimeout(r,50)}}}}function tr(e,t){return ao(e,"gutterContextMenu")?Rn(e,t,"gutterContextMenu",!1,fs):!1}function nr(e,t){if(ba(e,t.from)<0)return e;if(ba(e,t.to)<=0)return Ea(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Ea(t).ch-t.to.ch),ya(n,r)}function rr(e,t){for(var n=[],r=0;r<e.sel.ranges.length;r++){var i=e.sel.ranges[r];n.push(new J(nr(i.anchor,t),nr(i.head,t)))}return Y(n,e.sel.primIndex)}function ir(e,t,n){return e.line==t.line?ya(n.line,e.ch-t.ch+n.ch):ya(n.line+(e.line-t.line),e.ch)}function or(e,t,n){for(var r=[],i=ya(e.first,0),o=i,a=0;a<t.length;a++){var s=t[a],l=ir(s.from,i,o),u=ir(Ea(s),i,o);if(i=s.to,o=u,"around"==n){var c=e.sel.ranges[a],f=ba(c.head,c.anchor)<0;r[a]=new J(f?u:l,f?l:u)}else r[a]=new J(l,l)}return new $(r,e.sel.primIndex)}function ar(e,t,n){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};return n&&(r.update=function(t,n,r,i){t&&(this.from=Z(e,t)),n&&(this.to=Z(e,n)),r&&(this.text=r),void 0!==i&&(this.origin=i)}),fs(e,"beforeChange",e,r),e.cm&&fs(e.cm,"beforeChange",e.cm,r),r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function sr(e,t,n){if(e.cm){if(!e.cm.curOp)return cn(e.cm,sr)(e,t,n);if(e.cm.state.suppressEdits)return}if(!(ao(e,"beforeChange")||e.cm&&ao(e.cm,"beforeChange"))||(t=ar(e,t,!0))){var r=ma&&!n&&Br(e,t.from,t.to);if(r)for(var i=r.length-1;i>=0;--i)lr(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text});else lr(e,t)}}function lr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ba(t.from,t.to)){var n=rr(e,t);Bi(e,t,n,e.cm?e.cm.curOp.id:0/0),fr(e,t,n,Fr(e,t));var r=[];Ai(e,function(e,n){n||-1!=ho(r,e.history)||(Qi(e.history,t),r.push(e.history)),fr(e,t,null,Fr(e,t))})}}function ur(e,t,n){if(!e.cm||!e.cm.state.suppressEdits){for(var r,i=e.history,o=e.sel,a="undo"==t?i.done:i.undone,s="undo"==t?i.undone:i.done,l=0;l<a.length&&(r=a[l],n?!r.ranges||r.equals(e.sel):r.ranges);l++);if(l!=a.length){for(i.lastOrigin=i.lastSelOrigin=null;r=a.pop(),r.ranges;){if(Vi(r,s),n&&!r.equals(e.sel))return void ct(e,r,{clearRedo:!1});o=r}var u=[];Vi(o,s),s.push({changes:u,generation:i.generation}),i.generation=r.generation||++i.maxGeneration;for(var c=ao(e,"beforeChange")||e.cm&&ao(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var f=r.changes[l];if(f.origin=t,c&&!ar(e,f,!1))return void(a.length=0);u.push(Fi(e,f));var d=l?rr(e,f):fo(a);fr(e,f,d,zr(e,f)),!l&&e.cm&&e.cm.scrollIntoView({from:f.from,to:Ea(f)});var h=[];Ai(e,function(e,t){t||-1!=ho(h,e.history)||(Qi(e.history,f),h.push(e.history)),fr(e,f,null,zr(e,f))})}}}}function cr(e,t){if(0!=t&&(e.first+=t,e.sel=new $(po(e.sel.ranges,function(e){return new J(ya(e.anchor.line+t,e.anchor.ch),ya(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){gn(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;r<n.viewTo;r++)mn(e.cm,r,"gutter")}}function fr(e,t,n,r){if(e.cm&&!e.cm.curOp)return cn(e.cm,fr)(e,t,n,r);if(t.to.line<e.first)return void cr(e,t.text.length-1-(t.to.line-t.from.line));if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var i=t.text.length-1-(e.first-t.from.line);cr(e,i),t={from:ya(e.first,0),to:ya(t.to.line+i,t.to.ch),text:[fo(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:ya(o,_i(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Mi(e,t.from,t.to),n||(n=rr(e,t)),e.cm?dr(e.cm,t,r):Di(e,t,r),ft(e,n,gs)}}function dr(e,t,n){var r=e.doc,i=e.display,a=t.from,s=t.to,l=!1,u=a.line;e.options.lineWrapping||(u=Ii(Qr(_i(r,a.line))),r.iter(u,s.line+1,function(e){return e==i.maxLine?(l=!0,!0):void 0})),r.sel.contains(t.from,t.to)>-1&&oo(e),Di(r,t,n,o(e)),e.options.lineWrapping||(r.iter(u,a.line+t.text.length,function(e){var t=d(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,a.line),St(e,400);var c=t.text.length-(s.line-a.line)-1;a.line!=s.line||1!=t.text.length||Ti(e.doc,t)?gn(e,a.line,s.line+1,c):mn(e,a.line,"text");var f=ao(e,"changes"),h=ao(e,"change");if(h||f){var p={from:a,to:s,text:t.text,removed:t.removed,origin:t.origin};h&&no(e,"change",e,p),f&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(p)}e.display.selForContextMenu=null}function hr(e,t,n,r,i){if(r||(r=n),ba(r,n)<0){var o=r;r=n,n=o}"string"==typeof t&&(t=_s(t)),sr(e,{from:n,to:r,text:t,origin:i})}function pr(e,t){var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;if(t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!la){var o=wo("div","​",null,"position: absolute; top: "+(t.top-n.viewOffset-kt(e.display))+"px; height: "+(t.bottom-t.top+hs)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}function gr(e,t,n,r){null==r&&(r=0);for(var i=0;5>i;i++){var o=!1,a=Xt(e,t),s=n&&n!=t?Xt(e,n):a,l=vr(e,Math.min(a.left,s.left),Math.min(a.top,s.top)-r,Math.max(a.left,s.left),Math.max(a.bottom,s.bottom)+r),u=e.doc.scrollTop,c=e.doc.scrollLeft;if(null!=l.scrollTop&&(zn(e,l.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(o=!0)),null!=l.scrollLeft&&(Bn(e,l.scrollLeft),Math.abs(e.doc.scrollLeft-c)>1&&(o=!0)),!o)return a}}function mr(e,t,n,r,i){var o=vr(e,t,n,r,i);null!=o.scrollTop&&zn(e,o.scrollTop),null!=o.scrollLeft&&Bn(e,o.scrollLeft)}function vr(e,t,n,r,i){var o=e.display,a=Kt(e.display);0>n&&(n=0);var s=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-hs,u={};i-n>l&&(i=n+l);var c=e.doc.height+Lt(o),f=a>n,d=i>c-a;if(s>n)u.scrollTop=f?0:n;else if(i>s+l){var h=Math.min(n,(d?c:i)-l);h!=s&&(u.scrollTop=h)}var p=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,g=o.scroller.clientWidth-hs-o.gutters.offsetWidth,m=r-t>g;return m&&(r=t+g),10>t?u.scrollLeft=0:p>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>g+p-3&&(u.scrollLeft=r+(m?0:10)-g),u}function yr(e,t,n){(null!=t||null!=n)&&xr(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=n&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+n)}function br(e){xr(e);var t=e.getCursor(),n=t,r=t;e.options.lineWrapping||(n=t.ch?ya(t.line,t.ch-1):t,r=ya(t.line,t.ch+1)),e.curOp.scrollToPos={from:n,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function xr(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var n=Gt(e,t.from),r=Gt(e,t.to),i=vr(e,Math.min(n.left,r.left),Math.min(n.top,r.top)-t.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+t.margin);e.scrollTo(i.scrollLeft,i.scrollTop)}}function wr(e,t,n,r){var i,o=e.doc;null==n&&(n="add"),"smart"==n&&(o.mode.indent?i=Dt(e,t):n="prev");var a=e.options.tabSize,s=_i(o,t),l=ys(s.text,null,a);s.stateAfter&&(s.stateAfter=null);var u,c=s.text.match(/^\s*/)[0];if(r||/\S/.test(s.text)){if("smart"==n&&(u=o.mode.indent(i,s.text.slice(c.length),s.text),u==ps||u>150)){if(!r)return;n="prev"}}else u=0,n="not";"prev"==n?u=t>o.first?ys(_i(o,t-1).text,null,a):0:"add"==n?u=l+e.options.indentUnit:"subtract"==n?u=l-e.options.indentUnit:"number"==typeof n&&(u=l+n),u=Math.max(0,u);var f="",d=0;if(e.options.indentWithTabs)for(var h=Math.floor(u/a);h;--h)d+=a,f+=" ";if(u>d&&(f+=co(u-d)),f!=c)hr(o,f,ya(t,0),ya(t,c.length),"+input");else for(var h=0;h<o.sel.ranges.length;h++){var p=o.sel.ranges[h];if(p.head.line==t&&p.head.ch<c.length){var d=ya(t,c.length);at(o,h,new J(d,d));break}}s.stateAfter=null}function Sr(e,t,n,r){var i=t,o=t;return"number"==typeof t?o=_i(e,Q(e,t)):i=Ii(t),null==i?null:(r(o,i)&&e.cm&&mn(e.cm,i,n),o)}function Cr(e,t){for(var n=e.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=t(n[i]);r.length&&ba(o.from,fo(r).to)<=0;){var a=r.pop();if(ba(a.from,o.from)<0){o.from=a.from;break}}r.push(o)}un(e,function(){for(var t=r.length-1;t>=0;t--)hr(e.doc,"",r[t].from,r[t].to,"+delete");br(e)})}function Tr(e,t,n,r,i){function o(){var t=s+n;return t<e.first||t>=e.first+e.size?f=!1:(s=t,c=_i(e,t))}function a(e){var t=(i?$o:Jo)(c,l,n,!0);if(null==t){if(e||!o())return f=!1;l=i?(0>n?zo:Wo)(c):0>n?c.text.length:0}else l=t;return!0}var s=t.line,l=t.ch,u=n,c=_i(e,s),f=!0;if("char"==r)a();else if("column"==r)a(!0);else if("word"==r||"group"==r)for(var d=null,h="group"==r,p=e.cm&&e.cm.getHelper(t,"wordChars"),g=!0;!(0>n)||a(!g);g=!1){var m=c.text.charAt(l)||"\n",v=yo(m,p)?"w":h&&"\n"==m?"n":!h||/\s/.test(m)?null:"p";if(!h||g||v||(v="s"),d&&d!=v){0>n&&(n=1,a());break}if(v&&(d=v),n>0&&!a(!g))break}var y=gt(e,ya(s,l),u,!0);return f||(y.hitSide=!0),y}function Dr(e,t,n,r){var i,o=e.doc,a=t.left;if("page"==r){var s=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);i=t.top+n*(s-(0>n?1.5:.5)*Kt(e.display))}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(;;){var l=Jt(e,a,i);if(!l.outside)break;if(0>n?0>=i:i>=o.height){l.hitSide=!0;break}i+=5*n}return l}function kr(t,n,r,i){e.defaults[t]=n,r&&(Ia[t]=i?function(e,t,n){n!=Ha&&r(e,t,n)}:r)}function Lr(e){return"string"==typeof e?Ua[e]:e}function Ar(e,t,n,r,i){if(r&&r.shared)return Nr(e,t,n,r,i);if(e.cm&&!e.cm.curOp)return cn(e.cm,Ar)(e,t,n,r,i);var o=new Ja(e,i),a=ba(t,n);if(r&&mo(r,o,!1),a>0||0==a&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=wo("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Kr(e,t.line,t,n,o)||t.line!=n.line&&Kr(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");va=!0}o.addToHistory&&Bi(e,{from:t,to:n,origin:"markText"},e.sel,0/0);var s,l=t.line,u=e.cm;if(e.iter(l,n.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&Qr(e)==u.display.maxLine&&(s=!0),o.collapsed&&l!=t.line&&ji(e,0),Or(e,new jr(o,l==t.line?t.ch:null,l==n.line?n.ch:null)),++l}),o.collapsed&&e.iter(t.line,n.line+1,function(t){ni(e,t)&&ji(t,0)}),o.clearOnEnter&&us(o,"beforeCursorEnter",function(){o.clear()}),o.readOnly&&(ma=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++Ya,o.atomic=!0),u){if(s&&(u.curOp.updateMaxLine=!0),o.collapsed)gn(u,t.line,n.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var c=t.line;c<=n.line;c++)mn(u,c,"text");o.atomic&&ht(u.doc),no(u,"markerAdded",u,o)}return o}function Nr(e,t,n,r,i){r=mo(r),r.shared=!1;var o=[Ar(e,t,n,r,i)],a=o[0],s=r.widgetNode;return Ai(e,function(e){s&&(r.widgetNode=s.cloneNode(!0)),o.push(Ar(e,Z(e,t),Z(e,n),r,i));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;a=fo(o)}),new Ka(o,a)}function _r(e){return e.findMarks(ya(e.first,0),e.clipPos(ya(e.lastLine())),function(e){return e.parent})}function Mr(e,t){for(var n=0;n<t.length;n++){var r=t[n],i=r.find(),o=e.clipPos(i.from),a=e.clipPos(i.to);if(ba(o,a)){var s=Ar(e,o,a,r.primary,r.primary.type);r.markers.push(s),s.parent=r}}}function Er(e){for(var t=0;t<e.length;t++){var n=e[t],r=[n.primary.doc];Ai(n.primary.doc,function(e){r.push(e)});for(var i=0;i<n.markers.length;i++){var o=n.markers[i];-1==ho(r,o.doc)&&(o.parent=null,n.markers.splice(i--,1))}}}function jr(e,t,n){this.marker=e,this.from=t,this.to=n}function Ir(e,t){if(e)for(var n=0;n<e.length;++n){var r=e[n];if(r.marker==t)return r}}function Hr(e,t){for(var n,r=0;r<e.length;++r)e[r]!=t&&(n||(n=[])).push(e[r]);return n}function Or(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}function Rr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],a=o.marker,s=null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t);if(s||o.from==t&&"bookmark"==a.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(a.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new jr(a,o.from,l?null:o.to))}}return r}function Pr(e,t,n){if(e)for(var r,i=0;i<e.length;++i){var o=e[i],a=o.marker,s=null==o.to||(a.inclusiveRight?o.to>=t:o.to>t);if(s||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new jr(a,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function Fr(e,t){var n=tt(e,t.from.line)&&_i(e,t.from.line).markedSpans,r=tt(e,t.to.line)&&_i(e,t.to.line).markedSpans;if(!n&&!r)return null;var i=t.from.ch,o=t.to.ch,a=0==ba(t.from,t.to),s=Rr(n,i,a),l=Pr(r,o,a),u=1==t.text.length,c=fo(t.text).length+(u?i:0);if(s)for(var f=0;f<s.length;++f){var d=s[f];if(null==d.to){var h=Ir(l,d.marker);h?u&&(d.to=null==h.to?null:h.to+c):d.to=i}}if(l)for(var f=0;f<l.length;++f){var d=l[f];if(null!=d.to&&(d.to+=c),null==d.from){var h=Ir(s,d.marker);h||(d.from=c,u&&(s||(s=[])).push(d))}else d.from+=c,u&&(s||(s=[])).push(d)}s&&(s=Wr(s)),l&&l!=s&&(l=Wr(l));var p=[s];if(!u){var g,m=t.text.length-2;if(m>0&&s)for(var f=0;f<s.length;++f)null==s[f].to&&(g||(g=[])).push(new jr(s[f].marker,null,null));for(var f=0;m>f;++f)p.push(g);p.push(l)}return p}function Wr(e){for(var t=0;t<e.length;++t){var n=e[t];null!=n.from&&n.from==n.to&&n.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function zr(e,t){var n=$i(e,t),r=Fr(e,t);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],a=r[i];if(o&&a)e:for(var s=0;s<a.length;++s){for(var l=a[s],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else a&&(n[i]=a)}return n}function Br(e,t,n){var r=null;if(e.iter(t.line,n.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var n=e.markedSpans[t].marker;!n.readOnly||r&&-1!=ho(r,n)||(r||(r=[])).push(n)}}),!r)return null;for(var i=[{from:t,to:n}],o=0;o<r.length;++o)for(var a=r[o],s=a.find(0),l=0;l<i.length;++l){var u=i[l]; if(!(ba(u.to,s.from)<0||ba(u.from,s.to)>0)){var c=[l,1],f=ba(u.from,s.from),d=ba(u.to,s.to);(0>f||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from}),(d>0||!a.inclusiveRight&&!d)&&c.push({from:s.to,to:u.to}),i.splice.apply(i,c),l+=c.length-1}}return i}function qr(e){var t=e.markedSpans;if(t){for(var n=0;n<t.length;++n)t[n].marker.detachLine(e);e.markedSpans=null}}function Ur(e,t){if(t){for(var n=0;n<t.length;++n)t[n].marker.attachLine(e);e.markedSpans=t}}function Vr(e){return e.inclusiveLeft?-1:0}function Xr(e){return e.inclusiveRight?1:0}function Gr(e,t){var n=e.lines.length-t.lines.length;if(0!=n)return n;var r=e.find(),i=t.find(),o=ba(r.from,i.from)||Vr(e)-Vr(t);if(o)return-o;var a=ba(r.to,i.to)||Xr(e)-Xr(t);return a?a:t.id-e.id}function $r(e,t){var n,r=va&&e.markedSpans;if(r)for(var i,o=0;o<r.length;++o)i=r[o],i.marker.collapsed&&null==(t?i.from:i.to)&&(!n||Gr(n,i.marker)<0)&&(n=i.marker);return n}function Jr(e){return $r(e,!0)}function Yr(e){return $r(e,!1)}function Kr(e,t,n,r,i){var o=_i(e,t),a=va&&o.markedSpans;if(a)for(var s=0;s<a.length;++s){var l=a[s];if(l.marker.collapsed){var u=l.marker.find(0),c=ba(u.from,n)||Vr(l.marker)-Vr(i),f=ba(u.to,r)||Xr(l.marker)-Xr(i);if(!(c>=0&&0>=f||0>=c&&f>=0)&&(0>=c&&(ba(u.to,n)>0||l.marker.inclusiveRight&&i.inclusiveLeft)||c>=0&&(ba(u.from,r)<0||l.marker.inclusiveLeft&&i.inclusiveRight)))return!0}}}function Qr(e){for(var t;t=Jr(e);)e=t.find(-1,!0).line;return e}function Zr(e){for(var t,n;t=Yr(e);)e=t.find(1,!0).line,(n||(n=[])).push(e);return n}function ei(e,t){var n=_i(e,t),r=Qr(n);return n==r?t:Ii(r)}function ti(e,t){if(t>e.lastLine())return t;var n,r=_i(e,t);if(!ni(e,r))return t;for(;n=Yr(r);)r=n.find(1,!0).line;return Ii(r)+1}function ni(e,t){var n=va&&t.markedSpans;if(n)for(var r,i=0;i<n.length;++i)if(r=n[i],r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&ri(e,t,r))return!0}}function ri(e,t,n){if(null==n.to){var r=n.marker.find(1,!0);return ri(e,r.line,Ir(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==t.text.length)return!0;for(var i,o=0;o<t.markedSpans.length;++o)if(i=t.markedSpans[o],i.marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&ri(e,t,i))return!0}function ii(e,t,n){Oi(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&yr(e,null,n)}function oi(e){if(null!=e.height)return e.height;if(!To(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.getGutterElement().offsetWidth+"px;"),Co(e.cm.display.measure,wo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function ai(e,t,n,r){var i=new Qa(e,n,r);return i.noHScroll&&(e.display.alignWidgets=!0),Sr(e.doc,t,"widget",function(t){var n=t.widgets||(t.widgets=[]);if(null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i),i.line=t,!ni(e.doc,t)){var r=Oi(t)<e.doc.scrollTop;ji(t,t.height+oi(i)),r&&yr(e,null,i.height),e.curOp.forceUpdate=!0}return!0}),i}function si(e,t,n,r){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),qr(e),Ur(e,n);var i=r?r(e):1;i!=e.height&&ji(e,i)}function li(e){e.parent=null,qr(e)}function ui(e,t){if(e)for(;;){var n=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;e=e.slice(0,n.index)+e.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==t[r]?t[r]=n[2]:new RegExp("(?:^|s)"+n[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+n[2])}return e}function ci(t,n){if(t.blankLine)return t.blankLine(n);if(t.innerMode){var r=e.innerMode(t,n);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function fi(e,t,n){for(var r=0;10>r;r++){var i=e.token(t,n);if(t.pos>t.start)return i}throw new Error("Mode "+e.name+" failed to advance stream.")}function di(t,n,r,i,o,a,s){var l=r.flattenSpans;null==l&&(l=t.options.flattenSpans);var u,c=0,f=null,d=new $a(n,t.options.tabSize);for(""==n&&ui(ci(r,i),a);!d.eol();){if(d.pos>t.options.maxHighlightLength?(l=!1,s&&gi(t,n,i,d.pos),d.pos=n.length,u=null):u=ui(fi(r,d,i),a),t.options.addModeClass){var h=e.innerMode(r,i).mode.name;h&&(u="m-"+(u?h+" "+u:h))}l&&f==u||(c<d.start&&o(d.start,f),c=d.start,f=u),d.start=d.pos}for(;c<d.pos;){var p=Math.min(d.pos,c+5e4);o(p,f),c=p}}function hi(e,t,n,r){var i=[e.state.modeGen],o={};di(e,t.text,e.doc.mode,n,function(e,t){i.push(e,t)},o,r);for(var a=0;a<e.state.overlays.length;++a){var s=e.state.overlays[a],l=1,u=0;di(e,t.text,s.mode,!0,function(e,t){for(var n=l;e>u;){var r=i[l];r>e&&i.splice(l,1,e,i[l+1],r),l+=2,u=Math.min(e,r)}if(t)if(s.opaque)i.splice(n,l-n,e,"cm-overlay "+t),l=n+2;else for(;l>n;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:i,classes:o.bgClass||o.textClass?o:null}}function pi(e,t){if(!t.styles||t.styles[0]!=e.state.modeGen){var n=hi(e,t,t.stateAfter=Dt(e,Ii(t)));t.styles=n.styles,n.classes?t.styleClasses=n.classes:t.styleClasses&&(t.styleClasses=null)}return t.styles}function gi(e,t,n,r){var i=e.doc.mode,o=new $a(t,e.options.tabSize);for(o.start=o.pos=r||0,""==t&&ci(i,n);!o.eol()&&o.pos<=e.options.maxHighlightLength;)fi(i,o,n),o.start=o.pos}function mi(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?ts:es;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function vi(e,t){var n=wo("span",null,null,ta?"padding-right: .1px":null),r={pre:wo("pre",[n]),content:n,col:0,pos:0,cm:e};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o,a=i?t.rest[i-1]:t.line;r.pos=0,r.addToken=bi,(Zo||ta)&&e.getOption("lineWrapping")&&(r.addToken=xi(r.addToken)),Ho(e.display.measure)&&(o=Ri(a))&&(r.addToken=wi(r.addToken,o)),r.map=[],Ci(a,r,pi(e,a)),a.styleClasses&&(a.styleClasses.bgClass&&(r.bgClass=No(a.styleClasses.bgClass,r.bgClass||"")),a.styleClasses.textClass&&(r.textClass=No(a.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Io(e.display.measure))),0==i?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return fs(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=No(r.pre.className,r.textClass||"")),r}function yi(e){var t=wo("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t}function bi(e,t,n,r,i,o){if(t){var a=e.cm.options.specialChars,s=!1;if(a.test(t))for(var l=document.createDocumentFragment(),u=0;;){a.lastIndex=u;var c=a.exec(t),f=c?c.index-u:t.length-u;if(f){var d=document.createTextNode(t.slice(u,u+f));l.appendChild(Zo&&9>ea?wo("span",[d]):d),e.map.push(e.pos,e.pos+f,d),e.col+=f,e.pos+=f}if(!c)break;if(u+=f+1," "==c[0]){var h=e.cm.options.tabSize,p=h-e.col%h,d=l.appendChild(wo("span",co(p),"cm-tab"));e.col+=p}else{var d=e.cm.options.specialCharPlaceholder(c[0]);l.appendChild(Zo&&9>ea?wo("span",[d]):d),e.col+=1}e.map.push(e.pos,e.pos+1,d),e.pos++}else{e.col+=t.length;var l=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,l),Zo&&9>ea&&(s=!0),e.pos+=t.length}if(n||r||i||s){var g=n||"";r&&(g+=r),i&&(g+=i);var m=wo("span",[l],g);return o&&(m.title=o),e.content.appendChild(m)}e.content.appendChild(l)}}function xi(e){function t(e){for(var t=" ",n=0;n<e.length-2;++n)t+=n%2?" ":" ";return t+=" "}return function(n,r,i,o,a,s){e(n,r.replace(/ {3,}/g,t),i,o,a,s)}}function wi(e,t){return function(n,r,i,o,a,s){i=i?i+" cm-force-border":"cm-force-border";for(var l=n.pos,u=l+r.length;;){for(var c=0;c<t.length;c++){var f=t[c];if(f.to>l&&f.from<=l)break}if(f.to>=u)return e(n,r,i,o,a,s);e(n,r.slice(0,f.to-l),i,o,null,s),o=null,r=r.slice(f.to-l),l=f.to}}}function Si(e,t,n,r){var i=!r&&n.widgetNode;i&&(e.map.push(e.pos,e.pos+t,i),e.content.appendChild(i)),e.pos+=t}function Ci(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var a,s,l,u,c,f,d=i.length,h=0,p=1,g="",m=0;;){if(m==h){s=l=u=c="",f=null,m=1/0;for(var v=[],y=0;y<r.length;++y){var b=r[y],x=b.marker;b.from<=h&&(null==b.to||b.to>h)?(null!=b.to&&m>b.to&&(m=b.to,l=""),x.className&&(s+=" "+x.className),x.startStyle&&b.from==h&&(u+=" "+x.startStyle),x.endStyle&&b.to==m&&(l+=" "+x.endStyle),x.title&&!c&&(c=x.title),x.collapsed&&(!f||Gr(f.marker,x)<0)&&(f=b)):b.from>h&&m>b.from&&(m=b.from),"bookmark"==x.type&&b.from==h&&x.widgetNode&&v.push(x)}if(f&&(f.from||0)==h&&(Si(t,(null==f.to?d+1:f.to)-h,f.marker,null==f.from),null==f.to))return;if(!f&&v.length)for(var y=0;y<v.length;++y)Si(t,0,v[y])}if(h>=d)break;for(var w=Math.min(d,m);;){if(g){var S=h+g.length;if(!f){var C=S>w?g.slice(0,w-h):g;t.addToken(t,C,a?a+s:s,u,h+C.length==m?l:"",c)}if(S>=w){g=g.slice(w-h),h=w;break}h=S,u=""}g=i.slice(o,o=n[p++]),a=mi(n[p++],t.cm.options)}}else for(var p=1;p<n.length;p+=2)t.addToken(t,i.slice(o,o=n[p]),mi(n[p+1],t.cm.options))}function Ti(e,t){return 0==t.from.ch&&0==t.to.ch&&""==fo(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Di(e,t,n,r){function i(e){return n?n[e]:null}function o(e,n,i){si(e,n,i,r),no(e,"change",e,t)}var a=t.from,s=t.to,l=t.text,u=_i(e,a.line),c=_i(e,s.line),f=fo(l),d=i(l.length-1),h=s.line-a.line;if(Ti(e,t)){for(var p=0,g=[];p<l.length-1;++p)g.push(new Za(l[p],i(p),r));o(c,c.text,d),h&&e.remove(a.line,h),g.length&&e.insert(a.line,g)}else if(u==c)if(1==l.length)o(u,u.text.slice(0,a.ch)+f+u.text.slice(s.ch),d);else{for(var g=[],p=1;p<l.length-1;++p)g.push(new Za(l[p],i(p),r));g.push(new Za(f+u.text.slice(s.ch),d,r)),o(u,u.text.slice(0,a.ch)+l[0],i(0)),e.insert(a.line+1,g)}else if(1==l.length)o(u,u.text.slice(0,a.ch)+l[0]+c.text.slice(s.ch),i(0)),e.remove(a.line+1,h);else{o(u,u.text.slice(0,a.ch)+l[0],i(0)),o(c,f+c.text.slice(s.ch),d);for(var p=1,g=[];p<l.length-1;++p)g.push(new Za(l[p],i(p),r));h>1&&e.remove(a.line+1,h-1),e.insert(a.line+1,g)}no(e,"change",e,t)}function ki(e){this.lines=e,this.parent=null;for(var t=0,n=0;t<e.length;++t)e[t].parent=this,n+=e[t].height;this.height=n}function Li(e){this.children=e;for(var t=0,n=0,r=0;r<e.length;++r){var i=e[r];t+=i.chunkSize(),n+=i.height,i.parent=this}this.size=t,this.height=n,this.parent=null}function Ai(e,t,n){function r(e,i,o){if(e.linked)for(var a=0;a<e.linked.length;++a){var s=e.linked[a];if(s.doc!=i){var l=o&&s.sharedHist;(!n||l)&&(t(s.doc,l),r(s.doc,e,l))}}}r(e,null,!0)}function Ni(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,a(e),n(e),e.options.lineWrapping||h(e),e.options.mode=t.modeOption,gn(e)}function _i(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(o>t){n=i;break}t-=o}return n.lines[t]}function Mi(e,t,n){var r=[],i=t.line;return e.iter(t.line,n.line+1,function(e){var o=e.text;i==n.line&&(o=o.slice(0,n.ch)),i==t.line&&(o=o.slice(t.ch)),r.push(o),++i}),r}function Ei(e,t,n){var r=[];return e.iter(t,n,function(e){r.push(e.text)}),r}function ji(e,t){var n=t-e.height;if(n)for(var r=e;r;r=r.parent)r.height+=n}function Ii(e){if(null==e.parent)return null;for(var t=e.parent,n=ho(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var i=0;r.children[i]!=t;++i)n+=r.children[i].chunkSize();return n+t.first}function Hi(e,t){var n=e.first;e:do{for(var r=0;r<e.children.length;++r){var i=e.children[r],o=i.height;if(o>t){e=i;continue e}t-=o,n+=i.chunkSize()}return n}while(!e.lines);for(var r=0;r<e.lines.length;++r){var a=e.lines[r],s=a.height;if(s>t)break;t-=s}return n+r}function Oi(e){e=Qr(e);for(var t=0,n=e.parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==e)break;t+=i.height}for(var o=n.parent;o;n=o,o=n.parent)for(var r=0;r<o.children.length;++r){var a=o.children[r];if(a==n)break;t+=a.height}return t}function Ri(e){var t=e.order;return null==t&&(t=e.order=Os(e.text)),t}function Pi(e){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e||1}function Fi(e,t){var n={from:V(t.from),to:Ea(t),text:Mi(e,t.from,t.to)};return Xi(e,n,t.from.line,t.to.line+1),Ai(e,function(e){Xi(e,n,t.from.line,t.to.line+1)},!0),n}function Wi(e){for(;e.length;){var t=fo(e);if(!t.ranges)break;e.pop()}}function zi(e,t){return t?(Wi(e.done),fo(e.done)):e.done.length&&!fo(e.done).ranges?fo(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),fo(e.done)):void 0}function Bi(e,t,n,r){var i=e.history;i.undone.length=0;var o,a=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&i.lastModTime>a-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=zi(i,i.lastOp==r))){var s=fo(o.changes);0==ba(t.from,t.to)&&0==ba(t.from,s.to)?s.to=Ea(t):o.changes.push(Fi(e,t))}else{var l=fo(i.done);for(l&&l.ranges||Vi(e.sel,i.done),o={changes:[Fi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=a,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,s||fs(e,"historyAdded")}function qi(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Ui(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||qi(e,o,fo(i.done),t))?i.done[i.done.length-1]=t:Vi(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&r.clearRedo!==!1&&Wi(i.undone)}function Vi(e,t){var n=fo(t);n&&n.ranges&&n.equals(e)||t.push(e)}function Xi(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans),++o})}function Gi(e){if(!e)return null;for(var t,n=0;n<e.length;++n)e[n].marker.explicitlyCleared?t||(t=e.slice(0,n)):t&&t.push(e[n]);return t?t.length?t:null:e}function $i(e,t){var n=t["spans_"+e.id];if(!n)return null;for(var r=0,i=[];r<t.text.length;++r)i.push(Gi(n[r]));return i}function Ji(e,t,n){for(var r=0,i=[];r<e.length;++r){var o=e[r];if(o.ranges)i.push(n?$.prototype.deepCopy.call(o):o);else{var a=o.changes,s=[];i.push({changes:s});for(var l=0;l<a.length;++l){var u,c=a[l];if(s.push({from:c.from,to:c.to,text:c.text}),t)for(var f in c)(u=f.match(/^spans_(\d+)$/))&&ho(t,Number(u[1]))>-1&&(fo(s)[f]=c[f],delete c[f])}}}return i}function Yi(e,t,n,r){n<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function Ki(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i],a=!0;if(o.ranges){o.copied||(o=e[i]=o.deepCopy(),o.copied=!0);for(var s=0;s<o.ranges.length;s++)Yi(o.ranges[s].anchor,t,n,r),Yi(o.ranges[s].head,t,n,r)}else{for(var s=0;s<o.changes.length;++s){var l=o.changes[s];if(n<l.from.line)l.from=ya(l.from.line+r,l.from.ch),l.to=ya(l.to.line+r,l.to.ch);else if(t<=l.to.line){a=!1;break}}a||(e.splice(0,i+1),i=0)}}}function Qi(e,t){var n=t.from.line,r=t.to.line,i=t.text.length-(r-n)-1;Ki(e.done,n,r,i),Ki(e.undone,n,r,i)}function Zi(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function eo(e){return e.target||e.srcElement}function to(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),fa&&e.ctrlKey&&1==t&&(t=3),t}function no(e,t){function n(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var i,o=Array.prototype.slice.call(arguments,2);Ta?i=Ta.delayedCallbacks:ds?i=ds:(i=ds=[],setTimeout(ro,0));for(var a=0;a<r.length;++a)i.push(n(r[a]))}}function ro(){var e=ds;ds=null;for(var t=0;t<e.length;++t)e[t]()}function io(e,t,n){return fs(e,n||t.type,e,t),Zi(t)||t.codemirrorIgnore}function oo(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var n=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==ho(n,t[r])&&n.push(t[r])}function ao(e,t){var n=e._handlers&&e._handlers[t];return n&&n.length>0}function so(e){e.prototype.on=function(e,t){us(this,e,t)},e.prototype.off=function(e,t){cs(this,e,t)}}function lo(){this.id=null}function uo(e,t,n){for(var r=0,i=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var a=o-r;if(o==e.length||i+a>=t)return r+Math.min(a,t-i);if(i+=o-r,i+=n-i%n,r=o+1,i>=t)return r}}function co(e){for(;bs.length<=e;)bs.push(fo(bs)+" ");return bs[e]}function fo(e){return e[e.length-1]}function ho(e,t){for(var n=0;n<e.length;++n)if(e[n]==t)return n;return-1}function po(e,t){for(var n=[],r=0;r<e.length;r++)n[r]=t(e[r],r);return n}function go(e,t){var n;if(Object.create)n=Object.create(e);else{var r=function(){};r.prototype=e,n=new r}return t&&mo(t,n),n}function mo(e,t,n){t||(t={});for(var r in e)!e.hasOwnProperty(r)||n===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function vo(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function yo(e,t){return t?t.source.indexOf("\\w")>-1&&Cs(e)?!0:t.test(e):Cs(e)}function bo(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function xo(e){return e.charCodeAt(0)>=768&&Ts.test(e)}function wo(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)i.appendChild(t[o]);return i}function So(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Co(e,t){return So(e).appendChild(t)}function To(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function Do(){return document.activeElement}function ko(e){return new RegExp("\\b"+e+"\\b\\s*")}function Lo(e,t){var n=ko(t);n.test(e.className)&&(e.className=e.className.replace(n,""))}function Ao(e,t){ko(t).test(e.className)||(e.className+=" "+t)}function No(e,t){for(var n=e.split(" "),r=0;r<n.length;r++)n[r]&&!ko(n[r]).test(t)&&(t+=" "+n[r]);return t}function _o(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),n=0;n<t.length;n++){var r=t[n].CodeMirror;r&&e(r)}}function Mo(){As||(Eo(),As=!0)}function Eo(){var e;us(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,Ds=null,_o(_n)},100))}),us(window,"blur",function(){_o(Zn)})}function jo(e){if(null!=Ds)return Ds;var t=wo("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return Co(e,t),t.offsetWidth&&(Ds=t.offsetHeight-t.clientHeight),Ds||0}function Io(e){if(null==ks){var t=wo("span","​");Co(e,wo("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(ks=t.offsetWidth<=1&&t.offsetHeight>2&&!(Zo&&8>ea))}return ks?wo("span","​"):wo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Ho(e){if(null!=Ls)return Ls;var t=Co(e,document.createTextNode("AخA")),n=ws(t,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=ws(t,1,2).getBoundingClientRect();return Ls=r.right-n.right<3}function Oo(e){if(null!=js)return js;var t=Co(e,wo("span","x")),n=t.getBoundingClientRect(),r=ws(t,0,1).getBoundingClientRect();return js=Math.abs(n.left-r.left)>1}function Ro(e,t,n,r){if(!e)return r(t,n,"ltr");for(var i=!1,o=0;o<e.length;++o){var a=e[o];(a.from<n&&a.to>t||t==n&&a.to==t)&&(r(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr"),i=!0)}i||r(t,n,"ltr")}function Po(e){return e.level%2?e.to:e.from}function Fo(e){return e.level%2?e.from:e.to}function Wo(e){var t=Ri(e);return t?Po(t[0]):0}function zo(e){var t=Ri(e);return t?Fo(fo(t)):e.text.length}function Bo(e,t){var n=_i(e.doc,t),r=Qr(n);r!=n&&(t=Ii(r));var i=Ri(r),o=i?i[0].level%2?zo(r):Wo(r):0;return ya(t,o)}function qo(e,t){for(var n,r=_i(e.doc,t);n=Yr(r);)r=n.find(1,!0).line,t=null;var i=Ri(r),o=i?i[0].level%2?Wo(r):zo(r):r.text.length;return ya(null==t?Ii(r):t,o)}function Uo(e,t){var n=Bo(e,t.line),r=_i(e.doc,n.line),i=Ri(r);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),a=t.line==n.line&&t.ch<=o&&t.ch;return ya(n.line,a?0:o)}return n}function Vo(e,t,n){var r=e[0].level;return t==r?!0:n==r?!1:n>t}function Xo(e,t){Hs=null;for(var n,r=0;r<e.length;++r){var i=e[r];if(i.from<t&&i.to>t)return r;if(i.from==t||i.to==t){if(null!=n)return Vo(e,i.level,e[n].level)?(i.from!=i.to&&(Hs=n),r):(i.from!=i.to&&(Hs=r),n);n=r}}return n}function Go(e,t,n,r){if(!r)return t+n;do t+=n;while(t>0&&xo(e.text.charAt(t)));return t}function $o(e,t,n,r){var i=Ri(e);if(!i)return Jo(e,t,n,r);for(var o=Xo(i,t),a=i[o],s=Go(e,t,a.level%2?-n:n,r);;){if(s>a.from&&s<a.to)return s;if(s==a.from||s==a.to)return Xo(i,s)==o?s:(a=i[o+=n],n>0==a.level%2?a.to:a.from);if(a=i[o+=n],!a)return null;s=n>0==a.level%2?Go(e,a.to,-1,r):Go(e,a.from,1,r)}}function Jo(e,t,n,r){var i=t+n;if(r)for(;i>0&&xo(e.text.charAt(i));)i+=n;return 0>i||i>e.text.length?null:i}var Yo=/gecko\/\d/i.test(navigator.userAgent),Ko=/MSIE \d/.test(navigator.userAgent),Qo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Zo=Ko||Qo,ea=Zo&&(Ko?document.documentMode||6:Qo[1]),ta=/WebKit\//.test(navigator.userAgent),na=ta&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ra=/Chrome\//.test(navigator.userAgent),ia=/Opera\//.test(navigator.userAgent),oa=/Apple Computer/.test(navigator.vendor),aa=/KHTML\//.test(navigator.userAgent),sa=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),la=/PhantomJS/.test(navigator.userAgent),ua=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),ca=ua||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),fa=ua||/Mac/.test(navigator.platform),da=/win/i.test(navigator.platform),ha=ia&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);ha&&(ha=Number(ha[1])),ha&&ha>=15&&(ia=!1,ta=!0);var pa=fa&&(na||ia&&(null==ha||12.11>ha)),ga=Yo||Zo&&ea>=9,ma=!1,va=!1,ya=e.Pos=function(e,t){return this instanceof ya?(this.line=e,void(this.ch=t)):new ya(e,t)},ba=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var n=this.ranges[t],r=e.ranges[t];if(0!=ba(n.anchor,r.anchor)||0!=ba(n.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new J(V(this.ranges[t].anchor),V(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(ba(t,r.from())>=0&&ba(e,r.to())<=0)return n}return-1}},J.prototype={from:function(){return G(this.anchor,this.head)},to:function(){return X(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var xa,wa,Sa,Ca={left:0,right:0,top:0,bottom:0},Ta=null,Da=0,ka=null,La=0,Aa=0,Na=null;Zo?Na=-.53:Yo?Na=15:ra?Na=-.7:oa&&(Na=-1/3);var _a,Ma=null,Ea=e.changeEnd=function(e){return e.text?ya(e.from.line+e.text.length-1,fo(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus(),kn(this),Cn(this)},setOption:function(e,t){var n=this.options,r=n[e];(n[e]!=t||"mode"==e)&&(n[e]=t,Ia.hasOwnProperty(e)&&cn(this,Ia[e])(this,t,r))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](e)},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;n<t.length;++n)if(t[n]==e||"string"!=typeof t[n]&&t[n].name==e)return t.splice(n,1),!0},addOverlay:fn(function(t,n){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:n&&n.opaque}),this.state.modeGen++,gn(this)}),removeOverlay:fn(function(e){for(var t=this.state.overlays,n=0;n<t.length;++n){var r=t[n].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(n,1),this.state.modeGen++,void gn(this)}}),indentLine:fn(function(e,t,n){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),tt(this.doc,e)&&wr(this,e,t,n)}),indentSelection:fn(function(e){for(var t=this.doc.sel.ranges,n=-1,r=0;r<t.length;r++){var i=t[r];if(i.empty())i.head.line>n&&(wr(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&br(this));else{var o=i.from(),a=i.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;n>l;++l)wr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&&at(this.doc,r,new J(o,u[r].to()),gs)}}}),getTokenAt:function(e,t){var n=this.doc;e=Z(n,e);for(var r=Dt(this,e.line,t),i=this.doc.mode,o=_i(n,e.line),a=new $a(o.text,this.options.tabSize);a.pos<e.ch&&!a.eol();){a.start=a.pos;var s=fi(i,a,r)}return{start:a.start,end:a.pos,string:a.current(),type:s||null,state:r}},getTokenTypeAt:function(e){e=Z(this.doc,e);var t,n=pi(this,_i(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]<o)){t=n[2*a+2];break}r=a+1}}var s=t?t.indexOf("cm-overlay "):-1;return 0>s?t:0==s?null:t.slice(0,s-1)},getModeAt:function(t){var n=this.doc.mode;return n.innerMode?e.innerMode(n,this.getTokenAt(t).state).mode:n},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var n=[];if(!Wa.hasOwnProperty(t))return Wa;var r=Wa[t],i=this.getModeAt(e);if("string"==typeof i[t])r[i[t]]&&n.push(r[i[t]]);else if(i[t])for(var o=0;o<i[t].length;o++){var a=r[i[t][o]];a&&n.push(a)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var o=0;o<r._global.length;o++){var s=r._global[o];s.pred(i,this)&&-1==ho(n,s.val)&&n.push(s.val)}return n},getStateAfter:function(e,t){var n=this.doc;return e=Q(n,null==e?n.first+n.size-1:e),Dt(this,e+1,t)},cursorCoords:function(e,t){var n,r=this.doc.sel.primary();return n=null==e?r.head:"object"==typeof e?Z(this.doc,e):e?r.from():r.to(),Xt(this,n,t||"page")},charCoords:function(e,t){return Vt(this,Z(this.doc,e),t||"page")},coordsChar:function(e,t){return e=Ut(this,e,t||"page"),Jt(this,e.left,e.top)},lineAtHeight:function(e,t){return e=Ut(this,{top:e,left:0},t||"page").top,Hi(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var n=!1,r=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>r&&(e=r,n=!0);var i=_i(this.doc,e);return qt(this,i,{top:0,left:0},t||"page").top+(n?this.doc.height-Oi(i):0)},defaultTextHeight:function(){return Kt(this.display)},defaultCharWidth:function(){return Qt(this.display)},setGutterMarker:fn(function(e,t,n){return Sr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=n,!n&&bo(r)&&(e.gutterMarkers=null),!0})}),clearGutter:fn(function(e){var t=this,n=t.doc,r=n.first;n.iter(function(n){n.gutterMarkers&&n.gutterMarkers[e]&&(n.gutterMarkers[e]=null,mn(t,r,"gutter"),bo(n.gutterMarkers)&&(n.gutterMarkers=null)),++r})}),addLineWidget:fn(function(e,t,n){return ai(this,e,t,n)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!tt(this.doc,e))return null;var t=e;if(e=_i(this.doc,e),!e)return null}else{var t=Ii(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o=this.display;e=Xt(this,Z(this.doc,e));var a=e.bottom,s=e.left;if(t.style.position="absolute",o.sizer.appendChild(t),"over"==r)a=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?a=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(a=e.bottom),s+t.offsetWidth>u&&(s=u-t.offsetWidth)}t.style.top=a+"px",t.style.left=t.style.right="","right"==i?(s=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?s=0:"middle"==i&&(s=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=s+"px"),n&&mr(this,s,a,s+t.offsetWidth,a+t.offsetHeight)},triggerOnKeyDown:fn($n),triggerOnKeyPress:fn(Kn),triggerOnKeyUp:Yn,execCommand:function(e){return qa.hasOwnProperty(e)?qa[e](this):void 0},findPosH:function(e,t,n,r){var i=1;0>t&&(i=-1,t=-t);for(var o=0,a=Z(this.doc,e);t>o&&(a=Tr(this.doc,a,i,n,r),!a.hitSide);++o);return a},moveH:fn(function(e,t){var n=this;n.extendSelectionsBy(function(r){return n.display.shift||n.doc.extend||r.empty()?Tr(n.doc,r.head,e,t,n.options.rtlMoveVisually):0>e?r.from():r.to()},vs)}),deleteH:fn(function(e,t){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):Cr(this,function(n){var i=Tr(r,n.head,e,t,!1);return 0>e?{from:i,to:n.head}:{from:n.head,to:i}})}),findPosV:function(e,t,n,r){var i=1,o=r;0>t&&(i=-1,t=-t);for(var a=0,s=Z(this.doc,e);t>a;++a){var l=Xt(this,s,"div");if(null==o?o=l.left:l.left=o,s=Dr(this,l,i,n),s.hitSide)break}return s},moveV:fn(function(e,t){var n=this,r=this.doc,i=[],o=!n.display.shift&&!r.extend&&r.sel.somethingSelected();if(r.extendSelectionsBy(function(a){if(o)return 0>e?a.from():a.to();var s=Xt(n,a.head,"div");null!=a.goalColumn&&(s.left=a.goalColumn),i.push(s.left);var l=Dr(n,s,e,t);return"page"==t&&a==r.sel.primary()&&yr(n,null,Vt(n,l,"div").top-s.top),l},vs),i.length)for(var a=0;a<r.sel.ranges.length;a++)r.sel.ranges[a].goalColumn=i[a]}),findWordAt:function(e){var t=this.doc,n=_i(t,e.line).text,r=e.ch,i=e.ch;if(n){var o=this.getHelper(e,"wordChars");(e.xRel<0||i==n.length)&&r?--r:++i;for(var a=n.charAt(r),s=yo(a,o)?function(e){return yo(e,o)}:/\s/.test(a)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!yo(e)};r>0&&s(n.charAt(r-1));)--r;for(;i<n.length&&s(n.charAt(i));)++i}return new J(ya(e.line,r),ya(e.line,i))},toggleOverwrite:function(e){(null==e||e!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?Ao(this.display.cursorDiv,"CodeMirror-overwrite"):Lo(this.display.cursorDiv,"CodeMirror-overwrite"),fs(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return Do()==this.display.input},scrollTo:fn(function(e,t){(null!=e||null!=t)&&xr(this),null!=e&&(this.curOp.scrollLeft=e),null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller,t=hs;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-t,width:e.scrollWidth-t,clientHeight:e.clientHeight-t,clientWidth:e.clientWidth-t}},scrollIntoView:fn(function(e,t){if(null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:ya(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line)xr(this),this.curOp.scrollToPos=e;else{var n=vr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(n.scrollLeft,n.scrollTop)}}),setSize:fn(function(e,t){function n(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=n(e)),null!=t&&(r.display.wrapper.style.height=n(t)),r.options.lineWrapping&&Ft(this);var i=r.display.viewFrom;r.doc.iter(i,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){mn(r,i,"widget");break}++i}),r.curOp.forceUpdate=!0,fs(r,"refresh",this)}),operation:function(e){return un(this,e)},refresh:fn(function(){var e=this.display.cachedTextHeight;gn(this),this.curOp.forceUpdate=!0,Wt(this),this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop),f(this),(null==e||Math.abs(e-Kt(this.display))>.5)&&a(this),fs(this,"refresh",this)}),swapDoc:fn(function(e){var t=this.doc;return t.cm=null,Ni(this,e),Wt(this),Dn(this),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,no(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper },getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},so(e);var ja=e.defaults={},Ia=e.optionHandlers={},Ha=e.Init={toString:function(){return"CodeMirror.Init"}};kr("value","",function(e,t){e.setValue(t)},!0),kr("mode",null,function(e,t){e.doc.modeOption=t,n(e)},!0),kr("indentUnit",2,n,!0),kr("indentWithTabs",!1),kr("smartIndent",!0),kr("tabSize",4,function(e){r(e),Wt(e),gn(e)},!0),kr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),kr("specialCharPlaceholder",yi,function(e){e.refresh()},!0),kr("electricChars",!0),kr("rtlMoveVisually",!da),kr("wholeLineUpdateBefore",!0),kr("theme","default",function(e){l(e),u(e)},!0),kr("keyMap","default",s),kr("extraKeys",null),kr("lineWrapping",!1,i,!0),kr("gutters",[],function(e){p(e.options),u(e)},!0),kr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?S(e.display)+"px":"0",e.refresh()},!0),kr("coverGutterNextToScrollbar",!1,v,!0),kr("lineNumbers",!1,function(e){p(e.options),u(e)},!0),kr("firstLineNumber",1,u,!0),kr("lineNumberFormatter",function(e){return e},u,!0),kr("showCursorWhenSelecting",!1,yt,!0),kr("resetSelectionOnContextMenu",!0),kr("readOnly",!1,function(e,t){"nocursor"==t?(Zn(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||Dn(e))}),kr("disableInput",!1,function(e,t){t||Dn(e)},!0),kr("dragDrop",!0),kr("cursorBlinkRate",530),kr("cursorScrollMargin",0),kr("cursorHeight",1,yt,!0),kr("singleCursorHeightPerLine",!0,yt,!0),kr("workTime",100),kr("workDelay",100),kr("flattenSpans",!0,r,!0),kr("addModeClass",!1,r,!0),kr("pollInterval",100),kr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),kr("historyEventDelay",1250),kr("viewportMargin",10,function(e){e.refresh()},!0),kr("maxHighlightLength",1e4,r,!0),kr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),kr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),kr("autofocus",null);var Oa=e.modes={},Ra=e.mimeModes={};e.defineMode=function(t,n){e.defaults.mode||"null"==t||(e.defaults.mode=t),arguments.length>2&&(n.dependencies=Array.prototype.slice.call(arguments,2)),Oa[t]=n},e.defineMIME=function(e,t){Ra[e]=t},e.resolveMode=function(t){if("string"==typeof t&&Ra.hasOwnProperty(t))t=Ra[t];else if(t&&"string"==typeof t.name&&Ra.hasOwnProperty(t.name)){var n=Ra[t.name];"string"==typeof n&&(n={name:n}),t=go(n,t),t.name=n.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}},e.getMode=function(t,n){var n=e.resolveMode(n),r=Oa[n.name];if(!r)return e.getMode(t,"text/plain");var i=r(t,n);if(Pa.hasOwnProperty(n.name)){var o=Pa[n.name];for(var a in o)o.hasOwnProperty(a)&&(i.hasOwnProperty(a)&&(i["_"+a]=i[a]),i[a]=o[a])}if(i.name=n.name,n.helperType&&(i.helperType=n.helperType),n.modeProps)for(var a in n.modeProps)i[a]=n.modeProps[a];return i},e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),e.defineMIME("text/plain","null");var Pa=e.modeExtensions={};e.extendMode=function(e,t){var n=Pa.hasOwnProperty(e)?Pa[e]:Pa[e]={};mo(t,n)},e.defineExtension=function(t,n){e.prototype[t]=n},e.defineDocExtension=function(e,t){rs.prototype[e]=t},e.defineOption=kr;var Fa=[];e.defineInitHook=function(e){Fa.push(e)};var Wa=e.helpers={};e.registerHelper=function(t,n,r){Wa.hasOwnProperty(t)||(Wa[t]=e[t]={_global:[]}),Wa[t][n]=r},e.registerGlobalHelper=function(t,n,r,i){e.registerHelper(t,n,i),Wa[t]._global.push({pred:r,val:i})};var za=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n},Ba=e.startState=function(e,t,n){return e.startState?e.startState(t,n):!0};e.innerMode=function(e,t){for(;e.innerMode;){var n=e.innerMode(t);if(!n||n.mode==e)break;t=n.state,e=n.mode}return n||{mode:e,state:t}};var qa=e.commands={selectAll:function(e){e.setSelection(ya(e.firstLine(),0),ya(e.lastLine()),gs)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),gs)},killLine:function(e){Cr(e,function(t){if(t.empty()){var n=_i(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line<e.lastLine()?{from:t.head,to:ya(t.head.line+1,0)}:{from:t.head,to:ya(t.head.line,n)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Cr(e,function(t){return{from:ya(t.from().line,0),to:Z(e.doc,ya(t.to().line+1,0))}})},delLineLeft:function(e){Cr(e,function(e){return{from:ya(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Cr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Cr(e,function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(ya(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(ya(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Bo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Uo(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return qo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div")},vs)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:n},"div")},vs)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return r.ch<e.getLine(r.line).search(/\S/)?Uo(e,t.head):r},vs)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],n=e.listSelections(),r=e.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),a=ys(e.getLine(o.line),o.ch,r);t.push(new Array(r-a%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){un(e,function(){for(var t=e.listSelections(),n=[],r=0;r<t.length;r++){var i=t[r].head,o=_i(e.doc,i.line).text;if(o)if(i.ch==o.length&&(i=new ya(i.line,i.ch-1)),i.ch>0)i=new ya(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),ya(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var a=_i(e.doc,i.line-1).text;a&&e.replaceRange(o.charAt(0)+"\n"+a.charAt(a.length-1),ya(i.line-1,a.length-1),ya(i.line,1),"+transpose")}n.push(new J(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){un(e,function(){for(var t=e.listSelections().length,n=0;t>n;n++){var r=e.listSelections()[n];e.replaceRange("\n",r.anchor,r.head,"+input"),e.indentLine(r.from().line+1,null,!0),br(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ua=e.keyMap={};Ua.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ua.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ua.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Ua.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},Ua["default"]=fa?Ua.macDefault:Ua.pcDefault;var Va=e.lookupKey=function(e,t,n){function r(t){t=Lr(t);var i=t[e];if(i===!1)return"stop";if(null!=i&&n(i))return!0;if(t.nofallthrough)return"stop";var o=t.fallthrough;if(null==o)return!1;if("[object Array]"!=Object.prototype.toString.call(o))return r(o);for(var a=0;a<o.length;++a){var s=r(o[a]);if(s)return s}return!1}for(var i=0;i<t.length;++i){var o=r(t[i]);if(o)return"stop"!=o}},Xa=e.isModifierKey=function(e){var t=Is[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Ga=e.keyName=function(e,t){if(ia&&34==e.keyCode&&e["char"])return!1;var n=Is[e.keyCode];return null==n||e.altGraphKey?!1:(e.altKey&&(n="Alt-"+n),(pa?e.metaKey:e.ctrlKey)&&(n="Ctrl-"+n),(pa?e.ctrlKey:e.metaKey)&&(n="Cmd-"+n),!t&&e.shiftKey&&(n="Shift-"+n),n)};e.fromTextArea=function(t,n){function r(){t.value=u.getValue()}if(n||(n={}),n.value=t.value,!n.tabindex&&t.tabindex&&(n.tabindex=t.tabindex),!n.placeholder&&t.placeholder&&(n.placeholder=t.placeholder),null==n.autofocus){var i=Do();n.autofocus=i==t||null!=t.getAttribute("autofocus")&&i==document.body}if(t.form&&(us(t.form,"submit",r),!n.leaveSubmitMethodAlone)){var o=t.form,a=o.submit;try{var s=o.submit=function(){r(),o.submit=a,o.submit(),o.submit=s}}catch(l){}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},n);return u.save=r,u.getTextArea=function(){return t},u.toTextArea=function(){u.toTextArea=isNaN,r(),t.parentNode.removeChild(u.getWrapperElement()),t.style.display="",t.form&&(cs(t.form,"submit",r),"function"==typeof t.form.submit&&(t.form.submit=a))},u};var $a=e.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0};$a.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var n=t==e;else var n=t&&(e.test?e.test(t):e(t));return n?(++this.pos,t):void 0},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);return t>-1?(this.pos=t,!0):void 0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=ys(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ys(this.string,null,this.tabSize)-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,n){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&r.index>0?null:(r&&t!==!1&&(this.pos+=r[0].length),r)}var i=function(e){return n?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return i(o)==i(e)?(t!==!1&&(this.pos+=e.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Ja=e.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};so(Ja),Ja.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Zt(e),ao(this,"clear")){var n=this.find();n&&no(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var a=this.lines[o],s=Ir(a.markedSpans,this);e&&!this.collapsed?mn(e,Ii(a),"text"):e&&(null!=s.to&&(i=Ii(a)),null!=s.from&&(r=Ii(a))),a.markedSpans=Hr(a.markedSpans,s),null==s.from&&this.collapsed&&!ni(this.doc,a)&&e&&ji(a,Kt(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Qr(this.lines[o]),u=d(l);u>e.display.maxLineLength&&(e.display.maxLine=l,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&gn(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&ht(e.doc)),e&&no(e,"markerCleared",e,this),t&&tn(e),this.parent&&this.parent.clear()}},Ja.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var n,r,i=0;i<this.lines.length;++i){var o=this.lines[i],a=Ir(o.markedSpans,this);if(null!=a.from&&(n=ya(t?o:Ii(o),a.from),-1==e))return n;if(null!=a.to&&(r=ya(t?o:Ii(o),a.to),1==e))return r}return n&&{from:n,to:r}},Ja.prototype.changed=function(){var e=this.find(-1,!0),t=this,n=this.doc.cm;e&&n&&un(n,function(){var r=e.line,i=Ii(e.line),o=jt(n,i);if(o&&(Pt(o),n.curOp.selectionChanged=n.curOp.forceUpdate=!0),n.curOp.updateMaxLine=!0,!ni(t.doc,r)&&null!=t.height){var a=t.height;t.height=null;var s=oi(t)-a;s&&ji(r,r.height+s)}})},Ja.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=ho(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},Ja.prototype.detachLine=function(e){if(this.lines.splice(ho(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var Ya=0,Ka=e.SharedTextMarker=function(e,t){this.markers=e,this.primary=t;for(var n=0;n<e.length;++n)e[n].parent=this};so(Ka),Ka.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();no(this,"clear")}},Ka.prototype.find=function(e,t){return this.primary.find(e,t)};var Qa=e.LineWidget=function(e,t,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.cm=e,this.node=t};so(Qa),Qa.prototype.clear=function(){var e=this.cm,t=this.line.widgets,n=this.line,r=Ii(n);if(null!=r&&t){for(var i=0;i<t.length;++i)t[i]==this&&t.splice(i--,1);t.length||(n.widgets=null);var o=oi(this);un(e,function(){ii(e,n,-o),mn(e,r,"widget"),ji(n,Math.max(0,n.height-o))})}},Qa.prototype.changed=function(){var e=this.height,t=this.cm,n=this.line;this.height=null;var r=oi(this)-e;r&&un(t,function(){t.curOp.forceUpdate=!0,ii(t,n,r),ji(n,n.height+r)})};var Za=e.Line=function(e,t,n){this.text=e,Ur(this,t),this.height=n?n(this):1};so(Za),Za.prototype.lineNo=function(){return Ii(this)};var es={},ts={};ki.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n=e,r=e+t;r>n;++n){var i=this.lines[n];this.height-=i.height,li(i),no(i,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,n){this.height+=n,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,n){for(var r=e+t;r>e;++e)if(n(this.lines[e]))return!0}},Li.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(i>e){var o=Math.min(t,i-e),a=r.height;if(r.removeInner(e,o),this.height-=a-r.height,i==o&&(this.children.splice(n--,1),r.parent=null),0==(t-=o))break;e=0}else e-=i}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof ki))){var s=[];this.collapse(s),this.children=[new ki(s)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,n){this.size+=t.length,this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>=e){if(i.insertInner(e,t,n),i.lines&&i.lines.length>50){for(;i.lines.length>50;){var a=i.lines.splice(i.lines.length-25,25),s=new ki(a);i.height-=s.height,this.children.splice(r+1,0,s),s.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),n=new Li(t);if(e.parent){e.size-=n.size,e.height-=n.height;var r=ho(e.parent.children,e);e.parent.children.splice(r+1,0,n)}else{var i=new Li(e.children);i.parent=e,e.children=[i,n],e=i}n.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>e){var a=Math.min(t,o-e);if(i.iterN(e,a,n))return!0;if(0==(t-=a))break;e=0}else e-=o}}};var ns=0,rs=e.Doc=function(e,t,n){if(!(this instanceof rs))return new rs(e,t,n);null==n&&(n=0),Li.call(this,[new ki([new Za("",null)])]),this.first=n,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=n;var r=ya(n,0);this.sel=K(r),this.history=new Pi(null),this.id=++ns,this.modeOption=t,"string"==typeof e&&(e=_s(e)),Di(this,{from:r,to:r,text:e}),ct(this,K(r),gs)};rs.prototype=go(Li.prototype,{constructor:rs,iter:function(e,t,n){n?this.iterN(e-this.first,t-e,n):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var n=0,r=0;r<t.length;++r)n+=t[r].height;this.insertInner(e-this.first,t,n)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ei(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:dn(function(e){var t=ya(this.first,0),n=this.first+this.size-1;sr(this,{from:t,to:ya(n,_i(this,n).text.length),text:_s(e),origin:"setValue"},!0),ct(this,K(t))}),replaceRange:function(e,t,n,r){t=Z(this,t),n=n?Z(this,n):t,hr(this,e,t,n,r)},getRange:function(e,t,n){var r=Mi(this,Z(this,e),Z(this,t));return n===!1?r:r.join(n||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return tt(this,e)?_i(this,e):void 0},getLineNumber:function(e){return Ii(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=_i(this,e)),Qr(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return Z(this,e)},getCursor:function(e){var t,n=this.sel.primary();return t=null==e||"head"==e?n.head:"anchor"==e?n.anchor:"end"==e||"to"==e||e===!1?n.to():n.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:dn(function(e,t,n){st(this,Z(this,"number"==typeof e?ya(e,t||0):e),null,n)}),setSelection:dn(function(e,t,n){st(this,Z(this,e),Z(this,t||e),n)}),extendSelection:dn(function(e,t,n){it(this,Z(this,e),t&&Z(this,t),n)}),extendSelections:dn(function(e,t){ot(this,nt(this,e,t))}),extendSelectionsBy:dn(function(e,t){ot(this,po(this.sel.ranges,e),t)}),setSelections:dn(function(e,t,n){if(e.length){for(var r=0,i=[];r<e.length;r++)i[r]=new J(Z(this,e[r].anchor),Z(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),ct(this,Y(i,t),n)}}),addSelection:dn(function(e,t,n){var r=this.sel.ranges.slice(0);r.push(new J(Z(this,e),Z(this,t||e))),ct(this,Y(r,r.length-1),n)}),getSelection:function(e){for(var t,n=this.sel.ranges,r=0;r<n.length;r++){var i=Mi(this,n[r].from(),n[r].to());t=t?t.concat(i):i}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=Mi(this,n[r].from(),n[r].to());e!==!1&&(i=i.join(e||"\n")),t[r]=i}return t},replaceSelection:function(e,t,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=e;this.replaceSelections(r,t,n||"+input")},replaceSelections:dn(function(e,t,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var a=i.ranges[o];r[o]={from:a.from(),to:a.to(),text:_s(e[o]),origin:n}}for(var s=t&&"end"!=t&&or(this,r,t),o=r.length-1;o>=0;o--)sr(this,r[o]);s?ut(this,s):this.cm&&br(this.cm)}),undo:dn(function(){ur(this,"undo")}),redo:dn(function(){ur(this,"redo")}),undoSelection:dn(function(){ur(this,"undo",!0)}),redoSelection:dn(function(){ur(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++n;return{undo:t,redo:n}},clearHistory:function(){this.history=new Pi(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Ji(this.history.done),undone:Ji(this.history.undone)}},setHistory:function(e){var t=this.history=new Pi(this.history.maxGeneration);t.done=Ji(e.done.slice(0),null,!0),t.undone=Ji(e.undone.slice(0),null,!0)},addLineClass:dn(function(e,t,n){return Sr(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass";if(e[r]){if(new RegExp("(?:^|\\s)"+n+"(?:$|\\s)").test(e[r]))return!1;e[r]+=" "+n}else e[r]=n;return!0})}),removeLineClass:dn(function(e,t,n){return Sr(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass",i=e[r];if(!i)return!1;if(null==n)e[r]=null;else{var o=i.match(new RegExp("(?:^|\\s+)"+n+"(?:$|\\s+)"));if(!o)return!1;var a=o.index+o[0].length;e[r]=i.slice(0,o.index)+(o.index&&a!=i.length?" ":"")+i.slice(a)||null}return!0})}),markText:function(e,t,n){return Ar(this,Z(this,e),Z(this,t),n,"range")},setBookmark:function(e,t){var n={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};return e=Z(this,e),Ar(this,e,e,n,"bookmark")},findMarksAt:function(e){e=Z(this,e);var t=[],n=_i(this,e.line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=e.ch)&&(null==i.to||i.to>=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=Z(this,e),t=Z(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(o){var a=o.markedSpans;if(a)for(var s=0;s<a.length;s++){var l=a[s];i==e.line&&e.ch>l.to||null==l.from&&i!=e.line||i==t.line&&l.from>t.ch||n&&!n(l.marker)||r.push(l.marker.parent||l.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&e.push(n[r].marker)}),e},posFromIndex:function(e){var t,n=this.first;return this.iter(function(r){var i=r.text.length+1;return i>e?(t=e,!0):(e-=i,void++n)}),Z(this,ya(n,t))},indexFromPos:function(e){e=Z(this,e);var t=e.ch;return e.line<this.first||e.ch<0?0:(this.iter(this.first,e.line,function(e){t+=e.text.length+1}),t)},copy:function(e){var t=new rs(Ei(this,this.first,this.first+this.size),this.modeOption,this.first);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,n=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<n&&(n=e.to);var r=new rs(Ei(this,t,n),e.mode||this.modeOption,t);return e.sharedHist&&(r.history=this.history),(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist}),r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],Mr(r,_r(this)),r},unlinkDoc:function(t){if(t instanceof e&&(t=t.doc),this.linked)for(var n=0;n<this.linked.length;++n){var r=this.linked[n];if(r.doc==t){this.linked.splice(n,1),t.unlinkDoc(this),Er(_r(this));break}}if(t.history==this.history){var i=[t.id];Ai(t,function(e){i.push(e.id)},!0),t.history=new Pi(null),t.history.done=Ji(this.history.done,i),t.history.undone=Ji(this.history.undone,i)}},iterLinkedDocs:function(e){Ai(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),rs.prototype.eachLine=rs.prototype.iter;var is="iter insert remove copy getEditor".split(" ");for(var os in rs.prototype)rs.prototype.hasOwnProperty(os)&&ho(is,os)<0&&(e.prototype[os]=function(e){return function(){return e.apply(this.doc,arguments)}}(rs.prototype[os]));so(rs);var as=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},ss=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ls=e.e_stop=function(e){as(e),ss(e)},us=e.on=function(e,t,n){if(e.addEventListener)e.addEventListener(t,n,!1);else if(e.attachEvent)e.attachEvent("on"+t,n);else{var r=e._handlers||(e._handlers={}),i=r[t]||(r[t]=[]);i.push(n)}},cs=e.off=function(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else if(e.detachEvent)e.detachEvent("on"+t,n);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var i=0;i<r.length;++i)if(r[i]==n){r.splice(i,1);break}}},fs=e.signal=function(e,t){var n=e._handlers&&e._handlers[t];if(n)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)},ds=null,hs=30,ps=e.Pass={toString:function(){return"CodeMirror.Pass"}},gs={scroll:!1},ms={origin:"*mouse"},vs={origin:"+move"};lo.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var ys=e.countColumn=function(e,t,n,r,i){null==t&&(t=e.search(/[^\s\u00a0]/),-1==t&&(t=e.length));for(var o=r||0,a=i||0;;){var s=e.indexOf(" ",o);if(0>s||s>=t)return a+(t-o);a+=s-o,a+=n-a%n,o=s+1}},bs=[""],xs=function(e){e.select()};ua?xs=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:Zo&&(xs=function(e){try{e.select()}catch(t){}}),[].indexOf&&(ho=function(e,t){return e.indexOf(t)}),[].map&&(po=function(e,t){return e.map(t)});var ws,Ss=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Cs=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Ss.test(e))},Ts=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ws=document.createRange?function(e,t,n){var r=document.createRange();return r.setEnd(e,n),r.setStart(e,t),r}:function(e,t,n){var r=document.body.createTextRange();return r.moveToElementText(e.parentNode),r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r},Zo&&11>ea&&(Do=function(){try{return document.activeElement}catch(e){return document.body}});var Ds,ks,Ls,As=!1,Ns=function(){if(Zo&&9>ea)return!1;var e=wo("div");return"draggable"in e||"dragDrop"in e}(),_s=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;r>=t;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),t+=a+1):(n.push(o),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Ms=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Es=function(){var e=wo("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),js=null,Is={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=Is,function(){for(var e=0;10>e;e++)Is[e+48]=Is[e+96]=String(e);for(var e=65;90>=e;e++)Is[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Is[e+111]=Is[e+63235]="F"+e}();var Hs,Os=function(){function e(e){return 247>=e?n.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L" }function t(e,t,n){this.level=e,this.from=t,this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,a=/[LRr]/,s=/[Lb1n]/,l=/[1n]/,u="L";return function(n){if(!i.test(n))return!1;for(var r,c=n.length,f=[],d=0;c>d;++d)f.push(r=e(n.charCodeAt(d)));for(var d=0,h=u;c>d;++d){var r=f[d];"m"==r?f[d]=h:h=r}for(var d=0,p=u;c>d;++d){var r=f[d];"1"==r&&"r"==p?f[d]="n":a.test(r)&&(p=r,"r"==r&&(f[d]="R"))}for(var d=1,h=f[0];c-1>d;++d){var r=f[d];"+"==r&&"1"==h&&"1"==f[d+1]?f[d]="1":","!=r||h!=f[d+1]||"1"!=h&&"n"!=h||(f[d]=h),h=r}for(var d=0;c>d;++d){var r=f[d];if(","==r)f[d]="N";else if("%"==r){for(var g=d+1;c>g&&"%"==f[g];++g);for(var m=d&&"!"==f[d-1]||c>g&&"1"==f[g]?"1":"N",v=d;g>v;++v)f[v]=m;d=g-1}}for(var d=0,p=u;c>d;++d){var r=f[d];"L"==p&&"1"==r?f[d]="L":a.test(r)&&(p=r)}for(var d=0;c>d;++d)if(o.test(f[d])){for(var g=d+1;c>g&&o.test(f[g]);++g);for(var y="L"==(d?f[d-1]:u),b="L"==(c>g?f[g]:u),m=y||b?"L":"R",v=d;g>v;++v)f[v]=m;d=g-1}for(var x,w=[],d=0;c>d;)if(s.test(f[d])){var S=d;for(++d;c>d&&s.test(f[d]);++d);w.push(new t(0,S,d))}else{var C=d,T=w.length;for(++d;c>d&&"L"!=f[d];++d);for(var v=C;d>v;)if(l.test(f[v])){v>C&&w.splice(T,0,new t(1,C,v));var D=v;for(++v;d>v&&l.test(f[v]);++v);w.splice(T,0,new t(2,D,v)),C=v}else++v;d>C&&w.splice(T,0,new t(1,C,d))}return 1==w[0].level&&(x=n.match(/^\s+/))&&(w[0].from=x[0].length,w.unshift(new t(0,0,x[0].length))),1==fo(w).level&&(x=n.match(/\s+$/))&&(fo(w).to-=x[0].length,w.push(new t(0,c-x[0].length,c))),w[0].level!=fo(w).level&&w.push(new t(w[0].level,c,c)),w}}();return e.version="4.7.0",e})},{}],6:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){"use strict";e.defineMode("javascript",function(t,n){function r(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}function i(e,t,n){return pt=e,gt=n,t}function o(e,t){var n=e.next();if('"'==n||"'"==n)return t.tokenize=a(n),t.tokenize(e,t);if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),i("number","number");if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),i("number","number");if("/"==n)return e.eat("*")?(t.tokenize=s,s(e,t)):e.eat("/")?(e.skipToEnd(),i("comment","comment")):"operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)?(r(e),e.eatWhile(/[gimy]/),i("regexp","string-2")):(e.eatWhile(Ct),i("operator","operator",e.current()));if("`"==n)return t.tokenize=l,l(e,t);if("#"==n)return e.skipToEnd(),i("error","error");if(Ct.test(n))return e.eatWhile(Ct),i("operator","operator",e.current());if(wt.test(n)){e.eatWhile(wt);var o=e.current(),u=St.propertyIsEnumerable(o)&&St[o];return u&&"."!=t.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function a(e){return function(t,n){var r,a=!1;if(yt&&"@"==t.peek()&&t.match(Tt))return n.tokenize=o,i("jsonld-keyword","meta");for(;null!=(r=t.next())&&(r!=e||a);)a=!a&&"\\"==r;return a||(n.tokenize=o),i("string","string")}}function s(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var a=e.string.charAt(o),s=Dt.indexOf(a);if(s>=0&&3>s){if(!r){++o;break}if(0==--r)break}else if(s>=3&&6>s)++r;else if(wt.test(a))i=!0;else if(i&&!r){++o;break}}i&&!r&&(t.fatArrowAt=o)}}function c(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function f(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==t)return!0}function d(e,t,n,r,i){var o=e.cc;for(Lt.state=e,Lt.stream=i,Lt.marked=null,Lt.cc=o,Lt.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;){var a=o.length?o.pop():bt?S:w;if(a(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Lt.marked?Lt.marked:"variable"==n&&f(e,r)?"variable-2":t}}}function h(){for(var e=arguments.length-1;e>=0;e--)Lt.cc.push(arguments[e])}function p(){return h.apply(null,arguments),!0}function g(e){function t(t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}var r=Lt.state;if(r.context){if(Lt.marked="def",t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function m(){Lt.state.context={prev:Lt.state.context,vars:Lt.state.localVars},Lt.state.localVars=At}function v(){Lt.state.localVars=Lt.state.context.vars,Lt.state.context=Lt.state.context.prev}function y(e,t){var n=function(){var n=Lt.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new c(r,Lt.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function b(){var e=Lt.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function x(e){function t(n){return n==e?p():";"==e?h():p(t)}return t}function w(e,t){return"var"==e?p(y("vardef",t.length),q,x(";"),b):"keyword a"==e?p(y("form"),S,w,b):"keyword b"==e?p(y("form"),w,b):"{"==e?p(y("}"),W,b):";"==e?p():"if"==e?("else"==Lt.state.lexical.info&&Lt.state.cc[Lt.state.cc.length-1]==b&&Lt.state.cc.pop()(),p(y("form"),S,w,b,$)):"function"==e?p(et):"for"==e?p(y("form"),J,w,b):"variable"==e?p(y("stat"),j):"switch"==e?p(y("form"),S,y("}","switch"),x("{"),W,b,b):"case"==e?p(S,x(":")):"default"==e?p(x(":")):"catch"==e?p(y("form"),m,x("("),tt,x(")"),w,b,v):"module"==e?p(y("form"),m,at,v,b):"class"==e?p(y("form"),nt,b):"export"==e?p(y("form"),st,b):"import"==e?p(y("form"),lt,b):h(y("stat"),S,x(";"),b)}function S(e){return T(e,!1)}function C(e){return T(e,!0)}function T(e,t){if(Lt.state.fatArrowAt==Lt.stream.start){var n=t?E:M;if("("==e)return p(m,y(")"),P(U,")"),b,x("=>"),n,v);if("variable"==e)return h(m,U,x("=>"),n,v)}var r=t?A:L;return kt.hasOwnProperty(e)?p(r):"function"==e?p(et,r):"keyword c"==e?p(t?k:D):"("==e?p(y(")"),D,ht,x(")"),b,r):"operator"==e||"spread"==e?p(t?C:S):"["==e?p(y("]"),ft,b,r):"{"==e?F(H,"}",null,r):"quasi"==e?h(N,r):p()}function D(e){return e.match(/[;\}\)\],]/)?h():h(S)}function k(e){return e.match(/[;\}\)\],]/)?h():h(C)}function L(e,t){return","==e?p(S):A(e,t,!1)}function A(e,t,n){var r=0==n?L:A,i=0==n?S:C;return"=>"==e?p(m,n?E:M,v):"operator"==e?/\+\+|--/.test(t)?p(r):"?"==t?p(S,x(":"),i):p(i):"quasi"==e?h(N,r):";"!=e?"("==e?F(C,")","call",r):"."==e?p(I,r):"["==e?p(y("]"),D,x("]"),b,r):void 0:void 0}function N(e,t){return"quasi"!=e?h():"${"!=t.slice(t.length-2)?p(N):p(S,_)}function _(e){return"}"==e?(Lt.marked="string-2",Lt.state.tokenize=l,p(N)):void 0}function M(e){return u(Lt.stream,Lt.state),h("{"==e?w:S)}function E(e){return u(Lt.stream,Lt.state),h("{"==e?w:C)}function j(e){return":"==e?p(b,w):h(L,x(";"),b)}function I(e){return"variable"==e?(Lt.marked="property",p()):void 0}function H(e,t){return"variable"==e||"keyword"==Lt.style?(Lt.marked="property",p("get"==t||"set"==t?O:R)):"number"==e||"string"==e?(Lt.marked=yt?"property":Lt.style+" property",p(R)):"jsonld-keyword"==e?p(R):"["==e?p(S,x("]"),R):void 0}function O(e){return"variable"!=e?h(R):(Lt.marked="property",p(et))}function R(e){return":"==e?p(C):"("==e?h(et):void 0}function P(e,t){function n(r){if(","==r){var i=Lt.state.lexical;return"call"==i.info&&(i.pos=(i.pos||0)+1),p(e,n)}return r==t?p():p(x(t))}return function(r){return r==t?p():h(e,n)}}function F(e,t,n){for(var r=3;r<arguments.length;r++)Lt.cc.push(arguments[r]);return p(y(t,n),P(e,t),b)}function W(e){return"}"==e?p():h(w,W)}function z(e){return xt&&":"==e?p(B):void 0}function B(e){return"variable"==e?(Lt.marked="variable-3",p()):void 0}function q(){return h(U,z,X,G)}function U(e,t){return"variable"==e?(g(t),p()):"["==e?F(U,"]"):"{"==e?F(V,"}"):void 0}function V(e,t){return"variable"!=e||Lt.stream.match(/^\s*:/,!1)?("variable"==e&&(Lt.marked="property"),p(x(":"),U,X)):(g(t),p(X))}function X(e,t){return"="==t?p(C):void 0}function G(e){return","==e?p(q):void 0}function $(e,t){return"keyword b"==e&&"else"==t?p(y("form","else"),w,b):void 0}function J(e){return"("==e?p(y(")"),Y,x(")"),b):void 0}function Y(e){return"var"==e?p(q,x(";"),Q):";"==e?p(Q):"variable"==e?p(K):h(S,x(";"),Q)}function K(e,t){return"in"==t||"of"==t?(Lt.marked="keyword",p(S)):p(L,Q)}function Q(e,t){return";"==e?p(Z):"in"==t||"of"==t?(Lt.marked="keyword",p(S)):h(S,x(";"),Z)}function Z(e){")"!=e&&p(S)}function et(e,t){return"*"==t?(Lt.marked="keyword",p(et)):"variable"==e?(g(t),p(et)):"("==e?p(m,y(")"),P(tt,")"),b,w,v):void 0}function tt(e){return"spread"==e?p(tt):h(U,z)}function nt(e,t){return"variable"==e?(g(t),p(rt)):void 0}function rt(e,t){return"extends"==t?p(S,rt):"{"==e?p(y("}"),it,b):void 0}function it(e,t){return"variable"==e||"keyword"==Lt.style?(Lt.marked="property","get"==t||"set"==t?p(ot,et,it):p(et,it)):"*"==t?(Lt.marked="keyword",p(it)):";"==e?p(it):"}"==e?p():void 0}function ot(e){return"variable"!=e?h():(Lt.marked="property",p())}function at(e,t){return"string"==e?p(w):"variable"==e?(g(t),p(ct)):void 0}function st(e,t){return"*"==t?(Lt.marked="keyword",p(ct,x(";"))):"default"==t?(Lt.marked="keyword",p(S,x(";"))):h(w)}function lt(e){return"string"==e?p():h(ut,ct)}function ut(e,t){return"{"==e?F(ut,"}"):("variable"==e&&g(t),p())}function ct(e,t){return"from"==t?(Lt.marked="keyword",p(S)):void 0}function ft(e){return"]"==e?p():h(C,dt)}function dt(e){return"for"==e?h(ht,x("]")):","==e?p(P(k,"]")):h(P(C,"]"))}function ht(e){return"for"==e?p(J,ht):"if"==e?p(S,ht):void 0}var pt,gt,mt=t.indentUnit,vt=n.statementIndent,yt=n.jsonld,bt=n.json||yt,xt=n.typescript,wt=n.wordCharacters||/[\w$\xa1-\uffff]/,St=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("operator"),o={type:"atom",style:"atom"},a={"if":e("if"),"while":t,"with":t,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":r,"export":e("export"),"import":e("import"),"extends":r};if(xt){var s={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:s,number:s,bool:s,any:s};for(var u in l)a[u]=l[u]}return a}(),Ct=/[+\-*&%=<>!?|~^]/,Tt=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Dt="([{}])",kt={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Lt={state:null,column:null,marked:null,cc:null},At={name:"this",next:{name:"arguments"}};return b.lex=!0,{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new c((e||0)-mt,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),u(e,t)),t.tokenize!=s&&e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==pt?n:(t.lastType="operator"!=pt||"++"!=gt&&"--"!=gt?pt:"incdec",d(t,n,pt,gt,e))},indent:function(t,r){if(t.tokenize==s)return e.Pass;if(t.tokenize!=o)return 0;var i=r&&r.charAt(0),a=t.lexical;if(!/^\s*else\b/.test(r))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==b)a=a.prev;else if(u!=$)break}"stat"==a.type&&"}"==i&&(a=a.prev),vt&&")"==a.type&&"stat"==a.prev.type&&(a=a.prev);var c=a.type,f=i==c;return"vardef"==c?a.indented+("operator"==t.lastType||","==t.lastType?a.info+1:0):"form"==c&&"{"==i?a.indented:"form"==c?a.indented+mt:"stat"==c?a.indented+("operator"==t.lastType||","==t.lastType?vt||mt:0):"switch"!=a.info||f||0==n.doubleIndentSwitch?a.align?a.column+(f?0:1):a.indented+(f?0:mt):a.indented+(/^(?:case|default)\b/.test(r)?mt:2*mt)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:bt?null:"/*",blockCommentEnd:bt?null:"*/",lineComment:bt?null:"//",fold:"brace",helperType:bt?"json":"javascript",jsonldMode:yt,jsonMode:bt}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{"../../lib/codemirror":5}],7:[function(t,n,r){!function(i){"object"==typeof r&&"object"==typeof n?i(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],i):i(CodeMirror)}(function(e){"use strict";e.defineMode("xml",function(t,n){function r(e,t){function n(n){return t.tokenize=n,n(e,t)}var r=e.next();if("<"==r)return e.eat("!")?e.eat("[")?e.match("CDATA[")?n(a("atom","]]>")):null:e.match("--")?n(a("comment","-->")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),n(s(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=a("meta","?>"),"meta"):(C=e.eat("/")?"closeTag":"openTag",t.tokenize=i,"tag bracket");if("&"==r){var o;return o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";"),o?"atom":"error"}return e.eatWhile(/[^&<]/),null}function i(e,t){var n=e.next();if(">"==n||"/"==n&&e.eat(">"))return t.tokenize=r,C=">"==n?"endTag":"selfcloseTag","tag bracket";if("="==n)return C="equals",null;if("<"==n){t.tokenize=r,t.state=f,t.tagName=t.tagStart=null;var i=t.tokenize(e,t);return i?i+" tag error":"tag error"}return/[\'\"]/.test(n)?(t.tokenize=o(n),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function o(e){var t=function(t,n){for(;!t.eol();)if(t.next()==e){n.tokenize=i;break}return"string"};return t.isInAttribute=!0,t}function a(e,t){return function(n,i){for(;!n.eol();){if(n.match(t)){i.tokenize=r;break}n.next()}return e}}function s(e){return function(t,n){for(var i;null!=(i=t.next());){if("<"==i)return n.tokenize=s(e+1),n.tokenize(t,n);if(">"==i){if(1==e){n.tokenize=r;break}return n.tokenize=s(e-1),n.tokenize(t,n)}}return"meta"}}function l(e,t,n){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=n,(D.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function c(e,t){for(var n;;){if(!e.context)return;if(n=e.context.tagName,!D.contextGrabbers.hasOwnProperty(n)||!D.contextGrabbers[n].hasOwnProperty(t))return;u(e)}}function f(e,t,n){return"openTag"==e?(n.tagStart=t.column(),d):"closeTag"==e?h:f}function d(e,t,n){return"word"==e?(n.tagName=t.current(),T="tag",m):(T="error",d)}function h(e,t,n){if("word"==e){var r=t.current();return n.context&&n.context.tagName!=r&&D.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n),n.context&&n.context.tagName==r?(T="tag",p):(T="tag error",g)}return T="error",g}function p(e,t,n){return"endTag"!=e?(T="error",p):(u(n),f)}function g(e,t,n){return T="error",p(e,t,n)}function m(e,t,n){if("word"==e)return T="attribute",v;if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==e||D.autoSelfClosers.hasOwnProperty(r)?c(n,r):(c(n,r),n.context=new l(n,r,i==n.indented)),f}return T="error",m}function v(e,t,n){return"equals"==e?y:(D.allowMissing||(T="error"),m(e,t,n))}function y(e,t,n){return"string"==e?b:"word"==e&&D.allowUnquoted?(T="string",m):(T="error",m(e,t,n))}function b(e,t,n){return"string"==e?b:m(e,t,n)}var x=t.indentUnit,w=n.multilineTagIndentFactor||1,S=n.multilineTagIndentPastTag;null==S&&(S=!0);var C,T,D=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},k=n.alignCDATA;return{startState:function(){return{tokenize:r,state:f,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;C=null;var n=t.tokenize(e,t);return(n||C)&&"comment"!=n&&(T=null,t.state=t.state(C||n,e,t),T&&(n="error"==T?n+" error":T)),n},indent:function(t,n,o){var a=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+x;if(a&&a.noIndent)return e.Pass;if(t.tokenize!=i&&t.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return S?t.tagStart+t.tagName.length+2:t.tagStart+x*w;if(k&&/<!\[CDATA\[/.test(n))return 0;var s=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(s&&s[1])for(;a;){if(a.tagName==s[2]){a=a.prev;break}if(!D.implicitlyClosed.hasOwnProperty(a.tagName))break;a=a.prev}else if(s)for(;a;){var l=D.contextGrabbers[a.tagName];if(!l||!l.hasOwnProperty(s[2]))break;a=a.prev}for(;a&&!a.startOfLine;)a=a.prev;return a?a.indent+x:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}}),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{"../../lib/codemirror":5}],8:[function(t,n){!function(e,t){"object"==typeof n&&"object"==typeof n.exports?n.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(t,n){function r(e){var t=e.length,n=ot.type(e);return"function"===n||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function i(e,t,n){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return ot.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ht.test(t))return ot.filter(t,e,n);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==n})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function a(e){var t=wt[e]={};return ot.each(e.match(xt)||[],function(e,n){t[n]=!0}),t}function s(){gt.addEventListener?(gt.removeEventListener("DOMContentLoaded",l,!1),t.removeEventListener("load",l,!1)):(gt.detachEvent("onreadystatechange",l),t.detachEvent("onload",l))}function l(){(gt.addEventListener||"load"===event.type||"complete"===gt.readyState)&&(s(),ot.ready())}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(kt,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Dt.test(n)?ot.parseJSON(n):n}catch(i){}ot.data(e,t,n)}else n=void 0}return n}function c(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function f(e,t,n,r){if(ot.acceptData(e)){var i,o,a=ot.expando,s=e.nodeType,l=s?ot.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||ot.guid++:a),l[u]||(l[u]=s?{}:{toJSON:ot.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[ot.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[ot.camelCase(t)])):i=o,i}}function d(e,t,n){if(ot.acceptData(e)){var r,i,o=e.nodeType,a=o?ot.cache:e,s=o?e[ot.expando]:ot.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){ot.isArray(t)?t=t.concat(ot.map(t,ot.camelCase)):t in r?t=[t]:(t=ot.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!c(r):!ot.isEmptyObject(r))return}(n||(delete a[s].data,c(a[s])))&&(o?ot.cleanData([e],!0):rt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function h(){return!0}function p(){return!1}function g(){try{return gt.activeElement}catch(e){}}function m(e){var t=Rt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function v(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Tt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Tt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,v(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function y(e){Mt.test(e.type)&&(e.defaultChecked=e.checked)}function b(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function x(e){return e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type,e}function w(e){var t=$t.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function S(e,t){for(var n,r=0;null!=(n=e[r]);r++)ot._data(n,"globalEval",!t||ot._data(t[r],"globalEval"))}function C(e,t){if(1===t.nodeType&&ot.hasData(e)){var n,r,i,o=ot._data(e),a=ot._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)ot.event.add(t,n,s[n][r])}a.data&&(a.data=ot.extend({},a.data))}}function T(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!rt.noCloneEvent&&t[ot.expando]){i=ot._data(t);for(r in i.events)ot.removeEvent(t,r,i.handle);t.removeAttribute(ot.expando)}"script"===n&&t.text!==e.text?(x(t).text=e.text,w(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Mt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function D(e,n){var r,i=ot(n.createElement(e)).appendTo(n.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(i[0]))?r.display:ot.css(i[0],"display");return i.detach(),o}function k(e){var t=gt,n=en[e];return n||(n=D(e,t),"none"!==n&&n||(Zt=(Zt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Zt[0].contentWindow||Zt[0].contentDocument).document,t.write(),t.close(),n=D(e,t),Zt.detach()),en[e]=n),n}function L(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function A(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function N(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=ot._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&Nt(r)&&(o[a]=ot._data(r,"olddisplay",k(r.nodeName)))):(i=Nt(r),(n&&"none"!==n||!i)&&ot._data(r,"olddisplay",i?n:ot.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function _(e,t,n){var r=cn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function M(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=ot.css(e,n+At[o],!0,i)),r?("content"===n&&(a-=ot.css(e,"padding"+At[o],!0,i)),"margin"!==n&&(a-=ot.css(e,"border"+At[o]+"Width",!0,i))):(a+=ot.css(e,"padding"+At[o],!0,i),"padding"!==n&&(a+=ot.css(e,"border"+At[o]+"Width",!0,i)));return a}function E(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=tn(e),a=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=nn(e,t,o),(0>i||null==i)&&(i=e.style[t]),on.test(i))return i;r=a&&(rt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+M(e,t,n||(a?"border":"content"),r,o)+"px"}function j(e,t,n,r,i){return new j.prototype.init(e,t,n,r,i)}function I(){return setTimeout(function(){gn=void 0}),gn=ot.now()}function H(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=At[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function O(e,t,n){for(var r,i=(wn[t]||[]).concat(wn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function R(e,t,n){var r,i,o,a,s,l,u,c,f=this,d={},h=e.style,p=e.nodeType&&Nt(e),g=ot._data(e,"fxshow");n.queue||(s=ot._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,f.always(function(){f.always(function(){s.unqueued--,ot.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],u=ot.css(e,"display"),c="none"===u?ot._data(e,"olddisplay")||k(e.nodeName):u,"inline"===c&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==k(e.nodeName)?h.zoom=1:h.display="inline-block")),n.overflow&&(h.overflow="hidden",rt.shrinkWrapBlocks()||f.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(p?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;p=!0}d[r]=g&&g[r]||ot.style(e,r)}else u=void 0;if(ot.isEmptyObject(d))"inline"===("none"===u?k(e.nodeName):u)&&(h.display=u);else{g?"hidden"in g&&(p=g.hidden):g=ot._data(e,"fxshow",{}),o&&(g.hidden=!p),p?ot(e).show():f.done(function(){ot(e).hide()}),f.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d)a=O(p?g[r]:0,r,f),r in g||(g[r]=a.start,p&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function P(e,t){var n,r,i,o,a;for(n in e)if(r=ot.camelCase(n),i=t[r],o=e[n],ot.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=ot.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function F(e,t,n){var r,i,o=0,a=xn.length,s=ot.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=gn||I(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:gn||I(),duration:n.duration,tweens:[],createTween:function(t,n){var r=ot.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(P(c,u.opts.specialEasing);a>o;o++)if(r=xn[o].call(u,e,c,u.opts))return r;return ot.map(c,O,u),ot.isFunction(u.opts.start)&&u.opts.start.call(e,u),ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function W(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(xt)||[];if(ot.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function z(e,t,n,r){function i(s){var l;return o[s]=!0,ot.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===Vn;return i(t.dataTypes[0])||!o["*"]&&i("*")}function B(e,t){var n,r,i=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&ot.extend(!0,e,n),e}function q(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function U(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(f){return{state:"parsererror",error:a?f:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function V(e,t,n,r){var i;if(ot.isArray(t))ot.each(t,function(t,i){n||Jn.test(e)?r(e,i):V(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==ot.type(t))r(e,t);else for(i in t)V(e+"["+i+"]",t[i],n,r)}function X(){try{return new t.XMLHttpRequest}catch(e){}}function G(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function $(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,K=J.concat,Q=J.push,Z=J.indexOf,et={},tt=et.toString,nt=et.hasOwnProperty,rt={},it="1.11.1",ot=function(e,t){return new ot.fn.init(e,t)},at=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,st=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:it,constructor:ot,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},ot.extend=ot.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1; for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||ot.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(ot.isPlainObject(n)||(t=ot.isArray(n)))?(t?(t=!1,o=e&&ot.isArray(e)?e:[]):o=e&&ot.isPlainObject(e)?e:{},a[r]=ot.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},ot.extend({expando:"jQuery"+(it+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!nt.call(e,"constructor")&&!nt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(rt.ownLast)for(t in e)return nt.call(e,t);for(t in e);return void 0===t||nt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(st,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var i,o=0,a=e.length,s=r(e);if(n){if(s)for(;a>o&&(i=t.apply(e[o],n),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],n),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(at,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(r(Object(e))?ot.merge(n,"string"==typeof e?[e]:e):Q.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(Z)return Z.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,n){var i,o=0,a=e.length,s=r(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,n),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,n),null!=i&&l.push(i);return K.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),ot.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||ot.guid++,r):void 0},now:function(){return+new Date},support:rt}),ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var ct=function(e){function t(e,t,n,r){var i,o,a,s,l,u,f,h,p,g;if((t?t.ownerDocument||t:W)!==E&&M(t),t=t||E,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(I&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&P(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!H||!H.test(e))){if(h=f=F,p=t,g=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=D(e),(f=t.getAttribute("id"))?h=f.replace(xt,"\\$&"):t.setAttribute("id",h),h="[id='"+h+"'] ",l=u.length;l--;)u[l]=h+d(u[l]);p=bt.test(e)&&c(t.parentNode)||t,g=u.join(",")}if(g)try{return Z.apply(n,p.querySelectorAll(g)),n}catch(m){}finally{f||t.removeAttribute("id")}}}return L(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>S.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[F]=!0,e}function i(e){var t=E.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)S.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||$)-(~e.sourceIndex||$);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==G&&e}function f(){}function d(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function h(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=B++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[z,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[F]||(t[F]={}),(s=l[r])&&s[0]===z&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))return!0}}}function p(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function m(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[F]&&(i=v(i)),o&&!o[F]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,f,d=[],h=[],p=a.length,v=r||g(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:m(v,d,e,s,l),b=n?o||(r?e:p||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=m(b,h),i(u,[],s,l),c=u.length;c--;)(f=u[c])&&(b[h[c]]=!(y[h[c]]=f));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(f=b[c])&&u.push(y[c]=f);o(null,b=[],u,l)}for(c=b.length;c--;)(f=b[c])&&(u=o?tt.call(r,f):d[c])>-1&&(r[u]=!(a[u]=f))}}else b=m(b===a?b.splice(p,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=S.relative[e[0].type],a=o||S.relative[" "],s=o?1:0,l=h(function(e){return e===t},a,!0),u=h(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=S.relative[e[s].type])c=[h(p(c),n)];else{if(n=S.filter[e[s].type].apply(null,e[s].matches),n[F]){for(r=++s;i>r&&!S.relative[e[r].type];r++);return v(s>1&&p(c),s>1&&d(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&d(e))}c.push(n)}return p(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,f,d,h=0,p="0",g=r&&[],v=[],y=A,b=r||o&&S.find.TAG("*",u),x=z+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==E&&a);p!==w&&null!=(c=b[p]);p++){if(o&&c){for(f=0;d=e[f++];)if(d(c,a,s)){l.push(c);break}u&&(z=x)}i&&((c=!d&&c)&&h--,r&&g.push(c))}if(h+=p,i&&p!==h){for(f=0;d=n[f++];)d(g,v,a,s);if(r){if(h>0)for(;p--;)g[p]||v[p]||(v[p]=K.call(l));v=m(v)}Z.apply(l,v),u&&!r&&v.length>0&&h+n.length>1&&t.uniqueSort(l)}return u&&(z=x,A=y),g};return i?r(a):a}var x,w,S,C,T,D,k,L,A,N,_,M,E,j,I,H,O,R,P,F="sizzle"+-new Date,W=e.document,z=0,B=0,q=n(),U=n(),V=n(),X=function(e,t){return e===t&&(_=!0),0},G="undefined",$=1<<31,J={}.hasOwnProperty,Y=[],K=Y.pop,Q=Y.push,Z=Y.push,et=Y.slice,tt=Y.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),ft=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),dt=new RegExp(st),ht=new RegExp("^"+ot+"$"),pt={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},gt=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),St=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(Y=et.call(W.childNodes),W.childNodes),Y[W.childNodes.length].nodeType}catch(Ct){Z={apply:Y.length?function(e,t){Q.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},T=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},M=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:W,r=n.defaultView;return n!==E&&9===n.nodeType&&n.documentElement?(E=n,j=n.documentElement,I=!T(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){M()},!1):r.attachEvent&&r.attachEvent("onunload",function(){M()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return j.appendChild(e).id=F,!n.getElementsByName||!n.getElementsByName(F).length}),w.getById?(S.find.ID=function(e,t){if(typeof t.getElementById!==G&&I){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},S.filter.ID=function(e){var t=e.replace(wt,St);return function(e){return e.getAttribute("id")===t}}):(delete S.find.ID,S.filter.ID=function(e){var t=e.replace(wt,St);return function(e){var n=typeof e.getAttributeNode!==G&&e.getAttributeNode("id");return n&&n.value===t}}),S.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==G?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},S.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==G&&I?t.getElementsByClassName(e):void 0},O=[],H=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&H.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||H.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||H.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&H.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||H.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),H.push(",.*:")})),(w.matchesSelector=vt.test(R=j.matches||j.webkitMatchesSelector||j.mozMatchesSelector||j.oMatchesSelector||j.msMatchesSelector))&&i(function(e){w.disconnectedMatch=R.call(e,"div"),R.call(e,"[s!='']:x"),O.push("!=",st)}),H=H.length&&new RegExp(H.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(j.compareDocumentPosition),P=t||vt.test(j.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},X=t?function(e,t){if(e===t)return _=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===W&&P(W,e)?-1:t===n||t.ownerDocument===W&&P(W,t)?1:N?tt.call(N,e)-tt.call(N,t):0:4&r?-1:1)}:function(e,t){if(e===t)return _=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:N?tt.call(N,e)-tt.call(N,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===W?-1:u[i]===W?1:0},n):E},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==E&&M(e),n=n.replace(ft,"='$1']"),!(!w.matchesSelector||!I||O&&O.test(n)||H&&H.test(n)))try{var r=R.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,E,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==E&&M(e),P(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==E&&M(e);var n=S.attrHandle[t.toLowerCase()],r=n&&J.call(S.attrHandle,t.toLowerCase())?n(e,t,!I):void 0;return void 0!==r?r:w.attributes||!I?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(_=!w.detectDuplicates,N=!w.sortStable&&e.slice(0),e.sort(X),_){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return N=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},S=t.selectors={cacheLength:50,createPseudo:r,match:pt,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,St),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,St),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return pt.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&dt.test(n)&&(t=D(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,St).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=q[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&q(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==G&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,f,d,h,p,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===e&&!p&&"nextSibling"}return!0}if(p=[a?m.firstChild:m.lastChild],a&&y){for(c=m[F]||(m[F]={}),u=c[e]||[],h=u[0]===z&&u[1],d=u[0]===z&&u[2],f=h&&m.childNodes[h];f=++h&&f&&f[g]||(d=h=0)||p.pop();)if(1===f.nodeType&&++d&&f===t){c[e]=[z,h,d];break}}else if(y&&(u=(t[F]||(t[F]={}))[e])&&u[0]===z)d=u[1];else for(;(f=++h&&f&&f[g]||(d=h=0)||p.pop())&&((s?f.nodeName.toLowerCase()!==v:1!==f.nodeType)||!++d||(y&&((f[F]||(f[F]={}))[e]=[z,d]),f!==t)););return d-=i,d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,n){var i,o=S.pseudos[e]||S.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[F]?o(n):o.length>1?(i=[e,e,"",n],S.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[F]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return ht.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,St).toLowerCase(),function(t){var n;do if(n=I?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===j},focus:function(e){return e===E.activeElement&&(!E.hasFocus||E.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!S.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return gt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},S.pseudos.nth=S.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})S.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})S.pseudos[x]=l(x);return f.prototype=S.filters=S.pseudos,S.setFilters=new f,D=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=U[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=S.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in S.filter)!(i=pt[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):U(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=V[e+" "];if(!o){for(t||(t=D(e)),n=t.length;n--;)o=y(t[n]),o[F]?r.push(o):i.push(o);o=V(e,b(i,r)),o.selector=e}return o},L=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,f=!r&&D(e=u.selector||e);if(n=n||[],1===f.length){if(o=f[0]=f[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&I&&S.relative[o[1].type]){if(t=(S.find.ID(a.matches[0].replace(wt,St),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=pt.needsContext.test(e)?0:o.length;i--&&(a=o[i],!S.relative[s=a.type]);)if((l=S.find[s])&&(r=l(a.matches[0].replace(wt,St),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&d(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,f))(r,t,!I,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=F.split("").sort(X).join("")===F,w.detectDuplicates=!!_,M(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(E.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(t);ot.find=ct,ot.expr=ct.selectors,ot.expr[":"]=ot.expr.pseudos,ot.unique=ct.uniqueSort,ot.text=ct.getText,ot.isXMLDoc=ct.isXML,ot.contains=ct.contains;var ft=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ht=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))},ot.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;i>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;i>t;t++)ot.find(e,r[t],n);return n=this.pushStack(i>1?ot.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(i(this,e||[],!1))},not:function(e){return this.pushStack(i(this,e||[],!0))},is:function(e){return!!i(this,"string"==typeof e&&ft.test(e)?ot(e):e||[],!1).length}});var pt,gt=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,vt=ot.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof ot?t[0]:t,ot.merge(this,ot.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:gt,!0)),dt.test(n[1])&&ot.isPlainObject(t))for(n in t)ot.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=gt.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=gt,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ot.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(ot):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ot.makeArray(e,this))};vt.prototype=ot.fn,pt=ot(gt);var yt=/^(?:parents|prev(?:Until|All))/,bt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!ot(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),ot.fn.extend({has:function(e){var t,n=ot(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ft.test(e)||"string"!=typeof e?ot(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&ot.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,n){return ot.dir(e,"parentNode",n)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,n){return ot.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return ot.dir(e,"previousSibling",n)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(n,r){var i=ot.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=ot.filter(r,i)),this.length>1&&(bt[e]||(i=ot.unique(i)),yt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var xt=/\S+/g,wt={};ot.Callbacks=function(e){e="string"==typeof e?wt[e]||a(e):ot.extend({},e);var t,n,r,i,o,s,l=[],u=!e.once&&[],c=function(a){for(n=e.memory&&a,r=!0,o=s||0,s=0,i=l.length,t=!0;l&&i>o;o++)if(l[o].apply(a[0],a[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:f.disable())},f={add:function(){if(l){var r=l.length;!function o(t){ot.each(t,function(t,n){var r=ot.type(n);"function"===r?e.unique&&f.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&ot.each(arguments,function(e,n){for(var r;(r=ot.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,o>=r&&o--)}),this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||f.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!r}};return f},ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ot.Deferred(function(n){ot.each(t,function(t,o){var a=ot.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},i={};return r.pipe=r.then,ot.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&ot.isFunction(e.promise)?a:0,l=1===s?e:ot.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&ot.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var St;ot.fn.ready=function(e){return ot.ready.promise().done(e),this},ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!gt.body)return setTimeout(ot.ready);ot.isReady=!0,e!==!0&&--ot.readyWait>0||(St.resolveWith(gt,[ot]),ot.fn.triggerHandler&&(ot(gt).triggerHandler("ready"),ot(gt).off("ready")))}}}),ot.ready.promise=function(e){if(!St)if(St=ot.Deferred(),"complete"===gt.readyState)setTimeout(ot.ready);else if(gt.addEventListener)gt.addEventListener("DOMContentLoaded",l,!1),t.addEventListener("load",l,!1);else{gt.attachEvent("onreadystatechange",l),t.attachEvent("onload",l);var n=!1;try{n=null==t.frameElement&&gt.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!ot.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}s(),ot.ready()}}()}return St.promise(e)};var Ct,Tt="undefined";for(Ct in ot(rt))break;rt.ownLast="0"!==Ct,rt.inlineBlockNeedsLayout=!1,ot(function(){var e,t,n,r;n=gt.getElementsByTagName("body")[0],n&&n.style&&(t=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Tt&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",rt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=gt.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null}(),ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Dt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,kt=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando],!!e&&!c(e)},data:function(e,t,n){return f(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return f(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ot.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=ot.data(o),1===o.nodeType&&!ot._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=ot.camelCase(r.slice(5)),u(o,r,i[r])));ot._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}}),ot.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=ot._data(e,t),n&&(!r||ot.isArray(n)?r=ot._data(e,t,ot.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=ot.queue(e,t),r=n.length,i=n.shift(),o=ot._queueHooks(e,t),a=function(){ot.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return ot._data(e,n)||ot._data(e,n,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue"),ot._removeData(e,n)})})}}),ot.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ot.queue(this[0],e):void 0===t?this:this.each(function(){var n=ot.queue(this,e,t);ot._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=ot.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=ot._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var Lt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,At=["Top","Right","Bottom","Left"],Nt=function(e,t){return e=t||e,"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},_t=ot.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===ot.type(n)){i=!0;for(s in n)ot.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,ot.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(ot(e),n) })),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},Mt=/^(?:checkbox|radio)$/i;!function(){var e=gt.createElement("input"),t=gt.createElement("div"),n=gt.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",rt.leadingWhitespace=3===t.firstChild.nodeType,rt.tbody=!t.getElementsByTagName("tbody").length,rt.htmlSerialize=!!t.getElementsByTagName("link").length,rt.html5Clone="<:nav></:nav>"!==gt.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),rt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,rt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){rt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}}(),function(){var e,n,r=gt.createElement("div");for(e in{submit:!0,change:!0,focusin:!0})n="on"+e,(rt[e+"Bubbles"]=n in t)||(r.setAttribute(n,"t"),rt[e+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Et=/^(?:input|select|textarea)$/i,jt=/^key/,It=/^(?:mouse|pointer|contextmenu)|click/,Ht=/^(?:focusinfocus|focusoutblur)$/,Ot=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,f,d,h,p,g,m=ot._data(e);if(m){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=ot.guid++),(a=m.events)||(a=m.events={}),(c=m.handle)||(c=m.handle=function(e){return typeof ot===Tt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(xt)||[""],s=t.length;s--;)o=Ot.exec(t[s])||[],h=g=o[1],p=(o[2]||"").split(".").sort(),h&&(u=ot.event.special[h]||{},h=(i?u.delegateType:u.bindType)||h,u=ot.event.special[h]||{},f=ot.extend({type:h,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ot.expr.match.needsContext.test(i),namespace:p.join(".")},l),(d=a[h])||(d=a[h]=[],d.delegateCount=0,u.setup&&u.setup.call(e,r,p,c)!==!1||(e.addEventListener?e.addEventListener(h,c,!1):e.attachEvent&&e.attachEvent("on"+h,c))),u.add&&(u.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,f):d.push(f),ot.event.global[h]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,f,d,h,p,g,m=ot.hasData(e)&&ot._data(e);if(m&&(c=m.events)){for(t=(t||"").match(xt)||[""],u=t.length;u--;)if(s=Ot.exec(t[u])||[],h=g=s[1],p=(s[2]||"").split(".").sort(),h){for(f=ot.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,d=c[h]||[],s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;o--;)a=d[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(d.splice(o,1),a.selector&&d.delegateCount--,f.remove&&f.remove.call(e,a));l&&!d.length&&(f.teardown&&f.teardown.call(e,p,m.handle)!==!1||ot.removeEvent(e,h,m.handle),delete c[h])}else for(h in c)ot.event.remove(e,h+t[u],n,r,!0);ot.isEmptyObject(c)&&(delete m.handle,ot._removeData(e,"events"))}},trigger:function(e,n,r,i){var o,a,s,l,u,c,f,d=[r||gt],h=nt.call(e,"type")?e.type:e,p=nt.call(e,"namespace")?e.namespace.split("."):[];if(s=c=r=r||gt,3!==r.nodeType&&8!==r.nodeType&&!Ht.test(h+ot.event.triggered)&&(h.indexOf(".")>=0&&(p=h.split("."),h=p.shift(),p.sort()),a=h.indexOf(":")<0&&"on"+h,e=e[ot.expando]?e:new ot.Event(h,"object"==typeof e&&e),e.isTrigger=i?2:3,e.namespace=p.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),n=null==n?[e]:ot.makeArray(n,[e]),u=ot.event.special[h]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!ot.isWindow(r)){for(l=u.delegateType||h,Ht.test(l+h)||(s=s.parentNode);s;s=s.parentNode)d.push(s),c=s;c===(r.ownerDocument||gt)&&d.push(c.defaultView||c.parentWindow||t)}for(f=0;(s=d[f++])&&!e.isPropagationStopped();)e.type=f>1?l:u.bindType||h,o=(ot._data(s,"events")||{})[e.type]&&ot._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&ot.acceptData(s)&&(e.result=o.apply(s,n),e.result===!1&&e.preventDefault());if(e.type=h,!i&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),n)===!1)&&ot.acceptData(r)&&a&&r[h]&&!ot.isWindow(r)){c=r[a],c&&(r[a]=null),ot.event.triggered=h;try{r[h]()}catch(g){}ot.event.triggered=void 0,c&&(r[a]=c)}return e.result}},dispatch:function(e){e=ot.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=ot.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((ot.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?ot(n,this).index(l)>=0:ot.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[ot.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=It.test(i)?this.mouseHooks:jt.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new ot.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||gt),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||gt,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==g()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===g()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=ot.extend(new ot.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(i,null,t):ot.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},ot.removeEvent=gt.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===Tt&&(e[r]=null),e.detachEvent(r,n))},ot.Event=function(e,t){return this instanceof ot.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?h:p):this.type=e,t&&ot.extend(this,t),this.timeStamp=e&&e.timeStamp||ot.now(),void(this[ot.expando]=!0)):new ot.Event(e,t)},ot.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=h,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=h,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=h,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!ot.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),rt.submitBubbles||(ot.event.special.submit={setup:function(){return ot.nodeName(this,"form")?!1:void ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;n&&!ot._data(n,"submitBubbles")&&(ot.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),ot._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ot.nodeName(this,"form")?!1:void ot.event.remove(this,"._submit")}}),rt.changeBubbles||(ot.event.special.change={setup:function(){return Et.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ot.event.simulate("change",this,e,!0)})),!1):void ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;Et.test(t.nodeName)&&!ot._data(t,"changeBubbles")&&(ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)}),ot._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ot.event.remove(this,"._change"),!Et.test(this.nodeName)}}),rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=ot._data(r,t);i||r.addEventListener(e,n,!0),ot._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=ot._data(r,t)-1;i?ot._data(r,t,i):(r.removeEventListener(e,n,!0),ot._removeData(r,t))}}}),ot.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return ot().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=ot.guid++)),this.each(function(){ot.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){ot.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ot.event.trigger(e,t,n,!0):void 0}});var Rt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Pt=/ jQuery\d+="(?:null|\d+)"/g,Ft=new RegExp("<(?:"+Rt+")[\\s/>]","i"),Wt=/^\s+/,zt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Bt=/<([\w:]+)/,qt=/<tbody/i,Ut=/<|&#?\w+;/,Vt=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Gt=/^$|\/(?:java|ecma)script/i,$t=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Kt=m(gt),Qt=Kt.appendChild(gt.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,ot.extend({clone:function(e,t,n){var r,i,o,a,s,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ft.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e)))for(r=v(o),s=v(e),a=0;null!=(i=s[a]);++a)r[a]&&T(i,r[a]);if(t)if(n)for(s=s||v(e),r=r||v(o),a=0;null!=(i=s[a]);a++)C(i,r[a]);else C(e,o);return r=v(o,"script"),r.length>0&&S(r,!l&&v(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,f=e.length,d=m(t),h=[],p=0;f>p;p++)if(o=e[p],o||0===o)if("object"===ot.type(o))ot.merge(h,o.nodeType?[o]:o);else if(Ut.test(o)){for(s=s||d.appendChild(t.createElement("div")),l=(Bt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(zt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!rt.leadingWhitespace&&Wt.test(o)&&h.push(t.createTextNode(Wt.exec(o)[0])),!rt.tbody)for(o="table"!==l||qt.test(o)?"<table>"!==c[1]||qt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)ot.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(ot.merge(h,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=d.lastChild}else h.push(t.createTextNode(o));for(s&&d.removeChild(s),rt.appendChecked||ot.grep(v(h,"input"),y),p=0;o=h[p++];)if((!r||-1===ot.inArray(o,r))&&(a=ot.contains(o.ownerDocument,o),s=v(d.appendChild(o),"script"),a&&S(s),n))for(i=0;o=s[i++];)Gt.test(o.type||"")&&n.push(o);return s=null,d},cleanData:function(e,t){for(var n,r,i,o,a=0,s=ot.expando,l=ot.cache,u=rt.deleteExpando,c=ot.event.special;null!=(n=e[a]);a++)if((t||ot.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?ot.event.remove(n,r):ot.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Tt?n.removeAttribute(s):n[s]=null,J.push(i))}}}),ot.fn.extend({text:function(e){return _t(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||gt).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=b(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=b(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?ot.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||ot.cleanData(v(n)),n.parentNode&&(t&&ot.contains(n.ownerDocument,n)&&S(v(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ot.cleanData(v(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return ot.clone(this,e,t)})},html:function(e){return _t(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Pt,""):void 0;if(!("string"!=typeof e||Vt.test(e)||!rt.htmlSerialize&&Ft.test(e)||!rt.leadingWhitespace&&Wt.test(e)||Yt[(Bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(zt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(ot.cleanData(v(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ot.cleanData(v(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=K.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,f=u-1,d=e[0],h=ot.isFunction(d);if(h||u>1&&"string"==typeof d&&!rt.checkClone&&Xt.test(d))return this.each(function(n){var r=c.eq(n);h&&(e[0]=d.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=ot.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=ot.map(v(s,"script"),x),i=o.length;u>l;l++)r=s,l!==f&&(r=ot.clone(r,!0,!0),i&&ot.merge(o,v(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,ot.map(o,w),l=0;i>l;l++)r=o[l],Gt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(a,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var n,r=0,i=[],o=ot(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),ot(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Zt,en={};!function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=gt.getElementsByTagName("body")[0],n&&n.style?(t=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Tt&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(gt.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var tn,nn,rn=/^margin/,on=new RegExp("^("+Lt+")(?!px)[a-z%]+$","i"),an=/^(top|right|bottom|left)$/;t.getComputedStyle?(tn=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},nn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||tn(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||ot.contains(e.ownerDocument,e)||(a=ot.style(e,t)),on.test(a)&&rn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):gt.documentElement.currentStyle&&(tn=function(e){return e.currentStyle},nn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||tn(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),on.test(a)&&!an.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function e(){var e,n,r,i;n=gt.getElementsByTagName("body")[0],n&&n.style&&(e=gt.createElement("div"),r=gt.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(e),e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,t.getComputedStyle&&(o="1%"!==(t.getComputedStyle(e,null)||{}).top,a="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width,i=e.appendChild(gt.createElement("div")),i.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",e.style.width="1px",l=!parseFloat((t.getComputedStyle(i,null)||{}).marginRight)),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=e.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=gt.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",rt.opacity="0.5"===r.opacity,rt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",rt.clearCloneStyle="content-box"===n.style.backgroundClip,rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ot.extend(rt,{reliableHiddenOffsets:function(){return null==s&&e(),s},boxSizingReliable:function(){return null==a&&e(),a},pixelPosition:function(){return null==o&&e(),o},reliableMarginRight:function(){return null==l&&e(),l}}))}(),ot.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var sn=/alpha\([^)]*\)/i,ln=/opacity\s*=\s*([^)]*)/,un=/^(none|table(?!-c[ea]).+)/,cn=new RegExp("^("+Lt+")(.*)$","i"),fn=new RegExp("^([+-])=("+Lt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},hn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=nn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=ot.camelCase(t),l=e.style;if(t=ot.cssProps[s]||(ot.cssProps[s]=A(l,s)),a=ot.cssHooks[t]||ot.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=fn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(ot.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||ot.cssNumber[s]||(n+="px"),rt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=ot.camelCase(t);return t=ot.cssProps[s]||(ot.cssProps[s]=A(e.style,s)),a=ot.cssHooks[t]||ot.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=nn(e,t,r)),"normal"===o&&t in hn&&(o=hn[t]),""===n||n?(i=parseFloat(o),n===!0||ot.isNumeric(i)?i||0:o):o}}),ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,n,r){return n?un.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,dn,function(){return E(e,t,r)}):E(e,t,r):void 0},set:function(e,n,r){var i=r&&tn(e);return _(e,n,r?M(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,i),i):0)}}}),rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ln.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===ot.trim(o.replace(sn,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=sn.test(o)?o.replace(sn,i):o+" "+i)}}),ot.cssHooks.marginRight=L(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},nn,[e,"marginRight"]):void 0}),ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+At[r]+t]=o[r]||o[r-2]||o[0];return i}},rn.test(e)||(ot.cssHooks[e+t].set=_)}),ot.fn.extend({css:function(e,t){return _t(this,function(e,t,n){var r,i,o={},a=0;if(ot.isArray(t)){for(r=tn(e),i=t.length;i>a;a++)o[t[a]]=ot.css(e,t[a],!1,r);return o}return void 0!==n?ot.style(e,t,n):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return N(this,!0)},hide:function(){return N(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Nt(this)?ot(this).show():ot(this).hide()})}}),ot.Tween=j,j.prototype={constructor:j,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ot.cssNumber[n]?"":"px")},cur:function(){var e=j.propHooks[this.prop];return e&&e.get?e.get(this):j.propHooks._default.get(this)},run:function(e){var t,n=j.propHooks[this.prop];return this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):j.propHooks._default.set(this),this}},j.prototype.init.prototype=j.prototype,j.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ot.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},j.propHooks.scrollTop=j.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ot.fx=j.prototype.init,ot.fx.step={};var gn,mn,vn=/^(?:toggle|show|hide)$/,yn=new RegExp("^(?:([+-])=|)("+Lt+")([a-z%]*)$","i"),bn=/queueHooks$/,xn=[R],wn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=yn.exec(t),o=i&&i[3]||(ot.cssNumber[e]?"":"px"),a=(ot.cssNumber[e]||"px"!==o&&+r)&&yn.exec(ot.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,ot.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};ot.Animation=ot.extend(F,{tweener:function(e,t){ot.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],wn[n]=wn[n]||[],wn[n].unshift(t)},prefilter:function(e,t){t?xn.unshift(e):xn.push(e)}}),ot.speed=function(e,t,n){var r=e&&"object"==typeof e?ot.extend({},e):{complete:n||!n&&t||ot.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ot.isFunction(t)&&t};return r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ot.isFunction(r.old)&&r.old.call(this),r.queue&&ot.dequeue(this,r.queue)},r},ot.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Nt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=ot.isEmptyObject(e),o=ot.speed(t,n,r),a=function(){var t=F(this,ot.extend({},e),o);(i||ot._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=ot.timers,a=ot._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&bn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&ot.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=ot._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=ot.timers,a=r?r.length:0;for(n.finish=!0,ot.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),ot.each(["toggle","show","hide"],function(e,t){var n=ot.fn[t];ot.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(H(t,!0),e,r,i)}}),ot.each({slideDown:H("show"),slideUp:H("hide"),slideToggle:H("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),ot.timers=[],ot.fx.tick=function(){var e,t=ot.timers,n=0;for(gn=ot.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||ot.fx.stop(),gn=void 0},ot.fx.timer=function(e){ot.timers.push(e),e()?ot.fx.start():ot.timers.pop()},ot.fx.interval=13,ot.fx.start=function(){mn||(mn=setInterval(ot.fx.tick,ot.fx.interval))},ot.fx.stop=function(){clearInterval(mn),mn=null},ot.fx.speeds={slow:600,fast:200,_default:400},ot.fn.delay=function(e,t){return e=ot.fx?ot.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=gt.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=gt.createElement("select"),i=n.appendChild(gt.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",rt.getSetAttribute="t"!==t.className,rt.style=/top/.test(r.getAttribute("style")),rt.hrefNormalized="/a"===r.getAttribute("href"),rt.checkOn=!!e.value,rt.optSelected=i.selected,rt.enctype=!!gt.createElement("form").enctype,n.disabled=!0,rt.optDisabled=!i.disabled,e=gt.createElement("input"),e.setAttribute("value",""),rt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),rt.radioValue="t"===e.value}();var Sn=/\r/g;ot.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=ot.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,ot(this).val()):e,null==i?i="":"number"==typeof i?i+="":ot.isArray(i)&&(i=ot.map(i,function(e){return null==e?"":e+""})),t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=ot.valHooks[i.type]||ot.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(Sn,""):null==n?"":n)}}}),ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(rt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&ot.nodeName(n.parentNode,"optgroup"))){if(t=ot(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=ot.makeArray(t),a=i.length;a--;)if(r=i[a],ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}},rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Cn,Tn,Dn=ot.expr.attrHandle,kn=/^(?:checked|selected)$/i,Ln=rt.getSetAttribute,An=rt.input;ot.fn.extend({attr:function(e,t){return _t(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e) })}}),ot.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Tt?ot.prop(e,t,n):(1===o&&ot.isXMLDoc(e)||(t=t.toLowerCase(),r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Tn:Cn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=ot.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void ot.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(xt);if(o&&1===e.nodeType)for(;n=o[i++];)r=ot.propFix[n]||n,ot.expr.match.bool.test(n)?An&&Ln||!kn.test(n)?e[r]=!1:e[ot.camelCase("default-"+n)]=e[r]=!1:ot.attr(e,n,""),e.removeAttribute(Ln?n:r)},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Tn={set:function(e,t,n){return t===!1?ot.removeAttr(e,n):An&&Ln||!kn.test(n)?e.setAttribute(!Ln&&ot.propFix[n]||n,n):e[ot.camelCase("default-"+n)]=e[n]=!0,n}},ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Dn[t]||ot.find.attr;Dn[t]=An&&Ln||!kn.test(t)?function(e,t,r){var i,o;return r||(o=Dn[t],Dn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Dn[t]=o),i}:function(e,t,n){return n?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}}),An&&Ln||(ot.attrHooks.value={set:function(e,t,n){return ot.nodeName(e,"input")?void(e.defaultValue=t):Cn&&Cn.set(e,t,n)}}),Ln||(Cn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Dn.id=Dn.name=Dn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ot.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Cn.set},ot.attrHooks.contenteditable={set:function(e,t,n){Cn.set(e,""===t?!1:t,n)}},ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Nn=/^(?:input|select|textarea|button|object)$/i,_n=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return _t(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ot.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!ot.isXMLDoc(e),o&&(t=ot.propFix[t]||t,i=ot.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Nn.test(e.nodeName)||_n.test(e.nodeName)&&e.href?0:-1}}}}),rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this}),rt.enctype||(ot.propFix.enctype="encoding");var Mn=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(xt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Mn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=ot.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(xt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Mn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?ot.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(n){ot(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=ot(this),o=e.match(xt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Tt||"boolean"===n)&&(this.className&&ot._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ot._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Mn," ").indexOf(t)>=0)return!0;return!1}}),ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var En=ot.now(),jn=/\?/,In=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var n,r=null,i=ot.trim(e+"");return i&&!ot.trim(i.replace(In,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():ot.error("Invalid JSON: "+e)},ot.parseXML=function(e){var n,r;if(!e||"string"!=typeof e)return null;try{t.DOMParser?(r=new DOMParser,n=r.parseFromString(e,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(e))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e),n};var Hn,On,Rn=/#.*$/,Pn=/([?&])_=[^&]*/,Fn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Wn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,zn=/^(?:GET|HEAD)$/,Bn=/^\/\//,qn=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Un={},Vn={},Xn="*/".concat("*");try{On=location.href}catch(Gn){On=gt.createElement("a"),On.href="",On=On.href}Hn=qn.exec(On.toLowerCase())||[],ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:On,type:"GET",isLocal:Wn.test(Hn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?B(B(e,ot.ajaxSettings),t):B(ot.ajaxSettings,e)},ajaxPrefilter:W(Un),ajaxTransport:W(Vn),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,S=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=q(f,w,n)),y=U(f,y,w,i),i?(f.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(ot.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(ot.etag[o]=x)),204===e||"HEAD"===f.type?S="nocontent":304===e?S="notmodified":(S=y.state,c=y.data,v=y.error,i=!v)):(v=S,(e||!S)&&(S="error",0>e&&(e=0))),w.status=e,w.statusText=(t||S)+"",i?p.resolveWith(d,[c,S,w]):p.rejectWith(d,[w,S,v]),w.statusCode(m),m=void 0,l&&h.trigger(i?"ajaxSuccess":"ajaxError",[w,f,i?c:v]),g.fireWith(d,[w,S]),l&&(h.trigger("ajaxComplete",[w,f]),--ot.active||ot.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,f=ot.ajaxSetup({},t),d=f.context||f,h=f.context&&(d.nodeType||d.jquery)?ot(d):ot.event,p=ot.Deferred(),g=ot.Callbacks("once memory"),m=f.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Fn.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(f.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(p.promise(w).complete=g.add,w.success=w.done,w.error=w.fail,f.url=((e||f.url||On)+"").replace(Rn,"").replace(Bn,Hn[1]+"//"),f.type=t.method||t.type||f.method||f.type,f.dataTypes=ot.trim(f.dataType||"*").toLowerCase().match(xt)||[""],null==f.crossDomain&&(r=qn.exec(f.url.toLowerCase()),f.crossDomain=!(!r||r[1]===Hn[1]&&r[2]===Hn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Hn[3]||("http:"===Hn[1]?"80":"443")))),f.data&&f.processData&&"string"!=typeof f.data&&(f.data=ot.param(f.data,f.traditional)),z(Un,f,t,w),2===b)return w;l=f.global,l&&0===ot.active++&&ot.event.trigger("ajaxStart"),f.type=f.type.toUpperCase(),f.hasContent=!zn.test(f.type),o=f.url,f.hasContent||(f.data&&(o=f.url+=(jn.test(o)?"&":"?")+f.data,delete f.data),f.cache===!1&&(f.url=Pn.test(o)?o.replace(Pn,"$1_="+En++):o+(jn.test(o)?"&":"?")+"_="+En++)),f.ifModified&&(ot.lastModified[o]&&w.setRequestHeader("If-Modified-Since",ot.lastModified[o]),ot.etag[o]&&w.setRequestHeader("If-None-Match",ot.etag[o])),(f.data&&f.hasContent&&f.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",f.contentType),w.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Xn+"; q=0.01":""):f.accepts["*"]);for(i in f.headers)w.setRequestHeader(i,f.headers[i]);if(f.beforeSend&&(f.beforeSend.call(d,w,f)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](f[i]);if(u=z(Vn,f,t,w)){w.readyState=1,l&&h.trigger("ajaxSend",[w,f]),f.async&&f.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},f.timeout));try{b=1,u.send(v,n)}catch(S){if(!(2>b))throw S;n(-1,S)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return ot.get(e,t,n,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}}),ot.each(["get","post"],function(e,t){ot[t]=function(e,n,r,i){return ot.isFunction(n)&&(i=i||r,r=n,n=void 0),ot.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}}),ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(n){ot(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}}),ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))},ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var $n=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Kn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var n,r=[],i=function(e,t){t=ot.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional),ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){i(this.name,this.value)});else for(n in e)V(n,e[n],t,i);return r.join("&").replace($n,"+")},ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qn.test(this.nodeName)&&!Kn.test(e)&&(this.checked||!Mt.test(e))}).map(function(e,t){var n=ot(this).val();return null==n?null:ot.isArray(n)?ot.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||G()}:X;var Zn=0,er={},tr=ot.ajaxSettings.xhr();t.ActiveXObject&&ot(t).on("unload",function(){for(var e in er)er[e](void 0,!0)}),rt.cors=!!tr&&"withCredentials"in tr,tr=rt.ajax=!!tr,tr&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Zn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete er[a],t=void 0,o.onreadystatechange=ot.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=er[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ot.globalEval(e),e}}}),ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=gt.head||ot("head")[0]||gt.documentElement;return{send:function(r,i){t=gt.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var nr=[],rr=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=nr.pop()||ot.expando+"_"+En++;return this[e]=!0,e}}),ot.ajaxPrefilter("json jsonp",function(e,n,r){var i,o,a,s=e.jsonp!==!1&&(rr.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&rr.test(e.data)&&"data");return s||"jsonp"===e.dataTypes[0]?(i=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,s?e[s]=e[s].replace(rr,"$1"+i):e.jsonp!==!1&&(e.url+=(jn.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return a||ot.error(i+" was not called"),a[0]},e.dataTypes[0]="json",o=t[i],t[i]=function(){a=arguments},r.always(function(){t[i]=o,e[i]&&(e.jsonpCallback=n.jsonpCallback,nr.push(i)),a&&ot.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),ot.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||gt;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=ot.buildFragment([e],t,i),i&&i.length&&ot(i).remove(),ot.merge([],r.childNodes))};var ir=ot.fn.load;ot.fn.load=function(e,t,n){if("string"!=typeof e&&ir)return ir.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=ot.trim(e.slice(s,e.length)),e=e.slice(0,s)),ot.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var or=t.document.documentElement;ot.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=ot.css(e,"position"),f=ot(e),d={};"static"===c&&(e.style.position="relative"),s=f.offset(),o=ot.css(e,"top"),l=ot.css(e,"left"),u=("absolute"===c||"fixed"===c)&&ot.inArray("auto",[o,l])>-1,u?(r=f.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),ot.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(d.top=t.top-s.top+a),null!=t.left&&(d.left=t.left-s.left+i),"using"in t?t.using.call(e,d):f.css(d)}},ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,ot.contains(t,i)?(typeof i.getBoundingClientRect!==Tt&&(r=i.getBoundingClientRect()),n=$(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===ot.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ot.nodeName(e[0],"html")||(n=e.offset()),n.top+=ot.css(e[0],"borderTopWidth",!0),n.left+=ot.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-ot.css(r,"marginTop",!0),left:t.left-n.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||or;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||or})}}),ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);ot.fn[e]=function(r){return _t(this,function(e,r,i){var o=$(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?ot(o).scrollLeft():i,n?i:ot(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),ot.each(["top","left"],function(e,t){ot.cssHooks[t]=L(rt.pixelPosition,function(e,n){return n?(n=nn(e,t),on.test(n)?ot(e).position()[t]+"px":n):void 0})}),ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){ot.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return _t(this,function(t,n,r){var i;return ot.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?ot.css(t,n,a):ot.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),ot.fn.size=function(){return this.length},ot.fn.andSelf=ot.fn.addBack,"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var ar=t.jQuery,sr=t.$;return ot.noConflict=function(e){return t.$===ot&&(t.$=sr),e&&t.jQuery===ot&&(t.jQuery=ar),ot},typeof n===Tt&&(t.jQuery=t.$=ot),ot})},{}],9:[function(t,n){!function(t){function r(){try{return u in t&&t[u]}catch(e){return!1}}function i(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(a),f.appendChild(a),a.addBehavior("#default#userData"),a.load(u);var n=e.apply(s,t);return f.removeChild(a),n}}function o(e){return e.replace(/^d/,"___$&").replace(p,"___")}var a,s={},l=t.document,u="localStorage",c="script";if(s.disabled=!1,s.set=function(){},s.get=function(){},s.remove=function(){},s.clear=function(){},s.transact=function(e,t,n){var r=s.get(e);null==n&&(n=t,t=null),"undefined"==typeof r&&(r=t||{}),n(r),s.set(e,r)},s.getAll=function(){},s.forEach=function(){},s.serialize=function(e){return JSON.stringify(e)},s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},r())a=t[u],s.set=function(e,t){return void 0===t?s.remove(e):(a.setItem(e,s.serialize(t)),t)},s.get=function(e){return s.deserialize(a.getItem(e))},s.remove=function(e){a.removeItem(e)},s.clear=function(){a.clear()},s.getAll=function(){var e={};return s.forEach(function(t,n){e[t]=n}),e},s.forEach=function(e){for(var t=0;t<a.length;t++){var n=a.key(t);e(n,s.get(n))}};else if(l.documentElement.addBehavior){var f,d;try{d=new ActiveXObject("htmlfile"),d.open(),d.write("<"+c+">document.w=window</"+c+'><iframe src="/favicon.ico"></iframe>'),d.close(),f=d.w.frames[0].document,a=f.createElement("div")}catch(h){a=l.createElement("div"),f=l.body}var p=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=i(function(e,t,n){return t=o(t),void 0===n?s.remove(t):(e.setAttribute(t,s.serialize(n)),e.save(u),n)}),s.get=i(function(e,t){return t=o(t),s.deserialize(e.getAttribute(t))}),s.remove=i(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),s.clear=i(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var n,r=0;n=t[r];r++)e.removeAttribute(n.name);e.save(u)}),s.getAll=function(){var e={};return s.forEach(function(t,n){e[t]=n}),e},s.forEach=i(function(e,t){for(var n,r=e.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)t(n.name,s.deserialize(e.getAttribute(n.name)))})}try{var g="__storejs__";s.set(g,g),s.get(g)!=g&&(s.disabled=!0),s.remove(g)}catch(h){s.disabled=!0}s.enabled=!s.disabled,"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s}(Function("return this")())},{}],10:[function(e,t){t.exports={name:"yasgui-utils",version:"1.4.1",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"[email protected]",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"[email protected]",_from:"yasgui-utils@^1.4.1"}},{}],11:[function(e,t){window.console=window.console||{log:function(){}},t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":10,"./storage.js":12,"./svg.js":13}],12:[function(e,t){{var n=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,i){"string"==typeof i&&(i=r[i]()),t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement)),n.set(e,{val:t,exp:i,time:(new Date).getTime()})},get:function(e){var t=n.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:9}],13:[function(e,t){t.exports={draw:function(e,n,r){if(e){var i=t.exports.getElement(n,r);i&&(e.append?e.append(i):e.appendChild(i))}},getElement:function(e,t){if(e&&0==e.indexOf("<svg")){t.width||(t.width="100%"),t.height||(t.height="100%");var n=new DOMParser,r=n.parseFromString(e,"text/xml"),i=r.documentElement,o=document.createElement("div");return o.style.display="inline-block",o.style.width=t.width,o.style.height=t.height,o.appendChild(i),o}return!1}}},{}],14:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.2.1",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.0","gulp-notify":"^1.2.5","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^0.2.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.4",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","yasgui-yasqe":"^2.0.1","twitter-bootstrap-3.0.0":"^3.0.0","browserify-transform-tools":"^1.2.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.2.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"jquery.dataTables",global:"jQuery"}}}},{}],15:[function(e,t){t.exports=function(e){var t='"',n=",",r="\n",i=e.head.vars,o=e.results.bindings,a=function(){for(var e=0;e<i.length;e++)u(i[e]);csvString+=r},s=function(){for(var e=0;e<o.length;e++)l(o[e]),csvString+=r},l=function(e){for(var t=0;t<i.length;t++){var n=i[t];u(e.hasOwnProperty(n)?e[n].value:"")}},u=function(e){e.replace(t,t+t),c(e)&&(e=t+e+t),csvString+=" "+e+" "+n},c=function(e){var r=!1;return e.match("[\\w|"+n+"|"+t+"]")&&(r=!0),r};return csvString="",a(),s(),csvString}},{}],16:[function(e,t){var n=e("jquery"),r=t.exports=function(t){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(t.resultsContainer);var i=t.results.getBoolean(),o=null,a=null;i===!0?(o="check",a="True"):i===!1?(o="cross",a="False"):(r.width("140"),a="Could not find boolean value in response"),o&&e("yasgui-utils").svg.draw(r,e("./imgs.js")[o],{width:25,height:25}),n("<span></span>").text(a).appendTo(r)},o=function(){return t.results.getBoolean()===!0||0==t.results.getBoolean()};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":e("../package.json").version,jquery:n.fn.jquery}},{"../package.json":14,"./imgs.js":19,jquery:8,"yasgui-utils":11}],17:[function(e,t){var n=e("jquery");t.exports={output:"table",outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{outputSelector:function(e){return"selector_"+n(e.container).closest("[id]").attr("id")},results:{id:function(e){return"results_"+n(e.container).closest("[id]").attr("id")},maxSize:1e5}}}},{jquery:8}],18:[function(e,t){var n=e("jquery"),r=t.exports=function(e){var t=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){t.empty().appendTo(e.resultsContainer),n("<span class='exception'>ERROR</span>").appendTo(t),n("<p></p>").html(e.results.getException()).appendTo(t)}),o=function(e){return e.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:8}],19:[function(e,t){t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>'} },{}],20:[function(e,t){e("jquery"),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":21,jquery:8}],21:[function(e,t){var n=jQuery=e("jquery");e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var r={},i=n.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},a=function(){return 2!=i.length||1!=i[0].length||1!=i[1].length||"boolean"!=i[0][0]||"1"!=i[1][0]&&"0"!=i[1][0]?!1:(r.boolean="1"==i[1][0]?!0:!1,!0)},s=function(){return i.length>0&&i[0].length>0?(r.head={vars:i[0]},!0):!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var e=1;e<i.length;e++){for(var t={},n=0;n<i[e].length;n++){var a=r.head.vars[n];if(a){var s=i[e][n],l=o(s);t[a]={value:s},l&&(t[a].type=l)}}r.results.bindings.push(t)}return r.head={vars:i[0]},!0}return!1},u=a();if(!u){var c=s();c&&l()}return r}},{"../../lib/jquery.csv-0.71.js":3,jquery:8}],22:[function(e,t){e("jquery"),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:8}],23:[function(e,t){e("jquery"),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":21,jquery:8}],24:[function(e,t){e("jquery"),t.exports=function(t){var n,r,i={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,a=null,s="object"==typeof t&&t.exception?t.exception:null;n="object"==typeof t&&t.contentType?t.contentType.toLowerCase():null,r="object"==typeof t&&t.response?t.response:t;var l=function(){if(o)return o;if(o===!1||s)return!1;var e=function(){if(n)if(n.indexOf("json")>-1){try{o=i.json(r)}catch(e){s=e}a="json"}else if(n.indexOf("xml")>-1){try{o=i.xml(r)}catch(e){s=e}a="xml"}else if(n.indexOf("csv")>-1){try{o=i.csv(r)}catch(e){s=e}a="csv"}else if(n.indexOf("tab-separated")>-1){try{o=i.tsv(r)}catch(e){s=e}a="tsv"}},t=function(){if(o=i.json(r))a="json";else try{o=i.xml(r),o&&(a="xml")}catch(e){}};return e(),o||t(),o||(o=!1),o},u=function(){var e=l();return e&&"head"in e?e.head.vars:null},c=function(){var e=l();return e&&"results"in e?e.results.bindings:null},f=function(){var e=l();return e&&"boolean"in e?e.boolean:null},d=function(){return r},h=function(){var e="";return"string"==typeof r?e=r:"json"==a?e=JSON.stringify(r,void 0,2):"xml"==a&&(e=(new XMLSerializer).serializeToString(r)),e},p=function(){return s},g=function(){return null==a&&l(),a};return o=l(),{getAsJson:l,getOriginalResponse:d,getOriginalResponseAsString:h,getOriginalContentType:function(){return n},getVariables:u,getBindings:c,getBoolean:f,getType:g,getException:p}}},{"./csv.js":20,"./json.js":22,"./tsv.js":23,"./xml.js":25,jquery:8}],25:[function(e,t){{var n=e("jquery");t.exports=function(e){var t=function(e){a.head={};for(var t=0;t<e.childNodes.length;t++){var n=e.childNodes[t];if("variable"==n.nodeName){a.head.vars||(a.head.vars=[]);var r=n.getAttribute("name");r&&a.head.vars.push(r)}}},r=function(e){a.results={},a.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var n=e.childNodes[t],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var s=o.getAttribute("name");if(s){r=r||{},r[s]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){r[s].type=c,r[s].value=u.innerHTML;var f=u.getAttribute("datatype");f&&(r[s].datatype=f)}}}}}r&&a.results.bindings.push(r)}},i=function(e){a.boolean="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=n.parseXML(e):n.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var a={},s=0;s<e.childNodes.length;s++){var l=e.childNodes[s];"head"==l.nodeName&&t(l),"results"==l.nodeName&&r(l),"boolean"==l.nodeName&&i(l)}return a}}},{jquery:8}],26:[function(e,t){var n=e("jquery"),r=e("codemirror");e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/mode/xml/xml.js"),e("codemirror/mode/javascript/javascript.js");var i=t.exports=function(e){var t=n.extend(!0,{},i.defaults),o=function(){var n=t.CodeMirror;n.value=e.results.getOriginalResponseAsString();var i=e.results.getType();i&&("json"==i&&(i={name:"javascript",json:!0}),n.mode=i),r(e.resultsContainer.get()[0],n)},a=function(){if(!e.results)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},s=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),n=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:o,name:"Raw Response",canHandleResults:a,getPriority:2,getDownloadInfo:s}};i.defaults={CodeMirror:{readOnly:!0}},i.version={"YASR-rawResponse":e("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":14,codemirror:5,"codemirror/addon/edit/matchbrackets.js":4,"codemirror/mode/javascript/javascript.js":6,"codemirror/mode/xml/xml.js":7,jquery:8}],27:[function(e,t){var n=e("jquery"),r=e("yasgui-utils"),i=e("./imgs.js");e("../lib/DataTables/media/js/jquery.dataTables.js");var o=t.exports=function(t){var a=null,s={name:"Table",getPriority:10},u=s.options=n.extend(!0,{},o.defaults),c=function(){var e=[],n=t.results.getBindings(),r=t.results.getVariables(),i=null;t.options.getUsedPrefixes&&(i="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var a=[];a.push("");for(var l=n[o],c=0;c<r.length;c++){var f=r[c];a.push(f in l?u.getCellContent?u.getCellContent(t,s,l,f,{rowId:o,colId:c,usedPrefixes:i}):"":"")}e.push(a)}return e},f=function(){a.on("order.dt",function(){d()}),n.extend(!0,u.callbacks,u.handlers),a.delegate("td","click",function(e){if(u.callbacks&&u.callbacks.onCellClick){var t=u.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){u.callbacks&&u.callbacks.onCellMouseEnter&&u.callbacks.onCellMouseEnter(this,e);var t=n(this);u.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&l(t)}).delegate("td","mouseleave",function(e){u.callbacks&&u.callbacks.onCellMouseLeave&&u.callbacks.onCellMouseLeave(this,e)})};s.draw=function(){a=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>'),n(t.resultsContainer).html(a);var e=u.datatable;e.data=c(),e.columns=u.getColumns(t,s),a.DataTable(n.extend(!0,{},e)),d(),f();var r=t.header.outerHeight()-5;r>0&&t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+r+"px").css("margin-bottom","-"+r+"px")};var d=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};a.find(".sortIcons").remove();var t=8,o=13;for(var s in e){var l=n("<div class='sortIcons'></div>").css("float","right").css("margin-right","-12px").width(t).height(o);r.svg.draw(l,i[e[s]],{width:t+2,height:o+1}),a.find("th."+s).append(l)}};return s.canHandleResults=function(){return t.results&&t.results.getVariables()&&t.results.getVariables().length>0},s.getDownloadInfo=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null},s},a=function(e,t,n){var r=n.value;if(n["xml:lang"])r='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var i="http://www.w3.org/2001/XMLSchema#",o=n.datatype;o=0==o.indexOf(i)?"xsd:"+o.substring(i.length):"<"+o+">",r='"'+r+'"^^'+o}return r},s=function(e,t,n,r,i){var o=n[r],s=null;if("uri"==o.type){var l=null,u=visibleString=o.value;if(i.usedPrefixes)for(var c in i.usedPrefixes)if(0==visibleString.indexOf(i.usedPrefixes[c])){visibleString=c+u.substring(i.usedPrefixes[c].length);break}if(t.options.mergeLabelsWithUris){var f="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";n[r+f]&&(visibleString=a(e,t,n[r+f]),l=u)}s="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+visibleString+"</a>"}else s="<span class='nonUri'>"+a(e,t,o)+"</span>";return s},l=function(e){var t=function(){e.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?e.attr("title",n.label):"string"==typeof n&&n.length>0?e.attr("title",n):t()}).fail(t)};o.defaults={getCellContent:s,getColumns:function(e,t){var n=function(n){if(!t.options.mergeLabelsWithUris)return!0;var r="string"==typeof t.options.mergeLabelsWithUris?t.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&e.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];return r.push({title:""}),e.results.getVariables().forEach(function(e){r.push({title:e,visible:n(e)})}),r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!0,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)n("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var r=!1;n(e.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)}),r?n(e.nTableWrapper).find(".dataTables_paginate").show():n(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"12px",orderable:!1,targets:0}]}},o.version={"YASR-table":e("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/DataTables/media/js/jquery.dataTables.js":2,"../package.json":14,"./bindingsToCsv.js":15,"./imgs.js":19,jquery:8,"yasgui-utils":11}]},{},[1])(1)}); //# sourceMappingURL=yasr.bundled.min.js.map
ajax/libs/forerunnerdb/1.4.21/fdb-legacy.min.js
cdnjs/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Core":7,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),g<0&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;f<l;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(g.value===-1)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],!!b&&(c=this._data.indexOf(b),c>-1&&(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0))},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),c===-1&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;b<g;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":33,"./Shared":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a&&(this._store.push(a),this)},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):d.value===-1&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):b===-1?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b&&(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0)):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),b===-1&&this._right?this._right.remove(a):!(1!==b||!this._left)&&this._left.remove(a))},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),e===-1&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),g===-1&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&j!==-1))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":33,"./Shared":39}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){b=b||{},this.sharedPathSolver=o,this._primaryKey=b.primaryKey||"_id",this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()}),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=!a||void 0===a.$ensureKeys||a.$ensureKeys,g=!a||void 0===a.$violationCheck||a.$violationCheck,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){var a;if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary",{primaryKey:this.primaryKey()}),this._primaryCrc=new g("primaryCrc",{primaryKey:this.primaryKey()}),this._crcLookup=new g("crcLookup",{primaryKey:this.primaryKey()});for(a in this._indexByName)this._indexByName.hasOwnProperty(a)&&this._indexByName[a].rebuild();return this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){var d;return"function"==typeof a&&(c=a,a={},b={}),"function"==typeof b&&(c&&(d=c),c=b,b=d||{}),this.find(a,b).filter(c)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b.$replace&&(c=c||{},c.$replace=!0,b=b.$replace),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(g._removeFromIndexes(d),i=g.updateObject(d,e,f.query,f.options,""),g._insertIntoIndexes(d),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):(g._removeFromIndexes(d),i=g.updateObject(d,b,a,c,""),g._insertIntoIndexes(d)),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b,c,d){var e,f={};return f[this._primaryKey]=a,d&&(e=function(a){d(a[0])}),this.update(f,b,c,e)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;if(d&&d.$replace===!0){g=!0,n=b,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);return t}for(s in b)if(b.hasOwnProperty(s)){if(g=!1,!g&&"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;j<k;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(!g&&this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;j<k;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;j<k;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(k<0)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;w<B;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$splicePull":if(void 0!==a[s]){if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePull from a key that is not an array! ("+s+")";if(l=b[s].$index,void 0===l)throw this.logIdentifier()+" Cannot splicePull without a $index integer value!";l<a[s].length&&(this._updateSplicePull(a[s],l),t=!0)}break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else a[s]instanceof Date?this._updateProperty(a,s,b[s]):(u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u);else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;c<f;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0===a.$decouple||a.$decouple,a.$explain=void 0!==a.$explain&&a.$explain,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=[].concat(c.indexMatch[0].lookup)||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&D.indexOf(o)===-1&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0), x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e),x.time("group")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b&&(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c))},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):f.value===-1&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(f.value!==-1)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=[].concat(this._primaryIndex.lookup(a,b,c)),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=[].concat(m.lookup(a,b,c)),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;e<j;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return!!b&&b.name()},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){if(this._indexByName)return this._indexByName[a]},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;c<e;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;c<e;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(!a||a.autoCreate!==!1){if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.deferEmit("create",b._collection[c],"collection",c),this._collection[c]}if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!"}else if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked&&b.isLinked()}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":6,"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&this._collections.indexOf(a)===-1){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);c!==-1&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),b!==-1&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.deferEmit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":39}],6:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":39}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],8:[function(a,b,c){"use strict";var d,e,f,g,h;d=a("./Shared"),h=a("./Overload");var i=function(a,b){this.init.apply(this,arguments)};i.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",i),i.prototype.moduleLoaded=new h({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)&&(b&&b(),!0):d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.shared=d,i.prototype.shared=d,d.addModule("Db",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Constants"),d.mixin(i.prototype,"Mixin.Tags"),d.mixin(i.prototype,"Mixin.Events"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),i.prototype._isServer=!1,d.synthesize(i.prototype,"core"),d.synthesize(i.prototype,"primaryKey"),d.synthesize(i.prototype,"state"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.arrayToCollection=function(a){return(new f).setData(a)},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=new h({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;a<c;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},function:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},boolean:function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;b<d;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;c<e;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof i?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new i(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=i},{"./Collection.js":4,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Matching"),d.mixin(h.prototype,"Mixin.Updating"),d.mixin(h.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,g=a("./Path"),d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.setData=function(a,b){var c,d,e;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){e={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(e[c]=1);a.$unset=e,this.updateObject(this._data,a,{})}else this._data=a;d={type:"setData",data:this.decouple(this._data)},this.emit("immediateChange",d),this.deferEmit("change",d)}return this},h.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},h.prototype.findSub=function(a,b,c,d){return this._findSub([this.find(a)],b,c,d)},h.prototype._findSub=function(a,b,c,d){var f,h,i,j=new g(b),k=a.length,l=new e("__FDB_temp_"+this.objectId()).db(this._db),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},f=0;f<k;f++)if(h=j.value(a[f])[0]){if(l.setData(h),i=l.find(c,d),d.returnFirst&&i.length)return i[0];d.$split?m.subDocs.push(i):m.subDocs=m.subDocs.concat(i),m.subDocTotal+=i.length,m.pathFound=!0}return l.drop(),m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?m:m.subDocs[0]},h.prototype.update=function(a,b,c){var d,e=this.updateObject(this._data,b,a,c);e&&(d={type:"update",data:this.decouple(this._data)},this.emit("immediateChange",d),this.deferEmit("change",d))},h.prototype.updateObject=e.prototype.updateObject,h.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},h.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},h.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},h.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},h.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},h.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},h.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},h.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},h.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},h.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},h.prototype.drop=function(a){return!!this.isDropped()||!!(this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name])&&(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},f.prototype.document=function(a){var b=this;if(a){if(a instanceof h){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new h(a).db(this),b.deferEmit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("Document"),b.exports=h},{"./Collection":4,"./Path":33,"./Shared":39}],10:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;e<=n;e++)for(d=p[e],f=0;f<o;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return g[b][d].indexOf(c)!==-1&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;g<5;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,j<4?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],11:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._baseQuery={},this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"), d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),"function"==typeof this._from.query&&(this._baseQuery=this._from.query()),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return!!this.isDropped()||!!this._from&&(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0)},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=parseInt(c.attr("data-grid-dir")||"-1",10)===-1?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this.emit("beforeChange","sort"),this.emit("beforeSort",h),this._from.orderBy(h),this.emit("sort",h)},l.prototype.query=function(a,b){return this._baseQuery=a,this._baseQueryOptions=b,this},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d=a.decouple(a._baseQuery);b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j,k=e.attr("data-grid-filter"),l=e.attr("data-grid-vartype"),m={},n=e.html(),o=a._db.view("tmpGridFilter_"+a._id+"_"+k);m[k]=1,j={$distinct:m},o.query(j).orderBy(m).from(a._from._from),i=function(){o.refresh()},a._from._from.on("change",i),a.on("drop",function(){a._from&&a._from._from&&a._from._from.off("change",i),o.drop()}),h=['<div class="dropdown" id="'+a._id+"_"+k+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+k+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',n+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+k+'_dropdownMenu"></ul>'),f.append(g),e.html(f),o.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+k+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+k+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+k+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=o.query(),d=b.val();d?c[k]=new RegExp(d,"gi"):delete c[k],o.query(c)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=o.query();delete b[k],o.query(b)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),j=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(j.prop("checked",j.prop("checked")),e=j.is(":checked")):(j.prop("checked",!j.prop("checked")),e=j.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[k],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),l){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[k]=d[k]||{$in:[]},f=d[k].$in,f||(f=d[k].$in=[]),h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[k]}a.emit("beforeChange","filter"),a.emit("beforeFilter",d),a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return!!this.isDropped()||(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":31,"./Shared":39}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return!!this._btree.insert(a)&&(this._size++,!0)},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),q<=o&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=!(!b||!b.debug)&&b.debug,this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),!!this._btree.insert(a)&&(this._size++,!0)},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),!!this._btree.remove(a)&&(this._size--,!0)},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(!(!b||!b.unique)&&b.unique),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;a<d;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];c.indexOf(b)===-1&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;b<f;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],c.indexOf(b)===-1&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":33,"./Shared":39}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b){this.init.apply(this,arguments)};e.prototype.init=function(a,b){b=b||{},this._name=a,this._data={},this._primaryKey=b.primaryKey||"_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=!b||b,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;b<c;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]&&(this._data[a]=b,!0)},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":39}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":30,"./Shared":39}],18:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);b===-1&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;e<g;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e,f=0,g=a("./Overload"),h=a("./Serialiser"),i=new h;e=function(){var a,b,c,d=[];for(b=0;b<256;b++){for(a=b,c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),d={serialiser:i,make:function(a){return i.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;c<b;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,i.reviver())},jStringify:JSON.stringify,objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,e=0,g=a.length;for(d=0;d<g;d++)e+=a.charCodeAt(d)*c;b=e.toString(16)}else f++,b=(f+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new g([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){ return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d},checksum:function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^e[255&(c^a.charCodeAt(b))];return(c^-1)>>>0}},b.exports=d},{"./Overload":31,"./Serialiser":38}],21:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],22:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(a,b)})):this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;c<d;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;c<d;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;i<h;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":31}],23:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return b<c;case"$lte":return b<=c;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;h<j;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;k<m;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$fastIn":return c instanceof Array?c.indexOf(b)!==-1:(console.log(this.logIdentifier()+" Cannot use an $fastIn operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},!e.$rootData["//distinctLookup"][n][b[n]]&&(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],24:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:a<b?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:a<b?1:0}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),e===-1&&(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0)},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b.export,e=b.import,d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g.export,c=g.import,b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1&&(d._trigger[b][c][e].enabled=!0,!0)}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1&&(d._trigger[b][c][e].enabled=!1,!0)}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;g<h;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;f<e;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":31}],27:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updateSplicePull:function(a,b,c){c||(c=1),a.splice(b,c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;c<b;c++)a.pop();d=!0}else if(b<0){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],28:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":39}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return!(!this._db&&!this._from||!this._name)&&(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0)},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){if(this._from)return this._from.primaryKey()},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?(void 0!==c&&c!==!0||this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":39}],30:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":33,"./Shared":39}],31:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),f.indexOf("*")===-1)e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;c<d;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],32:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(), b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(a,b,c){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._sources.indexOf(a)===-1&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking'));var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.deferEmit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":39}],33:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&b.indexOf(".")===-1)return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;k<f;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;i<e;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":39}],34:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){return this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){return this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){return b?c(b):void o.setItem(a,d,function(a){if(c){if(a)return void c(a);c(!1,d,e)}})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a,function(a,d){return a?void(b&&b(a)):void c.decode(d,b)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a,function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},function:function(a){this.isDropped()||this.drop(!0,a)},boolean:function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){return b?void(a&&a(b)):void c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,f,g){c.deferEmit("save",e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"}),a&&setTimeout(function(){a(b,e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"})},1)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?(b.deferEmit("load",e),a&&a(c)):b.remove({},function(){d=d||[],b.insert(d,function(){b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),b.deferEmit("load",e,f),a&&a(c,e,f)})})})}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({function:function(a){this.$main.call(this,void 0,a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e,f,g,h=this;if(c=this._collection,d=Object.keys(c),e=d.length,e<=0)return b(!1);f=function(a){a?b&&b(a):(e--,e<=0&&(h.deferEmit("load"),b&&b(!1)))};for(g in c)c.hasOwnProperty(g)&&(a?c[g].loadCustom(a,f):c[g].load(f))}}),d.prototype.save=new l({function:function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e,f,g,h=this;if(c=this._collection,d=Object.keys(c),e=d.length,e<=0)return b(!1);f=function(a){a?b&&b(a):(e--,e<=0&&(h.deferEmit("save"),b&&b(!1)))};for(g in c)c.hasOwnProperty(g)&&(a.custom?c[g].saveCustom(f):c[g].save(f))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,async:41,localforage:77}],35:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,f<d&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":39,pako:78}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;if(a){a=this.jParse(a);try{if(d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),!d)return void(c&&c("Crypto failed to decrypt data, incorrect password?",d,b))}catch(a){return void(c&&c("Crypto failed to decrypt data, incorrect password?",d,b))}c&&c(!1,d,b)}else c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":39,"crypto-js":50}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":39}],38:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date&&(a.toJSON=function(){return"$date:"+this.toISOString()},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$date:"))return a.convert(new Date(b.substr(6)))}),this.registerHandler("$regexp",function(a){return a instanceof RegExp&&(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0)},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],39:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.935",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return("setData"===g||"insert"===g||"update"===g||"remove"===g)&&(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,!!(c||d||e)&&(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),!f.dataArr.length&&!f.removeArr.length||(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0)))},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(a,b,c,d){var e={$and:[this.query(),a]};this._from.update.call(this._from,e,b,c,d)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;d<c;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;d<c;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.addTrigger=function(){return this._data.addTrigger.apply(this._data,arguments)},o.prototype.removeTrigger=function(){return this._data.removeTrigger.apply(this._data,arguments)},o.prototype.ignoreTriggers=function(){return this._data.ignoreTriggers.apply(this._data,arguments)},o.prototype.addLinkIO=function(){return this._data.addLinkIO.apply(this._data,arguments)},o.prototype.removeLinkIO=function(){return this._data.removeLinkIO.apply(this._data,arguments)},o.prototype.willTrigger=function(){return this._data.willTrigger.apply(this._data,arguments)},o.prototype.processTrigger=function(){return this._data.processTrigger.apply(this._data,arguments)},o.prototype._triggerIndexOf=function(){return this._data._triggerIndexOf.apply(this._data,arguments)},o.prototype.drop=function(a){return!this.isDropped()&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this.decouple(this._querySettings.query)},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(), void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,d<0&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;d<c;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.deferEmit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked&&a.isLinked()}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(a,b,c){(function(a,d){!function(a,d){"object"==typeof c&&"undefined"!=typeof b?d(c):"function"==typeof define&&define.amd?define(["exports"],d):d(a.async=a.async||{})}(this,function(c){"use strict";function e(a){return a}function f(a,b,c){switch(c.length){case 0:return a.call(b);case 1:return a.call(b,c[0]);case 2:return a.call(b,c[0],c[1]);case 3:return a.call(b,c[0],c[1],c[2])}return a.apply(b,c)}function g(a,b,c){return b=hb(void 0===b?a.length-1:b,0),function(){for(var d=arguments,e=-1,g=hb(d.length-b,0),h=Array(g);++e<g;)h[e]=d[b+e];e=-1;for(var i=Array(b+1);++e<b;)i[e]=d[e];return i[b]=c(h),f(a,this,i)}}function h(a){return function(){return a}}function i(a){var b=typeof a;return null!=a&&("object"==b||"function"==b)}function j(a){var b=i(a)?mb.call(a):"";return b==ib||b==jb||b==kb}function k(a){return!!rb&&rb in a}function l(a){if(null!=a){try{return tb.call(a)}catch(a){}try{return a+""}catch(a){}}return""}function m(a){if(!i(a)||k(a))return!1;var b=j(a)?Ab:vb;return b.test(l(a))}function n(a,b){return null==a?void 0:a[b]}function o(a,b){var c=n(a,b);return m(c)?c:void 0}function p(a){var b=0,c=0;return function(){var d=Fb(),e=Eb-(d-c);if(c=d,e>0){if(++b>=Db)return arguments[0]}else b=0;return a.apply(void 0,arguments)}}function q(a,b){return Gb(g(a,b,e),a+"")}function r(a){return q(function(b,c){var d=Hb(function(c,d){var e=this;return a(b,function(a,b){a.apply(e,c.concat([b]))},d)});return c.length?d.apply(this,c):d})}function s(a){return"number"==typeof a&&a>-1&&a%1==0&&a<=Ib}function t(a){return null!=a&&s(a.length)&&!j(a)}function u(){}function v(a){return function(){if(null!==a){var b=a;a=null,b.apply(this,arguments)}}}function w(a,b){for(var c=-1,d=Array(a);++c<a;)d[c]=b(c);return d}function x(a){return null!=a&&"object"==typeof a}function y(a){return x(a)&&Nb.call(a)==Lb}function z(){return!1}function A(a,b){return b=null==b?Zb:b,!!b&&("number"==typeof a||$b.test(a))&&a>-1&&a%1==0&&a<b}function B(a){return x(a)&&s(a.length)&&!!xc[Ac.call(a)]}function C(a){return function(b){return a(b)}}function D(a,b){var c=Sb(a),d=!c&&Rb(a),e=!c&&!d&&Yb(a),f=!c&&!d&&!e&&Hc(a),g=c||d||e||f,h=g?w(a.length,String):[],i=h.length;for(var j in a)!b&&!Jc.call(a,j)||g&&("length"==j||e&&("offset"==j||"parent"==j)||f&&("buffer"==j||"byteLength"==j||"byteOffset"==j)||A(j,i))||h.push(j);return h}function E(a){var b=a&&a.constructor,c="function"==typeof b&&b.prototype||Kc;return a===c}function F(a,b){return function(c){return a(b(c))}}function G(a){if(!E(a))return Lc(a);var b=[];for(var c in Object(a))Nc.call(a,c)&&"constructor"!=c&&b.push(c);return b}function H(a){return t(a)?D(a):G(a)}function I(a){var b=-1,c=a.length;return function(){return++b<c?{value:a[b],key:b}:null}}function J(a){var b=-1;return function(){var c=a.next();return c.done?null:(b++,{value:c.value,key:b})}}function K(a){var b=H(a),c=-1,d=b.length;return function(){var e=b[++c];return c<d?{value:a[e],key:e}:null}}function L(a){if(t(a))return I(a);var b=Kb(a);return b?J(b):K(a)}function M(a){return function(){if(null===a)throw new Error("Callback was already called.");var b=a;a=null,b.apply(this,arguments)}}function N(a){return function(b,c,d){function e(a,b){if(i-=1,a)h=!0,d(a);else{if(b===Oc||h&&i<=0)return h=!0,d(null);f()}}function f(){for(;i<a&&!h;){var b=g();if(null===b)return h=!0,void(i<=0&&d(null));i+=1,c(b.value,b.key,M(e))}}if(d=v(d||u),a<=0||!b)return d(null);var g=L(b),h=!1,i=0;f()}}function O(a,b,c,d){N(b)(a,c,d)}function P(a,b){return function(c,d,e){return a(c,b,d,e)}}function Q(a,b,c){function d(a){a?c(a):++f===g&&c(null)}c=v(c||u);var e=0,f=0,g=a.length;for(0===g&&c(null);e<g;e++)b(a[e],e,M(d))}function R(a){return function(b,c,d){return a(Qc,b,c,d)}}function S(a,b,c,d){d=v(d||u),b=b||[];var e=[],f=0;a(b,function(a,b,d){var g=f++;c(a,function(a,b){e[g]=b,d(a)})},function(a){d(a,e)})}function T(a){return function(b,c,d,e){return a(N(c),b,d,e)}}function U(a){return Hb(function(b,c){var d;try{d=a.apply(this,b)}catch(a){return c(a)}i(d)&&"function"==typeof d.then?d.then(function(a){c(null,a)},function(a){c(a.message?a:new Error(a))}):c(null,d)})}function V(a,b){for(var c=-1,d=a?a.length:0;++c<d&&b(a[c],c,a)!==!1;);return a}function W(a){return function(b,c,d){for(var e=-1,f=Object(b),g=d(b),h=g.length;h--;){var i=g[a?h:++e];if(c(f[i],i,f)===!1)break}return b}}function X(a,b){return a&&Xc(a,b,H)}function Y(a,b,c,d){for(var e=a.length,f=c+(d?1:-1);d?f--:++f<e;)if(b(a[f],f,a))return f;return-1}function Z(a){return a!==a}function $(a,b,c){for(var d=c-1,e=a.length;++d<e;)if(a[d]===b)return d;return-1}function _(a,b,c){return b===b?$(a,b,c):Y(a,Z,c)}function aa(a,b){for(var c=-1,d=a?a.length:0,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function ba(a,b){var c=-1,d=a.length;for(b||(b=Array(d));++c<d;)b[c]=a[c];return b}function ca(a){return"symbol"==typeof a||x(a)&&ad.call(a)==$c}function da(a){if("string"==typeof a)return a;if(Sb(a))return aa(a,da)+"";if(ca(a))return dd?dd.call(a):"";var b=a+"";return"0"==b&&1/a==-bd?"-0":b}function ea(a,b,c){var d=-1,e=a.length;b<0&&(b=-b>e?0:e+b),c=c>e?e:c,c<0&&(c+=e),e=b>c?0:c-b>>>0,b>>>=0;for(var f=Array(e);++d<e;)f[d]=a[d+b];return f}function fa(a,b,c){var d=a.length;return c=void 0===c?d:c,!b&&c>=d?a:ea(a,b,c)}function ga(a,b){for(var c=a.length;c--&&_(b,a[c],0)>-1;);return c}function ha(a,b){for(var c=-1,d=a.length;++c<d&&_(b,a[c],0)>-1;);return c}function ia(a){return a.split("")}function ja(a){return jd.test(a)}function ka(a){return a.match(Bd)||[]}function la(a){return ja(a)?ka(a):ia(a)}function ma(a){return null==a?"":da(a)}function na(a,b,c){if(a=ma(a),a&&(c||void 0===b))return a.replace(Cd,"");if(!a||!(b=da(b)))return a;var d=la(a),e=la(b),f=ha(d,e),g=ga(d,e)+1;return fa(d,f,g).join("")}function oa(a){return a=a.toString().replace(Gd,""),a=a.match(Dd)[2].replace(" ",""),a=a?a.split(Ed):[],a=a.map(function(a){return na(a.replace(Fd,""))})}function pa(a,b){var c={};X(a,function(a,b){function d(b,c){var d=aa(e,function(a){return b[a]});d.push(c),a.apply(null,d)}var e;if(Sb(a))e=ba(a),a=e.pop(),c[b]=e.concat(e.length>0?d:a);else if(1===a.length)c[b]=a;else{if(e=oa(a),0===a.length&&0===e.length)throw new Error("autoInject task functions require explicit parameters.");e.pop(),c[b]=e.concat(d)}}),Yc(c,b)}function qa(a){setTimeout(a,0)}function ra(a){return q(function(b,c){a(function(){b.apply(null,c)})})}function sa(){this.head=this.tail=null,this.length=0}function ta(a,b){a.length=1,a.head=a.tail=b}function ua(a,b,c){function d(a,b,c){if(null!=c&&"function"!=typeof c)throw new Error("task callback must be a function");if(h.started=!0,Sb(a)||(a=[a]),0===a.length&&h.idle())return Jd(function(){h.drain()});for(var d=0,e=a.length;d<e;d++){var f={data:a[d],callback:c||u};b?h._tasks.unshift(f):h._tasks.push(f)}Jd(h.process)}function e(a){return q(function(b){f-=1;for(var c=0,d=a.length;c<d;c++){var e=a[c],i=_(g,e,0);i>=0&&g.splice(i),e.callback.apply(e,b),null!=b[0]&&h.error(b[0],e.data)}f<=h.concurrency-h.buffer&&h.unsaturated(),h.idle()&&h.drain(),h.process()})}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var f=0,g=[],h={_tasks:new sa,concurrency:b,payload:c,saturated:u,unsaturated:u,buffer:b/4,empty:u,drain:u,error:u,started:!1,paused:!1,push:function(a,b){d(a,!1,b)},kill:function(){h.drain=u,h._tasks.empty()},unshift:function(a,b){d(a,!0,b)},process:function(){for(;!h.paused&&f<h.concurrency&&h._tasks.length;){var b=[],c=[],d=h._tasks.length;h.payload&&(d=Math.min(d,h.payload));for(var i=0;i<d;i++){var j=h._tasks.shift();b.push(j),c.push(j.data)}0===h._tasks.length&&h.empty(),f+=1,g.push(b[0]),f===h.concurrency&&h.saturated();var k=M(e(b));a(c,k)}},length:function(){return h._tasks.length},running:function(){return f},workersList:function(){return g},idle:function(){return h._tasks.length+f===0},pause:function(){h.paused=!0},resume:function(){if(h.paused!==!1){h.paused=!1;for(var a=Math.min(h.concurrency,h._tasks.length),b=1;b<=a;b++)Jd(h.process)}}};return h}function va(a,b){return ua(a,1,b)}function wa(a,b,c,d){d=v(d||u),Ld(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})}function xa(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function ya(a){return function(b,c,d){return a(Ld,b,c,d)}}function za(a,b,c){return function(d,e,f,g){function h(){g&&g(null,c(!1))}function i(a,d,e){return g?void f(a,function(d,h){g&&(d||b(h))?(d?g(d):g(d,c(!0,a)),g=f=!1,e(d,Oc)):e()}):e()}arguments.length>3?(g=g||u,a(d,e,i,h)):(g=f,g=g||u,f=e,a(d,i,h))}}function Aa(a,b){return b}function Ba(a){return q(function(b,c){b.apply(null,c.concat([q(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&V(c,function(b){console[a](b)}))})]))})}function Ca(a,b,c){function d(b,d){return b?c(b):d?void a(e):c(null)}c=M(c||u);var e=q(function(a,e){return a?c(a):(e.push(d),void b.apply(this,e))});d(null,!0)}function Da(a,b,c){c=M(c||u);var d=q(function(e,f){return e?c(e):b.apply(this,f)?a(d):void c.apply(null,[null].concat(f))});a(d)}function Ea(a,b,c){Da(a,function(){return!b.apply(this,arguments)},c)}function Fa(a,b,c){function d(b){return b?c(b):void a(e)}function e(a,e){return a?c(a):e?void b(d):c(null)}c=M(c||u),a(e)}function Ga(a){return function(b,c,d){return a(b,d)}}function Ha(a,b,c){Qc(a,Ga(b),c)}function Ia(a,b,c,d){N(b)(a,Ga(c),d)}function Ja(a){return Hb(function(b,c){var d=!0;b.push(function(){var a=arguments;d?Jd(function(){c.apply(null,a)}):c.apply(null,a)}),a.apply(this,b),d=!1})}function Ka(a){return!a}function La(a){return function(b){return null==b?void 0:b[a]}}function Ma(a,b,c,d){d=v(d||u);var e=[];a(b,function(a,b,d){c(a,function(c,f){c?d(c):(f&&e.push({index:b,value:a}),d())})},function(a){a?d(a):d(null,aa(e.sort(function(a,b){return a.index-b.index}),La("value")))})}function Na(a,b){function c(a){return a?d(a):void e(c)}var d=M(b||u),e=Ja(a);c()}function Oa(a,b,c,d){d=v(d||u);var e={};O(a,b,function(a,b,d){c(a,b,function(a,c){return a?d(a):(e[b]=c,void d())})},function(a){d(a,e)})}function Pa(a,b){return b in a}function Qa(a,b){var c=Object.create(null),d=Object.create(null);b=b||e;var f=Hb(function(e,f){var g=b.apply(null,e);Pa(c,g)?Jd(function(){f.apply(null,c[g])}):Pa(d,g)?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([q(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;e<f;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f}function Ra(a,b,c){c=c||u;var d=t(b)?[]:{};a(b,function(a,b,c){a(q(function(a,e){e.length<=1&&(e=e[0]),d[b]=e,c(a)}))},function(a){c(a,d)})}function Sa(a,b){Ra(Qc,a,b)}function Ta(a,b,c){Ra(N(b),a,c)}function Ua(a,b){if(b=v(b||u),!Sb(a))return b(new TypeError("First argument to race must be an array of functions"));if(!a.length)return b();for(var c=0,d=a.length;c<d;c++)a[c](b)}function Va(a,b,c,d){var e=ge.call(a).reverse();wa(e,b,c,d)}function Wa(a){return Hb(function(b,c){return b.push(q(function(a,b){if(a)c(null,{error:a});else{var d=null;1===b.length?d=b[0]:b.length>1&&(d=b),c(null,{value:d})}})),a.apply(this,b)})}function Xa(a,b,c,d){Ma(a,b,function(a,b){c(a,function(a,c){a?b(a):b(null,!c)})},d)}function Ya(a){var b;return Sb(a)?b=aa(a,Wa):(b={},X(a,function(a,c){b[c]=Wa.call(this,a)})),b}function Za(a,b,c){function d(a,b){if("object"==typeof b)a.times=+b.times||f,a.intervalFunc="function"==typeof b.interval?b.interval:h(+b.interval||g),a.errorFilter=b.errorFilter;else{if("number"!=typeof b&&"string"!=typeof b)throw new Error("Invalid arguments for async.retry");a.times=+b||f}}function e(){b(function(a){a&&j++<i.times&&("function"!=typeof i.errorFilter||i.errorFilter(a))?setTimeout(e,i.intervalFunc(j)):c.apply(null,arguments)})}var f=5,g=0,i={times:f,intervalFunc:h(g)};if(arguments.length<3&&"function"==typeof a?(c=b||u,b=a):(d(i,a),c=c||u),"function"!=typeof b)throw new Error("Invalid arguments for async.retry");var j=1;e()}function $a(a,b){Ra(Ld,a,b)}function _a(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}Rc(a,function(a,c){b(a,function(b,d){return b?c(b):void c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,aa(b.sort(d),La("value")))})}function ab(a,b,c){function d(){h||(f.apply(null,arguments),clearTimeout(g))}function e(){var b=a.name||"anonymous",d=new Error('Callback function "'+b+'" timed out.');d.code="ETIMEDOUT",c&&(d.info=c),h=!0,f(d)}var f,g,h=!1;return Hb(function(c,h){f=h,g=setTimeout(e,b),a.apply(null,c.concat(d))})}function bb(a,b,c,d){for(var e=-1,f=pe(oe((b-a)/(c||1)),0),g=Array(f);f--;)g[d?f:++e]=a,a+=c;return g}function cb(a,b,c,d){Tc(bb(0,a,1),b,c,d)}function db(a,b,c,d){3===arguments.length&&(d=c,c=b,b=Sb(a)?[]:{}),d=v(d||u),Qc(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})}function eb(a){return function(){return(a.unmemoized||a).apply(null,arguments)}}function fb(a,b,c){if(c=M(c||u),!a())return c(null);var d=q(function(e,f){return e?c(e):a()?b(d):void c.apply(null,[null].concat(f))});b(d)}function gb(a,b,c){fb(function(){return!a.apply(this,arguments)},b,c)}var hb=Math.max,ib="[object Function]",jb="[object GeneratorFunction]",kb="[object Proxy]",lb=Object.prototype,mb=lb.toString,nb="object"==typeof d&&d&&d.Object===Object&&d,ob="object"==typeof self&&self&&self.Object===Object&&self,pb=nb||ob||Function("return this")(),qb=pb["__core-js_shared__"],rb=function(){var a=/[^.]+$/.exec(qb&&qb.keys&&qb.keys.IE_PROTO||"");return a?"Symbol(src)_1."+a:""}(),sb=Function.prototype,tb=sb.toString,ub=/[\\^$.*+?()[\]{}|]/g,vb=/^\[object .+?Constructor\]$/,wb=Function.prototype,xb=Object.prototype,yb=wb.toString,zb=xb.hasOwnProperty,Ab=RegExp("^"+yb.call(zb).replace(ub,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bb=function(){try{var a=o(Object,"defineProperty");return a({},"",{}),a}catch(a){}}(),Cb=Bb?function(a,b){return Bb(a,"toString",{configurable:!0,enumerable:!1,value:h(b),writable:!0})}:e,Db=500,Eb=16,Fb=Date.now,Gb=p(Cb),Hb=function(a){return q(function(b){var c=b.pop();a.call(this,b,c)})},Ib=9007199254740991,Jb="function"==typeof Symbol&&Symbol.iterator,Kb=function(a){return Jb&&a[Jb]&&a[Jb]()},Lb="[object Arguments]",Mb=Object.prototype,Nb=Mb.toString,Ob=Object.prototype,Pb=Ob.hasOwnProperty,Qb=Ob.propertyIsEnumerable,Rb=y(function(){return arguments}())?y:function(a){return x(a)&&Pb.call(a,"callee")&&!Qb.call(a,"callee")},Sb=Array.isArray,Tb="object"==typeof c&&c&&!c.nodeType&&c,Ub=Tb&&"object"==typeof b&&b&&!b.nodeType&&b,Vb=Ub&&Ub.exports===Tb,Wb=Vb?pb.Buffer:void 0,Xb=Wb?Wb.isBuffer:void 0,Yb=Xb||z,Zb=9007199254740991,$b=/^(?:0|[1-9]\d*)$/,_b="[object Arguments]",ac="[object Array]",bc="[object Boolean]",cc="[object Date]",dc="[object Error]",ec="[object Function]",fc="[object Map]",gc="[object Number]",hc="[object Object]",ic="[object RegExp]",jc="[object Set]",kc="[object String]",lc="[object WeakMap]",mc="[object ArrayBuffer]",nc="[object DataView]",oc="[object Float32Array]",pc="[object Float64Array]",qc="[object Int8Array]",rc="[object Int16Array]",sc="[object Int32Array]",tc="[object Uint8Array]",uc="[object Uint8ClampedArray]",vc="[object Uint16Array]",wc="[object Uint32Array]",xc={};xc[oc]=xc[pc]=xc[qc]=xc[rc]=xc[sc]=xc[tc]=xc[uc]=xc[vc]=xc[wc]=!0,xc[_b]=xc[ac]=xc[mc]=xc[bc]=xc[nc]=xc[cc]=xc[dc]=xc[ec]=xc[fc]=xc[gc]=xc[hc]=xc[ic]=xc[jc]=xc[kc]=xc[lc]=!1;var yc,zc=Object.prototype,Ac=zc.toString,Bc="object"==typeof c&&c&&!c.nodeType&&c,Cc=Bc&&"object"==typeof b&&b&&!b.nodeType&&b,Dc=Cc&&Cc.exports===Bc,Ec=Dc&&nb.process,Fc=function(){try{return Ec&&Ec.binding("util")}catch(a){}}(),Gc=Fc&&Fc.isTypedArray,Hc=Gc?C(Gc):B,Ic=Object.prototype,Jc=Ic.hasOwnProperty,Kc=Object.prototype,Lc=F(Object.keys,Object),Mc=Object.prototype,Nc=Mc.hasOwnProperty,Oc={},Pc=P(O,1/0),Qc=function(a,b,c){var d=t(a)?Q:Pc;d(a,b,c)},Rc=R(S),Sc=r(Rc),Tc=T(S),Uc=P(Tc,1),Vc=r(Uc),Wc=q(function(a,b){return q(function(c){return a.apply(null,b.concat(c))})}),Xc=W(),Yc=function(a,b,c){function d(a,b){r.push(function(){h(a,b)})}function e(){if(0===r.length&&0===n)return c(null,m);for(;r.length&&n<b;){var a=r.shift();a()}}function f(a,b){var c=p[a];c||(c=p[a]=[]),c.push(b)}function g(a){var b=p[a]||[];V(b,function(a){a()}),e()}function h(a,b){if(!o){var d=M(q(function(b,d){if(n--,d.length<=1&&(d=d[0]),b){var e={};X(m,function(a,b){e[b]=a}),e[a]=d,o=!0,p=[],c(b,e)}else m[a]=d,g(a)}));n++;var e=b[b.length-1];b.length>1?e(m,d):e(d)}}function i(){for(var a,b=0;s.length;)a=s.pop(),b++,V(j(a),function(a){0===--t[a]&&s.push(a)});if(b!==l)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function j(b){var c=[];return X(a,function(a,d){Sb(a)&&_(a,b,0)>=0&&c.push(d)}),c}"function"==typeof b&&(c=b,b=null),c=v(c||u);var k=H(a),l=k.length;if(!l)return c(null);b||(b=l);var m={},n=0,o=!1,p={},r=[],s=[],t={};X(a,function(b,c){if(!Sb(b))return d(c,[b]),void s.push(c);var e=b.slice(0,b.length-1),g=e.length;return 0===g?(d(c,b),void s.push(c)):(t[c]=g,void V(e,function(h){if(!a[h])throw new Error("async.auto task `"+c+"` has a non-existent dependency in "+e.join(", "));f(h,function(){g--,0===g&&d(c,b)})}))}),i(),e()},Zc=pb.Symbol,$c="[object Symbol]",_c=Object.prototype,ad=_c.toString,bd=1/0,cd=Zc?Zc.prototype:void 0,dd=cd?cd.toString:void 0,ed="\\ud800-\\udfff",fd="\\u0300-\\u036f\\ufe20-\\ufe23",gd="\\u20d0-\\u20f0",hd="\\ufe0e\\ufe0f",id="\\u200d",jd=RegExp("["+id+ed+fd+gd+hd+"]"),kd="\\ud800-\\udfff",ld="\\u0300-\\u036f\\ufe20-\\ufe23",md="\\u20d0-\\u20f0",nd="\\ufe0e\\ufe0f",od="["+kd+"]",pd="["+ld+md+"]",qd="\\ud83c[\\udffb-\\udfff]",rd="(?:"+pd+"|"+qd+")",sd="[^"+kd+"]",td="(?:\\ud83c[\\udde6-\\uddff]){2}",ud="[\\ud800-\\udbff][\\udc00-\\udfff]",vd="\\u200d",wd=rd+"?",xd="["+nd+"]?",yd="(?:"+vd+"(?:"+[sd,td,ud].join("|")+")"+xd+wd+")*",zd=xd+wd+yd,Ad="(?:"+[sd+pd+"?",pd,td,ud,od].join("|")+")",Bd=RegExp(qd+"(?="+qd+")|"+Ad+zd,"g"),Cd=/^\s+|\s+$/g,Dd=/^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Ed=/,/,Fd=/(=.+)?(\s*)$/,Gd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Hd="function"==typeof setImmediate&&setImmediate,Id="object"==typeof a&&"function"==typeof a.nextTick;yc=Hd?setImmediate:Id?a.nextTick:qa;var Jd=ra(yc);sa.prototype.removeLink=function(a){return a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev,a.prev=a.next=null,this.length-=1,a},sa.prototype.empty=sa,sa.prototype.insertAfter=function(a,b){b.prev=a,b.next=a.next,a.next?a.next.prev=b:this.tail=b,a.next=b,this.length+=1},sa.prototype.insertBefore=function(a,b){b.prev=a.prev,b.next=a,a.prev?a.prev.next=b:this.head=b,a.prev=b,this.length+=1},sa.prototype.unshift=function(a){this.head?this.insertBefore(this.head,a):ta(this,a)},sa.prototype.push=function(a){this.tail?this.insertAfter(this.tail,a):ta(this,a)},sa.prototype.shift=function(){return this.head&&this.removeLink(this.head)},sa.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)};var Kd,Ld=P(O,1),Md=q(function(a){return q(function(b){var c=this,d=b[b.length-1];"function"==typeof d?b.pop():d=u,wa(a,b,function(a,b,d){b.apply(c,a.concat([q(function(a,b){d(a,b)})]))},function(a,b){d.apply(c,[a].concat(b))})})}),Nd=q(function(a){return Md.apply(null,a.reverse())}),Od=R(xa),Pd=ya(xa),Qd=q(function(a){var b=[null].concat(a);return Hb(function(a,c){return c.apply(this,b)})}),Rd=za(Qc,e,Aa),Sd=za(O,e,Aa),Td=za(Ld,e,Aa),Ud=Ba("dir"),Vd=P(Ia,1),Wd=za(Qc,Ka,Ka),Xd=za(O,Ka,Ka),Yd=P(Xd,1),Zd=R(Ma),$d=T(Ma),_d=P($d,1),ae=Ba("log"),be=P(Oa,1/0),ce=P(Oa,1);Kd=Id?a.nextTick:Hd?setImmediate:qa;var de=ra(Kd),ee=function(a,b){return ua(function(b,c){a(b[0],c)},b,1)},fe=function(a,b){var c=ee(a,b);return c.push=function(a,b,d){if(null==d&&(d=u),"function"!=typeof d)throw new Error("task callback must be a function");if(c.started=!0,Sb(a)||(a=[a]),0===a.length)return Jd(function(){c.drain()});b=b||0;for(var e=c._tasks.head;e&&b>=e.priority;)e=e.next;for(var f=0,g=a.length;f<g;f++){var h={data:a[f],priority:b,callback:d};e?c._tasks.insertBefore(e,h):c._tasks.push(h)}Jd(c.process)},delete c.unshift,c},ge=Array.prototype.slice,he=R(Xa),ie=T(Xa),je=P(ie,1),ke=function(a,b){return b||(b=a,a=null),Hb(function(c,d){function e(a){b.apply(null,c.concat([a]))}a?Za(a,e,d):Za(e,d)})},le=za(Qc,Boolean,e),me=za(O,Boolean,e),ne=P(me,1),oe=Math.ceil,pe=Math.max,qe=P(cb,1/0),re=P(cb,1),se=function(a,b){function c(e){if(d===a.length)return b.apply(null,[null].concat(e));var f=M(q(function(a,d){return a?b.apply(null,[a].concat(d)):void c(d)}));e.push(f);var g=a[d++];g.apply(null,e)}if(b=v(b||u),!Sb(a))return b(new Error("First argument to waterfall must be an array of functions"));if(!a.length)return b();var d=0;c([])},te={applyEach:Sc,applyEachSeries:Vc,apply:Wc,asyncify:U,auto:Yc,autoInject:pa,cargo:va,compose:Nd,concat:Od,concatSeries:Pd,constant:Qd,detect:Rd,detectLimit:Sd,detectSeries:Td,dir:Ud,doDuring:Ca,doUntil:Ea,doWhilst:Da,during:Fa,each:Ha,eachLimit:Ia,eachOf:Qc,eachOfLimit:O,eachOfSeries:Ld,eachSeries:Vd,ensureAsync:Ja,every:Wd,everyLimit:Xd,everySeries:Yd,filter:Zd,filterLimit:$d,filterSeries:_d,forever:Na,log:ae,map:Rc,mapLimit:Tc,mapSeries:Uc,mapValues:be,mapValuesLimit:Oa,mapValuesSeries:ce,memoize:Qa,nextTick:de,parallel:Sa,parallelLimit:Ta,priorityQueue:fe,queue:ee,race:Ua,reduce:wa,reduceRight:Va,reflect:Wa,reflectAll:Ya,reject:he,rejectLimit:ie,rejectSeries:je,retry:Za,retryable:ke,seq:Md,series:$a,setImmediate:Jd,some:le,someLimit:me,someSeries:ne,sortBy:_a,timeout:ab,times:qe,timesLimit:cb,timesSeries:re,transform:db,unmemoize:eb,until:gb,waterfall:se,whilst:fb,all:Wd,any:le,forEach:Ha,forEachSeries:Vd,forEachLimit:Ia,forEachOf:Qc,forEachOfSeries:Ld,forEachOfLimit:O,inject:wa,foldl:wa,foldr:Va,select:Zd,selectLimit:$d,selectSeries:_d,wrapSync:U};c.default=te,c.applyEach=Sc,c.applyEachSeries=Vc,c.apply=Wc,c.asyncify=U,c.auto=Yc,c.autoInject=pa,c.cargo=va,c.compose=Nd,c.concat=Od,c.concatSeries=Pd,c.constant=Qd,c.detect=Rd,c.detectLimit=Sd,c.detectSeries=Td,c.dir=Ud,c.doDuring=Ca,c.doUntil=Ea,c.doWhilst=Da,c.during=Fa,c.each=Ha,c.eachLimit=Ia,c.eachOf=Qc,c.eachOfLimit=O,c.eachOfSeries=Ld,c.eachSeries=Vd,c.ensureAsync=Ja,c.every=Wd,c.everyLimit=Xd,c.everySeries=Yd,c.filter=Zd,c.filterLimit=$d,c.filterSeries=_d,c.forever=Na,c.log=ae,c.map=Rc,c.mapLimit=Tc,c.mapSeries=Uc,c.mapValues=be,c.mapValuesLimit=Oa,c.mapValuesSeries=ce,c.memoize=Qa,c.nextTick=de,c.parallel=Sa,c.parallelLimit=Ta,c.priorityQueue=fe,c.queue=ee,c.race=Ua,c.reduce=wa,c.reduceRight=Va,c.reflect=Wa,c.reflectAll=Ya,c.reject=he,c.rejectLimit=ie,c.rejectSeries=je,c.retry=Za,c.retryable=ke,c.seq=Md,c.series=$a,c.setImmediate=Jd,c.some=le,c.someLimit=me,c.someSeries=ne,c.sortBy=_a,c.timeout=ab,c.times=qe,c.timesLimit=cb,c.timesSeries=re,c.transform=db,c.unmemoize=eb,c.until=gb,c.waterfall=se,c.whilst=fb,c.all=Wd,c.allLimit=Xd,c.allSeries=Yd,c.any=le,c.anyLimit=me,c.anySeries=ne,c.find=Rd,c.findLimit=Sd,c.findSeries=Td,c.forEach=Ha,c.forEachSeries=Vd,c.forEachLimit=Ia,c.forEachOf=Qc,c.forEachOfSeries=Ld,c.forEachOfLimit=O,c.inject=wa,c.foldl=wa,c.foldr=Va,c.select=Zd,c.selectLimit=$d,c.selectSeries=_d,c.wrapSync=U,Object.defineProperty(c,"__esModule",{value:!0})})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;b<256;b++)b<128?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;b<256;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var a=this._keyPriorReset=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;h<e;h++)if(h<c)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;k<e;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];k<4||h<=4?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;o<i;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;g<d;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){ var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;h<d;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":44}],44:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c=Object.create||function(){function a(){}return function(b){var c;return a.prototype=b,c=new a,a.prototype=null,c}}(),d={},e=d.lib={},f=e.Base=function(){return{extend:function(a){var b=c(this);return a&&b.mixIn(a),b.hasOwnProperty("init")&&this.init!==b.init||(b.init=function(){b.$super.init.apply(this,arguments)}),b.init.prototype=b,b.$super=this,b},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),g=e.WordArray=f.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||i).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;f<e;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;f<e;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=f.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},f=0;f<b;f+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new g.init(d,b)}}),h=d.enc={},i=h.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new g.init(c,b/2)}},j=h.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new g.init(c,b)}},k=h.Utf8={stringify:function(a){try{return decodeURIComponent(escape(j.stringify(a)))}catch(a){throw new Error("Malformed UTF-8 data")}},parse:function(a){return j.parse(unescape(encodeURIComponent(a)))}},l=e.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new g.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=k.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,f=this.blockSize,h=4*f,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*f,k=a.min(4*j,e);if(j){for(var l=0;l<j;l+=f)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new g.init(m,k)},clone:function(){var a=f.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),m=(e.Hasher=l.extend({cfg:f.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){l.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new m.HMAC.init(a,c).finalize(b)}}}),d.algo={});return d}(Math);return a})},{}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b,c){for(var d=[],f=0,g=0;g<b;g++)if(g%4){var h=c[a.charCodeAt(g-1)]<<g%4*2,i=c[a.charCodeAt(g)]>>>6-g%4*2;d[f>>>2]|=(h|i)<<24-f%4*8,f++}return e.create(d,f)}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;f<c;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;k<4&&f+.75*k<c;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var c=a.length,d=this._map,e=this._reverseMap;if(!e){e=this._reverseMap=[];for(var f=0;f<d.length;f++)e[d.charCodeAt(f)]=f}var g=d.charAt(64);if(g){var h=a.indexOf(g);h!==-1&&(c=h)}return b(a,c,e)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],46:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;e<c;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;f<d;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;f<c;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":44}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;k<i;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":43,"./core":44}],49:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;j<c;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":44}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;d<b;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":44}],52:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;a<64;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;g<16;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;j<4;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":44}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;g<c;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":43,"./core":44}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;i<e;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":43,"./core":44}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;h<d;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":43,"./core":44}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":43,"./core":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;g<d;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":43,"./core":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":43,"./core":44}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":43,"./core":44}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":43,"./core":44}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":43,"./core":44}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;q<l;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;s<o;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;c<8;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;c<8;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;f<4;f++)b.call(this);for(var f=0;f<8;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;f<4;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;e<4;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;c<8;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;c<8;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;d<4;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;d<4;d++)b.call(this);for(var d=0;d<8;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;d<4;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;e<4;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;e<4;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;e<256;e++)d[e]=e;for(var e=0,f=0;e<256;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;i<16;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;i<80;i+=1)I=l+a[b+E[i]]|0,I+=i<16?c(m,t,u)+C[0]:i<32?d(m,t,u)+C[1]:i<48?e(m,t,u)+C[2]:i<64?f(m,t,u)+C[3]:g(m,t,u)+C[4],I|=0,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=i<16?g(x,y,z)+D[0]:i<32?f(x,y,z)+D[1]:i<48?e(x,y,z)+D[2]:i<64?d(x,y,z)+D[3]:c(x,y,z)+D[4],I|=0,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;g<5;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":44}],68:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;j<80;j++){if(j<16)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=j<20?(e&f|~e&h)+1518500249:j<40?(e^f^h)+1859775393:j<60?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0, c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":44}],69:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":44,"./sha256":70}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;d<=c;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;e<64;)a(d)&&(e<8&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;n<64;n++){if(n<16)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":44}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;c<24;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;a<5;a++)for(var b=0;b<5;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;g<24;g++){for(var i=0,m=0,n=0;n<7;n++){if(1&f){var o=(1<<n)-1;o<32?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;a<25;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;b<25;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;e<d;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;i<24;i++){for(var n=0;n<5;n++){for(var o=0,p=0,q=0;q<5;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;n<5;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;q<5;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;w<25;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(z<32)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;n<5;n++)for(var q=0;q<5;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;k<i;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;c<25;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":44,"./x64-core":75}],72:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;a<80;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;T<80;T++){var U=k[T];if(T<16)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(W>>>0<_>>>0?1:0),W=W+ea,V=V+da+(W>>>0<ea>>>0?1:0),W=W+ka,V=V+ja+(W>>>0<ka>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(wa>>>0<S>>>0?1:0),wa=wa+ma,xa=xa+la+(wa>>>0<ma>>>0?1:0),wa=wa+va,xa=xa+ua+(wa>>>0<va>>>0?1:0),wa=wa+W,xa=xa+V+(wa>>>0<W>>>0?1:0),ya=qa+oa,za=pa+na+(ya>>>0<qa>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(M>>>0<K>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(E>>>0<wa>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(o>>>0<E>>>0?1:0),q=e.low=q+G,e.high=p+F+(q>>>0<G>>>0?1:0),s=f.low=s+I,f.high=r+H+(s>>>0<I>>>0?1:0),u=g.low=u+K,g.high=t+J+(u>>>0<K>>>0?1:0),w=h.low=w+M,h.high=v+L+(w>>>0<M>>>0?1:0),y=i.low=y+O,i.high=x+N+(y>>>0<O>>>0?1:0),A=l.low=A+Q,l.high=z+P+(A>>>0<Q>>>0?1:0),C=m.low=C+S,m.high=B+R+(C>>>0<S>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":44,"./x64-core":75}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;d<56;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;g<16;g++){for(var h=f[g]=[],l=k[g],d=0;d<24;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;d<7;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;d<16;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;f<16;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;k<8;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;d<b;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;d<c;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":44}],76:[function(a,b,c){function d(){throw new Error("setTimeout has not been defined")}function e(){throw new Error("clearTimeout has not been defined")}function f(a){if(l===setTimeout)return setTimeout(a,0);if((l===d||!l)&&setTimeout)return l=setTimeout,setTimeout(a,0);try{return l(a,0)}catch(b){try{return l.call(null,a,0)}catch(b){return l.call(this,a,0)}}}function g(a){if(m===clearTimeout)return clearTimeout(a);if((m===e||!m)&&clearTimeout)return m=clearTimeout,clearTimeout(a);try{return m(a)}catch(b){try{return m.call(null,a)}catch(b){return m.call(this,a)}}}function h(){q&&o&&(q=!1,o.length?p=o.concat(p):r=-1,p.length&&i())}function i(){if(!q){var a=f(h);q=!0;for(var b=p.length;b;){for(o=p,p=[];++r<b;)o&&o[r].run();r=-1,b=p.length}o=null,q=!1,g(a)}}function j(a,b){this.fun=a,this.array=b}function k(){}var l,m,n=b.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:d}catch(a){l=d}try{m="function"==typeof clearTimeout?clearTimeout:e}catch(a){m=e}}();var o,p=[],q=!1,r=-1;n.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];p.push(new j(a,b)),1!==p.length||q||f(i)},j.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=k,n.addListener=k,n.once=k,n.off=k,n.removeListener=k,n.removeAllListeners=k,n.emit=k,n.binding=function(a){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(a){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},{}],77:[function(a,b,c){(function(d){!function(a){if("object"==typeof c&&"undefined"!=typeof b)b.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof d?d:"undefined"!=typeof self?self:this,e.localforage=a()}}(function(){return function b(c,d,e){function f(h,i){if(!d[h]){if(!c[h]){var j="function"==typeof a&&a;if(!i&&j)return j(h,!0);if(g)return g(h,!0);var k=new Error("Cannot find module '"+h+"'");throw k.code="MODULE_NOT_FOUND",k}var l=d[h]={exports:{}};c[h][0].call(l.exports,function(a){var b=c[h][1][a];return f(b?b:a)},l,l.exports,b,c,d,e)}return d[h].exports}for(var g="function"==typeof a&&a,h=0;h<e.length;h++)f(e[h]);return f}({1:[function(a,b,c){"use strict";function d(){}function e(a){if("function"!=typeof a)throw new TypeError("resolver must be a function");this.state=s,this.queue=[],this.outcome=void 0,a!==d&&i(this,a)}function f(a,b,c){this.promise=a,"function"==typeof b&&(this.onFulfilled=b,this.callFulfilled=this.otherCallFulfilled),"function"==typeof c&&(this.onRejected=c,this.callRejected=this.otherCallRejected)}function g(a,b,c){o(function(){var d;try{d=b(c)}catch(b){return p.reject(a,b)}d===a?p.reject(a,new TypeError("Cannot resolve promise with itself")):p.resolve(a,d)})}function h(a){var b=a&&a.then;if(a&&"object"==typeof a&&"function"==typeof b)return function(){b.apply(a,arguments)}}function i(a,b){function c(b){f||(f=!0,p.reject(a,b))}function d(b){f||(f=!0,p.resolve(a,b))}function e(){b(d,c)}var f=!1,g=j(e);"error"===g.status&&c(g.value)}function j(a,b){var c={};try{c.value=a(b),c.status="success"}catch(a){c.status="error",c.value=a}return c}function k(a){return a instanceof this?a:p.resolve(new this(d),a)}function l(a){var b=new this(d);return p.reject(b,a)}function m(a){function b(a,b){function d(a){g[b]=a,++h!==e||f||(f=!0,p.resolve(j,g))}c.resolve(a).then(d,function(a){f||(f=!0,p.reject(j,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=new Array(e),h=0,i=-1,j=new this(d);++i<e;)b(a[i],i);return j}function n(a){function b(a){c.resolve(a).then(function(a){f||(f=!0,p.resolve(h,a))},function(a){f||(f=!0,p.reject(h,a))})}var c=this;if("[object Array]"!==Object.prototype.toString.call(a))return this.reject(new TypeError("must be an array"));var e=a.length,f=!1;if(!e)return this.resolve([]);for(var g=-1,h=new this(d);++g<e;)b(a[g]);return h}var o=a(2),p={},q=["REJECTED"],r=["FULFILLED"],s=["PENDING"];b.exports=c=e,e.prototype.catch=function(a){return this.then(null,a)},e.prototype.then=function(a,b){if("function"!=typeof a&&this.state===r||"function"!=typeof b&&this.state===q)return this;var c=new this.constructor(d);if(this.state!==s){var e=this.state===r?a:b;g(c,e,this.outcome)}else this.queue.push(new f(c,a,b));return c},f.prototype.callFulfilled=function(a){p.resolve(this.promise,a)},f.prototype.otherCallFulfilled=function(a){g(this.promise,this.onFulfilled,a)},f.prototype.callRejected=function(a){p.reject(this.promise,a)},f.prototype.otherCallRejected=function(a){g(this.promise,this.onRejected,a)},p.resolve=function(a,b){var c=j(h,b);if("error"===c.status)return p.reject(a,c.value);var d=c.value;if(d)i(a,d);else{a.state=r,a.outcome=b;for(var e=-1,f=a.queue.length;++e<f;)a.queue[e].callFulfilled(b)}return a},p.reject=function(a,b){a.state=q,a.outcome=b;for(var c=-1,d=a.queue.length;++c<d;)a.queue[c].callRejected(b);return a},c.resolve=k,c.reject=l,c.all=m,c.race=n},{2:2}],2:[function(a,b,c){(function(a){"use strict";function c(){k=!0;for(var a,b,c=l.length;c;){for(b=l,l=[],a=-1;++a<c;)b[a]();c=l.length}k=!1}function d(a){1!==l.push(a)||k||e()}var e,f=a.MutationObserver||a.WebKitMutationObserver;if(f){var g=0,h=new f(c),i=a.document.createTextNode("");h.observe(i,{characterData:!0}),e=function(){i.data=g=++g%2}}else if(a.setImmediate||"undefined"==typeof a.MessageChannel)e="document"in a&&"onreadystatechange"in a.document.createElement("script")?function(){var b=a.document.createElement("script");b.onreadystatechange=function(){c(),b.onreadystatechange=null,b.parentNode.removeChild(b),b=null},a.document.documentElement.appendChild(b)}:function(){setTimeout(c,0)};else{var j=new a.MessageChannel;j.port1.onmessage=c,e=function(){j.port2.postMessage(0)}}var k,l=[];b.exports=d}).call(this,"undefined"!=typeof d?d:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],3:[function(a,b,c){(function(b){"use strict";"function"!=typeof b.Promise&&(b.Promise=a(1))}).call(this,"undefined"!=typeof d?d:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{1:1}],4:[function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function e(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(a){}}function f(){try{return!!fa&&(!("undefined"!=typeof openDatabase&&"undefined"!=typeof navigator&&navigator.userAgent&&/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent))&&(fa&&"function"==typeof fa.open&&"undefined"!=typeof IDBKeyRange))}catch(a){return!1}}function g(){return"function"==typeof openDatabase}function h(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&localStorage.setItem}catch(a){return!1}}function i(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(f){if("TypeError"!==f.name)throw f;for(var c="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,d=new c,e=0;e<a.length;e+=1)d.append(a[e]);return d.getBlob(b.type)}}function j(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function k(a,b,c){"function"==typeof b&&a.then(b),"function"==typeof c&&a.catch(c)}function l(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;e<b;e++)d[e]=a.charCodeAt(e);return c}function m(a){return new ia(function(b){var c=i([""]);a.objectStore(ja).put(c,"key"),a.onabort=function(a){a.preventDefault(),a.stopPropagation(),b(!1)},a.oncomplete=function(){var a=navigator.userAgent.match(/Chrome\/(\d+)/),c=navigator.userAgent.match(/Edge\//);b(c||!a||parseInt(a[1],10)>=43)}}).catch(function(){return!1})}function n(a){return"boolean"==typeof ga?ia.resolve(ga):m(a).then(function(a){return ga=a})}function o(a){var b=ha[a.name],c={};c.promise=new ia(function(a){c.resolve=a}),b.deferredOperations.push(c),b.dbReady?b.dbReady=b.dbReady.then(function(){return c.promise}):b.dbReady=c.promise}function p(a){var b=ha[a.name],c=b.deferredOperations.pop();c&&c.resolve()}function q(a,b){return new ia(function(c,d){if(a.db){if(!b)return c(a.db);o(a),a.db.close()}var e=[a.name];b&&e.push(a.version);var f=fa.open.apply(fa,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(ja)}catch(c){if("ConstraintError"!==c.name)throw c;console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result),p(a)}})}function r(a){return q(a,!1)}function s(a){return q(a,!0)}function t(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function u(a){return new ia(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function v(a){var b=l(atob(a.data));return i([b],{type:a.type})}function w(a){return a&&a.__local_forage_encoded_blob}function x(a){var b=this,c=b._initReady().then(function(){var a=ha[b._dbInfo.name];if(a&&a.dbReady)return a.dbReady});return k(c,a,a),c}function y(a){function b(){return ia.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];ha||(ha={});var f=ha[d.name];f||(f={ forages:[],db:null,dbReady:null,deferredOperations:[]},ha[d.name]=f),f.forages.push(c),c._initReady||(c._initReady=c.ready,c.ready=x);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==c&&g.push(i._initReady().catch(b))}var j=f.forages.slice(0);return ia.all(g).then(function(){return d.db=f.db,r(d)}).then(function(a){return d.db=a,t(d,c._defaultConfig.version)?s(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b=0;b<j.length;b++){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function z(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),w(a)&&(a=v(a)),b(a)},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function A(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;w(d)&&(d=v(d));var e=a(d,c.key,h++);void 0!==e?b(e):c.continue()}else b()},g.onerror=function(){d(g.error)}}).catch(d)});return j(d,b),d}function B(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,"[object Blob]"===ka.call(b)?n(f.db).then(function(a){return a?b:u(b)}):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0),d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)};var h=g.put(b,a)}).catch(e)});return j(e,c),e}function C(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g.delete(a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}}).catch(d)});return j(d,b),d}function D(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}}).catch(c)});return j(c,a),c}function E(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function F(a,b){var c=this,d=new ia(function(b,d){return a<0?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}}).catch(d)});return j(d,b),d}function G(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b.continue()):void a(g)},f.onerror=function(){c(f.error)}}).catch(c)});return j(c,a),c}function H(a){var b,c,d,e,f,g=.75*a.length,h=a.length,i=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var j=new ArrayBuffer(g),k=new Uint8Array(j);for(b=0;b<h;b+=4)c=ma.indexOf(a[b]),d=ma.indexOf(a[b+1]),e=ma.indexOf(a[b+2]),f=ma.indexOf(a[b+3]),k[i++]=c<<2|d>>4,k[i++]=(15&d)<<4|e>>2,k[i++]=(3&e)<<6|63&f;return j}function I(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=ma[c[b]>>2],d+=ma[(3&c[b])<<4|c[b+1]>>4],d+=ma[(15&c[b+1])<<2|c[b+2]>>6],d+=ma[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}function J(a,b){var c="";if(a&&(c=Da.call(a)),a&&("[object ArrayBuffer]"===c||a.buffer&&"[object ArrayBuffer]"===Da.call(a.buffer))){var d,e=pa;a instanceof ArrayBuffer?(d=a,e+=ra):(d=a.buffer,"[object Int8Array]"===c?e+=ta:"[object Uint8Array]"===c?e+=ua:"[object Uint8ClampedArray]"===c?e+=va:"[object Int16Array]"===c?e+=wa:"[object Uint16Array]"===c?e+=ya:"[object Int32Array]"===c?e+=xa:"[object Uint32Array]"===c?e+=za:"[object Float32Array]"===c?e+=Aa:"[object Float64Array]"===c?e+=Ba:b(new Error("Failed to get type for BinaryArray"))),b(e+I(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=na+a.type+"~"+I(this.result);b(pa+sa+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(c){console.error("Couldn't convert value into a JSON string: ",a),b(null,c)}}function K(a){if(a.substring(0,qa)!==pa)return JSON.parse(a);var b,c=a.substring(Ca),d=a.substring(qa,Ca);if(d===sa&&oa.test(c)){var e=c.match(oa);b=e[1],c=c.substring(e[0].length)}var f=H(c);switch(d){case ra:return f;case sa:return i([f],{type:b});case ta:return new Int8Array(f);case ua:return new Uint8Array(f);case va:return new Uint8ClampedArray(f);case wa:return new Int16Array(f);case ya:return new Uint16Array(f);case xa:return new Int32Array(f);case za:return new Uint32Array(f);case Aa:return new Float32Array(f);case Ba:return new Float64Array(f);default:throw new Error("Unkown type: "+d)}}function L(a){var b=this,c={db:null};if(a)for(var d in a)c[d]="string"!=typeof a[d]?a[d].toString():a[d];var e=new ia(function(a,d){try{c.db=openDatabase(c.name,String(c.version),c.description,c.size)}catch(a){return d(a)}c.db.transaction(function(e){e.executeSql("CREATE TABLE IF NOT EXISTS "+c.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=c,a()},function(a,b){d(b)})})});return c.serializer=Ea,e}function M(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function N(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;h<g;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function O(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new ia(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})}).catch(e)});return j(e,c),e}function P(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function Q(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function R(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function S(a,b){var c=this,d=new ia(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})}).catch(d)});return j(d,b),d}function T(a){var b=this,c=new ia(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})}).catch(c)});return j(c,a),c}function U(a){var b=this,c={};if(a)for(var d in a)c[d]=a[d];return c.keyPrefix=c.name+"/",c.storeName!==b._defaultConfig.storeName&&(c.keyPrefix+=c.storeName+"/"),b._dbInfo=c,c.serializer=Ea,ia.resolve()}function V(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=localStorage.length-1;c>=0;c--){var d=localStorage.key(c);0===d.indexOf(a)&&localStorage.removeItem(d)}});return j(c,a),c}function W(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=localStorage.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return j(d,b),d}function X(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=localStorage.length,g=1,h=0;h<f;h++){var i=localStorage.key(h);if(0===i.indexOf(d)){var j=localStorage.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return j(d,b),d}function Y(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=localStorage.key(a)}catch(a){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return j(d,b),d}function Z(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=localStorage.length,d=[],e=0;e<c;e++)0===localStorage.key(e).indexOf(a.keyPrefix)&&d.push(localStorage.key(e).substring(a.keyPrefix.length));return d});return j(c,a),c}function $(a){var b=this,c=b.keys().then(function(a){return a.length});return j(c,a),c}function _(a,b){var c=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;localStorage.removeItem(b.keyPrefix+a)});return j(d,b),d}function aa(a,b,c){var d=this;"string"!=typeof a&&(console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new ia(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{localStorage.setItem(g.keyPrefix+a,b),e(c)}catch(a){"QuotaExceededError"!==a.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==a.name||f(a),f(a)}})})});return j(e,c),e}function ba(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function ca(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(Na(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function da(a){for(var b in Ia)if(Ia.hasOwnProperty(b)&&Ia[b]===a)return!0;return!1}var ea="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},fa=e();"undefined"==typeof Promise&&"undefined"!=typeof a&&a(3);var ga,ha,ia=Promise,ja="local-forage-detect-blob-support",ka=Object.prototype.toString,la={_driver:"asyncStorage",_initStorage:y,iterate:A,getItem:z,setItem:B,removeItem:C,clear:D,length:E,key:F,keys:G},ma="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",na="~~local_forage_type~",oa=/^~~local_forage_type~([^~]+)~/,pa="__lfsc__:",qa=pa.length,ra="arbf",sa="blob",ta="si08",ua="ui08",va="uic8",wa="si16",xa="si32",ya="ur16",za="ui32",Aa="fl32",Ba="fl64",Ca=qa+ra.length,Da=Object.prototype.toString,Ea={serialize:J,deserialize:K,stringToBuffer:H,bufferToString:I},Fa={_driver:"webSQLStorage",_initStorage:L,iterate:N,getItem:M,setItem:O,removeItem:P,clear:Q,length:R,key:S,keys:T},Ga={_driver:"localStorageWrapper",_initStorage:U,iterate:X,getItem:W,setItem:aa,removeItem:_,clear:V,length:$,key:Y,keys:Z},Ha={},Ia={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},Ja=[Ia.INDEXEDDB,Ia.WEBSQL,Ia.LOCALSTORAGE],Ka=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],La={description:"",driver:Ja.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},Ma={};Ma[Ia.INDEXEDDB]=f(),Ma[Ia.WEBSQL]=g(),Ma[Ia.LOCALSTORAGE]=h();var Na=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},Oa=function(){function a(b){d(this,a),this.INDEXEDDB=Ia.INDEXEDDB,this.LOCALSTORAGE=Ia.LOCALSTORAGE,this.WEBSQL=Ia.WEBSQL,this._defaultConfig=ca({},La),this._config=ca({},this._defaultConfig,b),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return a.prototype.config=function(a){if("object"===("undefined"==typeof a?"undefined":ea(a))){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},a.prototype.defineDriver=function(a,b,c){var d=new ia(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),f=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(da(a._driver))return void c(f);for(var g=Ka.concat("_initStorage"),h=0;h<g.length;h++){var i=g[h];if(!i||!a[i]||"function"!=typeof a[i])return void c(e)}var j=ia.resolve(!0);"_support"in a&&(j=a._support&&"function"==typeof a._support?a._support():ia.resolve(!!a._support)),j.then(function(c){Ma[d]=c,Ha[d]=a,b()},c)}catch(a){c(a)}});return k(d,b,c),d},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(a,b,c){var d=this,e=ia.resolve().then(function(){if(!da(a)){if(Ha[a])return Ha[a];throw new Error("Driver not found.")}switch(a){case d.INDEXEDDB:return la;case d.LOCALSTORAGE:return Ga;case d.WEBSQL:return Fa}});return k(e,b,c),e},a.prototype.getSerializer=function(a){var b=ia.resolve(Ea);return k(b,a),b},a.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return k(c,a,a),c},a.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready}).catch(b)}d();var g=new Error("No available storage method found.");return f._driverSet=ia.reject(g),f._driverSet}var c=0;return b()}}var f=this;Na(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet.catch(function(){return ia.resolve()}):ia.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})}).catch(function(){d();var a=new Error("No available storage method found.");return f._driverSet=ia.reject(a),f._driverSet}),k(this._driverSet,b,c),this._driverSet},a.prototype.supports=function(a){return!!Ma[a]},a.prototype._extend=function(a){ca(this,a)},a.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},a.prototype._wrapLibraryMethodsWithReady=function(){for(var a=0;a<Ka.length;a++)ba(this,Ka[a])},a.prototype.createInstance=function(b){return new a(b)},a}(),Pa=new Oa;b.exports=Pa},{3:3}]},{},[4])(4)})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],78:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);if(b.header&&h.deflateSetHeader(this.strm,b.header),b.dictionary){var e;if(e="string"==typeof b.dictionary?j.string2buf(b.dictionary):"[object ArrayBuffer]"===m.call(b.dictionary)?new Uint8Array(b.dictionary):b.dictionary,c=h.deflateSetDictionary(this.strm,e),c!==p)throw new Error(k[c]);this._dict_set=!0}}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===p):d!==r||(this.onEnd(p),e.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l,m=this.strm,o=this.options.chunkSize,p=this.options.dictionary,q=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?m.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?m.input=new Uint8Array(a):m.input=a,m.next_in=0,m.avail_in=m.input.length;do{if(0===m.avail_out&&(m.output=new h.Buf8(o),m.next_out=0,m.avail_out=o),c=g.inflate(m,j.Z_NO_FLUSH),c===j.Z_NEED_DICT&&p&&(l="string"==typeof p?i.string2buf(p):"[object ArrayBuffer]"===n.call(p)?new Uint8Array(p):p,c=g.inflateSetDictionary(this.strm,l)),c===j.Z_BUF_ERROR&&q===!0&&(c=j.Z_OK,q=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;m.next_out&&(0!==m.avail_out&&c!==j.Z_STREAM_END&&(0!==m.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(m.output,m.next_out),f=m.next_out-e,k=i.buf2string(m.output,e),m.next_out=f,m.avail_out=o-f,f&&h.arraySet(m.output,m.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(m.output,m.next_out)))),0===m.avail_in&&0===m.avail_out&&(q=!0)}while((m.avail_in>0||0===m.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d!==j.Z_SYNC_FLUSH||(this.onEnd(j.Z_OK),m.avail_out=0,!0)},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;b<c;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;b<c;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;f<d;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],82:[function(a,b,c){"use strict";function d(a,b){if(b<65537&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;d<b;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(a){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(a){g=!1}for(var h=new e.Buf8(256),i=0;i<256;i++)h[i]=i>=252?6:i>=248?5:i>=240?4:i>=224?3:i>=192?2:1;h[254]=h[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;f<h;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=c<128?1:c<2048?2:c<65536?3:4;for(b=new e.Buf8(i),g=0,f=0;g<i;f++)c=a.charCodeAt(f),55296===(64512&c)&&f+1<h&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),c<128?b[g++]=c:c<2048?(b[g++]=192|c>>>6,b[g++]=128|63&c):c<65536?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;c<d;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,i=b||a.length,j=new Array(2*i);for(e=0,c=0;c<i;)if(f=a[c++],f<128)j[e++]=f;else if(g=h[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&c<i;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:f<65536?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return c<0?b:0===c?b:c+h[a[c]]>b?c:b}},{"./common":81}],83:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],84:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],85:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;c<256;c++){a=c;for(var d=0;d<8;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;h<g;h++)a=a>>>8^e[255&(a^b[h])];return a^-1}var f=d();b.exports=e},{}],86:[function(a,b,c){"use strict";function d(a,b){return a.msg=I[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(E.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){F._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,E.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=G(a.adler,b,e,c):2===a.state.wrap&&(a.adler=H(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-la?a.strstart-(a.w_size-la):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ka,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&f<m);if(d=ka-(m-f),f=m-ka,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-la)){E.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ja)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ja-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ja)););}while(a.lookahead<la&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===J)return ua;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ua;if(a.strstart-a.block_start>=a.w_size-la&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ua:ua}function o(a,b){for(var c,d;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c)),a.match_length>=ja)if(d=F._tr_tally(a,a.strstart-a.match_start,a.match_length-ja),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ja){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function p(a,b){for(var c,d,e;;){if(a.lookahead<la){if(m(a),a.lookahead<la&&b===J)return ua;if(0===a.lookahead)break}if(c=0,a.lookahead>=ja&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ja-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-la&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===U||a.match_length===ja&&a.strstart-a.match_start>4096)&&(a.match_length=ja-1)),a.prev_length>=ja&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ja,d=F._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ja),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ja-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ja-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ua}else if(a.match_available){if(d=F._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ua}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=F._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ja-1?a.strstart:ja-1,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ka){if(m(a),a.lookahead<=ka&&b===J)return ua;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ja&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ka;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&e<f);a.match_length=ka-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ja?(c=F._tr_tally(a,1,a.match_length-ja),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===J)return ua;break}if(a.match_length=0,c=F._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ua}return a.insert=0,b===M?(h(a,!0),0===a.strm.avail_out?wa:xa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ua:va}function s(a,b,c,d,e){ this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=D[a.level].max_lazy,a.good_match=D[a.level].good_length,a.nice_match=D[a.level].nice_length,a.max_chain_length=D[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ja-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=$,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new E.Buf16(2*ha),this.dyn_dtree=new E.Buf16(2*(2*fa+1)),this.bl_tree=new E.Buf16(2*(2*ga+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new E.Buf16(ia+1),this.heap=new E.Buf16(2*ea+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new E.Buf16(2*ea+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Z,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?na:sa,a.adler=2===b.wrap?0:1,b.last_flush=J,F._tr_init(b),O):d(a,Q)}function w(a){var b=v(a);return b===O&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?Q:(a.state.gzhead=b,O):Q}function y(a,b,c,e,f,g){if(!a)return Q;var h=1;if(b===T&&(b=6),e<0?(h=0,e=-e):e>15&&(h=2,e-=16),f<1||f>_||c!==$||e<8||e>15||b<0||b>9||g<0||g>X)return d(a,Q);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ja-1)/ja),i.window=new E.Buf8(2*i.w_size),i.head=new E.Buf16(i.hash_size),i.prev=new E.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new E.Buf8(i.pending_buf_size),i.d_buf=1*i.lit_bufsize,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,$,aa,ba,Y)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>N||b<0)return a?d(a,Q):Q;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ta&&b!==M)return d(a,0===a.avail_out?S:Q);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===na)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=H(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=oa):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=V||h.level<2?4:0),i(h,ya),h.status=sa);else{var m=$+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=V||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ma),m+=31-m%31,h.status=sa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===oa)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=qa)}else h.status=qa;if(h.status===qa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=H(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=ra)}else h.status=ra;if(h.status===ra&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=sa)):h.status=sa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,O}else if(0===a.avail_in&&e(b)<=e(c)&&b!==M)return d(a,S);if(h.status===ta&&0!==a.avail_in)return d(a,S);if(0!==a.avail_in||0!==h.lookahead||b!==J&&h.status!==ta){var o=h.strategy===V?r(h,b):h.strategy===W?q(h,b):D[h.level].func(h,b);if(o!==wa&&o!==xa||(h.status=ta),o===ua||o===wa)return 0===a.avail_out&&(h.last_flush=-1),O;if(o===va&&(b===K?F._tr_align(h):b!==N&&(F._tr_stored_block(h,0,0,!1),b===L&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,O}return b!==M?O:h.wrap<=0?P:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?O:P)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa&&b!==ta?d(a,Q):(a.state=null,b===sa?d(a,R):O)):Q}function C(a,b){var c,d,e,g,h,i,j,k,l=b.length;if(!a||!a.state)return Q;if(c=a.state,g=c.wrap,2===g||1===g&&c.status!==na||c.lookahead)return Q;for(1===g&&(a.adler=G(a.adler,b,l,0)),c.wrap=0,l>=c.w_size&&(0===g&&(f(c.head),c.strstart=0,c.block_start=0,c.insert=0),k=new E.Buf8(c.w_size),E.arraySet(k,b,l-c.w_size,c.w_size,0),b=k,l=c.w_size),h=a.avail_in,i=a.next_in,j=a.input,a.avail_in=l,a.next_in=0,a.input=b,m(c);c.lookahead>=ja;){d=c.strstart,e=c.lookahead-(ja-1);do c.ins_h=(c.ins_h<<c.hash_shift^c.window[d+ja-1])&c.hash_mask,c.prev[d&c.w_mask]=c.head[c.ins_h],c.head[c.ins_h]=d,d++;while(--e);c.strstart=d,c.lookahead=ja-1,m(c)}return c.strstart+=c.lookahead,c.block_start=c.strstart,c.insert=c.lookahead,c.lookahead=0,c.match_length=c.prev_length=ja-1,c.match_available=0,a.next_in=i,a.input=j,a.avail_in=h,c.wrap=g,O}var D,E=a("../utils/common"),F=a("./trees"),G=a("./adler32"),H=a("./crc32"),I=a("./messages"),J=0,K=1,L=3,M=4,N=5,O=0,P=1,Q=-2,R=-3,S=-5,T=-1,U=1,V=2,W=3,X=4,Y=0,Z=2,$=8,_=9,aa=15,ba=8,ca=29,da=256,ea=da+1+ca,fa=30,ga=19,ha=2*ea+1,ia=15,ja=3,ka=258,la=ka+ja+1,ma=32,na=42,oa=69,pa=73,qa=91,ra=103,sa=113,ta=666,ua=1,va=2,wa=3,xa=4,ya=3;D=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateSetDictionary=C,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],88:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(q<w&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),q<15&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,q<w&&(p+=B[f++]<<q,q+=8,q<w&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(n<w){if(z+=l+n-w,w-=n,w<x){x-=w;do C[h++]=o[z++];while(--w);if(z=0,n<x){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,w<x){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(f<g&&h<j);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=f<g?5+(g-f):5-(f-g),a.avail_out=h<j?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],89:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=L,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new s.Buf32(pa),b.distcode=b.distdyn=new s.Buf32(qa),b.sane=1,b.back=-1,D):G}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):G}function h(a,b){var c,d;return a&&a.state?(d=a.state,b<0?(c=0,b=-b):(c=(b>>4)+1,b<48&&(b&=15)),b&&(b<8||b>15)?G:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):G}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==D&&(a.state=null),c):G}function j(a){return i(a,sa)}function k(a){if(ta){var b;for(q=new s.Buf32(512),r=new s.Buf32(32),b=0;b<144;)a.lens[b++]=8;for(;b<256;)a.lens[b++]=9;for(;b<280;)a.lens[b++]=7;for(;b<288;)a.lens[b++]=8;for(w(y,a.lens,0,288,q,0,a.work,{bits:9}),b=0;b<32;)a.lens[b++]=5;w(z,a.lens,0,32,r,0,a.work,{bits:5}),ta=!1}a.lencode=q,a.lenbits=9,a.distcode=r,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new s.Buf8(f.wsize)),d>=f.wsize?(s.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),s.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(s.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,r,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new s.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return G;c=a.state,c.mode===W&&(c.mode=X),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=D;a:for(;;)switch(c.mode){case L:if(0===c.wrap){c.mode=X;break}for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0),m=0,n=0,c.mode=M;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=ma;break}if((15&m)!==K){a.msg="unknown compression method",c.mode=ma;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=ma;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?U:W,m=0,n=0;break;case M:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==K){a.msg="unknown compression method",c.mode=ma;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=ma;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=N;case N:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=u(c.check,Ba,4,0)),m=0,n=0,c.mode=O;case O:for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0,c.mode=P;case P:if(1024&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=u(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=Q;case Q:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),s.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=R;case R:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=S;case S:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&q<i);if(512&c.flags&&(c.check=u(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=T;case T:if(512&c.flags){for(;n<16;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=ma;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=W;break;case U:for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=V;case V:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,F;a.adler=c.check=1,c.mode=W;case W:if(b===B||b===C)break a;case X:if(c.last){m>>>=7&n,n-=7&n,c.mode=ja;break}for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=Y;break;case 1:if(k(c),c.mode=ca,b===C){m>>>=2,n-=2;break a}break;case 2:c.mode=_;break;case 3:a.msg="invalid block type",c.mode=ma}m>>>=2,n-=2;break;case Y:for(m>>>=7&n,n-=7&n;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=ma;break}if(c.length=65535&m,m=0,n=0,c.mode=Z,b===C)break a;case Z:c.mode=$;case $:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;s.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=W;break;case _:for(;n<14;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=ma;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.ncode;){for(;n<3;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=w(x,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=ma;break}c.have=0,c.mode=ba;case ba:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(sa<16)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=ma;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=ma;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===ma)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=ma;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=w(y,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=ma;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=w(z,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=ma;break}if(c.mode=ca,b===C)break a;case ca:c.mode=da;case da:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,v(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===W&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ia;break}if(32&ra){c.back=-1,c.mode=W;break}if(64&ra){a.msg="invalid literal/length code",c.mode=ma;break}c.extra=15&ra,c.mode=ea;case ea:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=fa;case fa:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(ta+qa<=n);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=ma;break}c.offset=sa,c.extra=15&ra,c.mode=ga;case ga:if(c.extra){for(za=c.extra;n<za;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=ma;break}c.mode=ha;case ha:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=ma;break}q>c.wnext?(q-=c.wnext,r=c.wsize-q):r=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,r=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[r++];while(--q);0===c.length&&(c.mode=da);break;case ia:if(0===j)break a;f[h++]=c.length,j--,c.mode=da;break;case ja:if(c.wrap){for(;n<32;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?u(c.check,f,p,h-p):t(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=ma;break}m=0,n=0}c.mode=ka;case ka:if(c.wrap&&c.flags){for(;n<32;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=ma;break}m=0,n=0}c.mode=la;case la:xa=E;break a;case ma:xa=H;break a;case na:return I;case oa:default:return G}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<ma&&(c.mode<ja||b!==A))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=na,I):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?u(c.check,f,p,a.next_out-p):t(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===W?128:0)+(c.mode===ca||c.mode===Z?256:0),(0===o&&0===p||b===A)&&xa===D&&(xa=J),xa)}function n(a){if(!a||!a.state)return G;var b=a.state;return b.window&&(b.window=null),a.state=null,D}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?G:(c.head=b,b.done=!1,D)):G}function p(a,b){var c,d,e,f=b.length;return a&&a.state?(c=a.state,0!==c.wrap&&c.mode!==V?G:c.mode===V&&(d=1,d=t(d,b,f,0),d!==c.check)?H:(e=l(a,b,f,f))?(c.mode=na,I):(c.havedict=1,D)):G}var q,r,s=a("../utils/common"),t=a("./adler32"),u=a("./crc32"),v=a("./inffast"),w=a("./inftrees"),x=0,y=1,z=2,A=4,B=5,C=6,D=0,E=1,F=2,G=-2,H=-3,I=-4,J=-5,K=8,L=1,M=2,N=3,O=4,P=5,Q=6,R=7,S=8,T=9,U=10,V=11,W=12,X=13,Y=14,Z=15,$=16,_=17,aa=18,ba=19,ca=20,da=21,ea=22,fa=23,ga=24,ha=25,ia=26,ja=27,ka=28,la=29,ma=30,na=31,oa=32,pa=852,qa=592,ra=15,sa=ra,ta=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateSetDictionary=p,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;D<=e;D++)P[D]=0;for(E=0;E<o;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;F<G&&0===P[F];F++);for(H<F&&(H=F),K=1,D=1;D<=e;D++)if(K<<=1,K-=P[D],K<0)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;D<e;D++)Q[D+1]=Q[D]+P[D];for(E=0;E<o;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;I+J<G&&(K-=P[I+J],!(K<=0));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":81}],91:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],92:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return a<256?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;f<=W;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;c<V;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;d<=W;d++)f[d]=g=g+c[d-1]<<1;for(e=0;e<=b;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;d<Q-1;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;d<16;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;d<T;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;b<=W;b++)g[b]=0;for(a=0;a<=143;)ga[2*a+1]=8,a++,g[8]++;for(;a<=255;)ga[2*a+1]=9,a++,g[9]++;for(;a<=279;)ga[2*a+1]=7,a++,g[7]++;for(;a<=287;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;a<T;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;b<S;b++)a.dyn_ltree[2*b]=0;for(b=0;b<T;b++)a.dyn_dtree[2*b]=0;for(b=0;b<U;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;c<i;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=j<2?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;d<=c;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(h<j?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):h<=10?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;d<=c;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(h<l){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):h<=10?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;e<d;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;b<=31;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;b<R;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,f<=e&&(e=f)):e=f=c+5,c+4<=e&&b!==-1?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":81}],93:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]);
v7/development/src/templates/post/suggested-posts/suggested-posts.js
BigBoss424/portfolio
/* Vendor imports */ import React from 'react' import PropTypes from 'prop-types' /* App imports */ import PostList from '../../../components/post-list' import style from './suggested-posts.module.less' const SuggestedPosts = ({ posts }) => ( <div> <p className={style.title}>Did you like it? Why don't you try also...</p> <PostList posts={posts} /> </div> ) SuggestedPosts.propTypes = { posts: PropTypes.arrayOf( PropTypes.shape({ edge: PropTypes.shape({ node: PropTypes.object, }), }) ).isRequired, } export default SuggestedPosts
src/react/index.js
pabloalonsos/redux-devtools
import React from 'react'; import createDevTools from '../createDevTools'; export const DevTools = createDevTools(React); export { default as LogMonitor } from './LogMonitor'; export { default as DebugPanel } from './DebugPanel';
wp-includes/js/jquery/jquery.js
dennned/ioppie
/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==cb()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===cb()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ab:bb):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:bb,isPropagationStopped:bb,isImmediatePropagationStopped:bb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ab,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ab,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ab,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=bb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=bb),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function db(a){var b=eb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var eb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fb=/ jQuery\d+="(?:null|\d+)"/g,gb=new RegExp("<(?:"+eb+")[\\s/>]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/<tbody/i,lb=/<|&#?\w+;/,mb=/<(?:script|style|link)/i,nb=/checked\s*(?:[^=]|=\s*.checked.)/i,ob=/^$|\/(?:java|ecma)script/i,pb=/^true\/(.*)/,qb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,rb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?"<table>"!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Cb[0].contentWindow||Cb[0].contentDocument).document,b.write(),b.close(),c=Eb(a,b),Cb.detach()),Db[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Gb=/^margin/,Hb=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ib,Jb,Kb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ib=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Hb.test(g)&&Gb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ib=function(a){return a.currentStyle},Jb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ib(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Hb.test(g)&&!Kb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Lb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Mb=/alpha\([^)]*\)/i,Nb=/opacity\s*=\s*([^)]*)/,Ob=/^(none|table(?!-c[ea]).+)/,Pb=new RegExp("^("+S+")(.*)$","i"),Qb=new RegExp("^([+-])=("+S+")","i"),Rb={position:"absolute",visibility:"hidden",display:"block"},Sb={letterSpacing:"0",fontWeight:"400"},Tb=["Webkit","O","Moz","ms"];function Ub(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Tb.length;while(e--)if(b=Tb[e]+c,b in a)return b;return d}function Vb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fb(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wb(a,b,c){var d=Pb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Yb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ib(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Jb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Hb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xb(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Jb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ub(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ub(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Jb(a,b,d)),"normal"===f&&b in Sb&&(f=Sb[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Ob.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Rb,function(){return Yb(a,b,d)}):Yb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ib(a);return Wb(a,c,d?Xb(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Nb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Mb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Mb.test(f)?f.replace(Mb,e):f+" "+e)}}),m.cssHooks.marginRight=Lb(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Jb,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Gb.test(a)||(m.cssHooks[a+b].set=Wb)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ib(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Vb(this,!0)},hide:function(){return Vb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Zb(a,b,c,d,e){return new Zb.prototype.init(a,b,c,d,e)}m.Tween=Zb,Zb.prototype={constructor:Zb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px") },cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Zb.propHooks.scrollTop=Zb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Zb.prototype.init,m.fx.step={};var $b,_b,ac=/^(?:toggle|show|hide)$/,bc=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cc=/queueHooks$/,dc=[ic],ec={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bc.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bc.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fc(){return setTimeout(function(){$b=void 0}),$b=m.now()}function gc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hc(a,b,c){for(var d,e=(ec[b]||[]).concat(ec["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ic(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fb(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fb(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ac.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fb(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hc(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jc(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kc(a,b,c){var d,e,f=0,g=dc.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$b||fc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$b||fc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jc(k,j.opts.specialEasing);g>f;f++)if(d=dc[f].call(j,a,k,j.opts))return d;return m.map(k,hc,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kc,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],ec[c]=ec[c]||[],ec[c].unshift(b)},prefilter:function(a,b){b?dc.unshift(a):dc.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kc(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gc(b,!0),a,d,e)}}),m.each({slideDown:gc("show"),slideUp:gc("hide"),slideToggle:gc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($b=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$b=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_b||(_b=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_b),_b=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lc=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lc,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mc,nc,oc=m.expr.attrHandle,pc=/^(?:checked|selected)$/i,qc=k.getSetAttribute,rc=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nc:mc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rc&&qc||!pc.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qc?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nc={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rc&&qc||!pc.test(c)?a.setAttribute(!qc&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=oc[b]||m.find.attr;oc[b]=rc&&qc||!pc.test(b)?function(a,b,d){var e,f;return d||(f=oc[b],oc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,oc[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rc&&qc||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mc&&mc.set(a,b,c)}}),qc||(mc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},oc.id=oc.name=oc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mc.set},m.attrHooks.contenteditable={set:function(a,b,c){mc.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sc=/^(?:input|select|textarea|button|object)$/i,tc=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sc.test(a.nodeName)||tc.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var uc=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(uc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(uc," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vc=m.now(),wc=/\?/,xc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yc,zc,Ac=/#.*$/,Bc=/([?&])_=[^&]*/,Cc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Dc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ec=/^(?:GET|HEAD)$/,Fc=/^\/\//,Gc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hc={},Ic={},Jc="*/".concat("*");try{zc=location.href}catch(Kc){zc=y.createElement("a"),zc.href="",zc=zc.href}yc=Gc.exec(zc.toLowerCase())||[];function Lc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mc(a,b,c,d){var e={},f=a===Ic;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nc(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Oc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zc,type:"GET",isLocal:Dc.test(yc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nc(Nc(a,m.ajaxSettings),b):Nc(m.ajaxSettings,a)},ajaxPrefilter:Lc(Hc),ajaxTransport:Lc(Ic),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zc)+"").replace(Ac,"").replace(Fc,yc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yc[1]&&c[2]===yc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yc[3]||("http:"===yc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mc(Hc,k,b,v),2===t)return v;h=k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Ec.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bc.test(e)?e.replace(Bc,"$1_="+vc++):e+(wc.test(e)?"&":"?")+"_="+vc++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mc(Ic,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Oc(k,v,c)),u=Pc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qc=/%20/g,Rc=/\[\]$/,Sc=/\r?\n/g,Tc=/^(?:submit|button|image|reset|file)$/i,Uc=/^(?:input|select|textarea|keygen)/i;function Vc(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rc.test(a)?d(a,e):Vc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vc(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vc(c,a[c],b,e);return d.join("&").replace(Qc,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Uc.test(this.nodeName)&&!Tc.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sc,"\r\n")}}):{name:b.name,value:c.replace(Sc,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zc()||$c()}:Zc;var Wc=0,Xc={},Yc=m.ajaxSettings.xhr();a.ActiveXObject&&m(a).on("unload",function(){for(var a in Xc)Xc[a](void 0,!0)}),k.cors=!!Yc&&"withCredentials"in Yc,Yc=k.ajax=!!Yc,Yc&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xc[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zc(){try{return new a.XMLHttpRequest}catch(b){}}function $c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _c=[],ad=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_c.pop()||m.expando+"_"+vc++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ad.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ad.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ad,"$1"+e):b.jsonp!==!1&&(b.url+=(wc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_c.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bd=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bd)return bd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cd=a.document.documentElement;function dd(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dd(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cd;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cd})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dd(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=Lb(k.pixelPosition,function(a,c){return c?(c=Jb(a,b),Hb.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ed=a.jQuery,fd=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fd),b&&a.jQuery===m&&(a.jQuery=ed),m},typeof b===K&&(a.jQuery=a.$=m),m}); jQuery.noConflict();
node_modules/react/node_modules/fbjs/node_modules/core-js/library/modules/es6.promise.js
laere/country-news
'use strict'; var $ = require('./$') , LIBRARY = require('./$.library') , global = require('./$.global') , ctx = require('./$.ctx') , classof = require('./$.classof') , $export = require('./$.export') , isObject = require('./$.is-object') , anObject = require('./$.an-object') , aFunction = require('./$.a-function') , strictNew = require('./$.strict-new') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , same = require('./$.same-value') , SPECIES = require('./$.wks')('species') , speciesConstructor = require('./$.species-constructor') , asap = require('./$.microtask') , PROMISE = 'Promise' , process = global.process , isNode = classof(process) == 'process' , P = global[PROMISE] , Wrapper; var testResolve = function(sub){ var test = new P(function(){}); if(sub)test.constructor = Object; return P.resolve(test) === test; }; var USE_NATIVE = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = P && P.resolve && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && require('./$.descriptors')){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers var sameConstructor = function(a, b){ // library wrapper special case if(LIBRARY && a === P && b === Wrapper)return true; return same(a, b); }; var getConstructor = function(C){ var S = anObject(C)[SPECIES]; return S != undefined ? S : C; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var PromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve), this.reject = aFunction(reject) }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(record, isReject){ if(record.n)return; record.n = true; var chain = record.c; asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , result, then; try { if(handler){ if(!ok)record.h = true; result = handler === true ? value : handler(value); if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; record.n = false; if(isReject)setTimeout(function(){ var promise = record.p , handler, console; if(isUnhandled(promise)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }, 1); }); }; var isUnhandled = function(promise){ var record = promise._d , chain = record.a || record.c , i = 0 , reaction; if(record.h)return false; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var $reject = function(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); notify(record, true); }; var $resolve = function(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(record.p === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ asap(function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record, false); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ aFunction(executor); var record = this._d = { p: strictNew(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false, // <- handled rejection n: false // <- notify }; try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; require('./$.redefine-all')(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = new PromiseCapability(speciesConstructor(this, P)) , promise = reaction.promise , record = this._d; reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; record.c.push(reaction); if(record.a)record.a.push(reaction); if(record.s)notify(record, false); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); require('./$.set-to-string-tag')(P, PROMISE); require('./$.set-species')(PROMISE); Wrapper = require('./$.core')[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = new PromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof P && sameConstructor(x.constructor, this))return x; var capability = new PromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , resolve = capability.resolve , reject = capability.reject , values = []; var abrupt = perform(function(){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ var alreadyCalled = false; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } });
src/NavItem.js
thealjey/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import SafeAnchor from './SafeAnchor'; const NavItem = React.createClass({ mixins: [BootstrapMixin], propTypes: { linkId: React.PropTypes.string, onSelect: React.PropTypes.func, active: React.PropTypes.bool, disabled: React.PropTypes.bool, href: React.PropTypes.string, role: React.PropTypes.string, title: React.PropTypes.node, eventKey: React.PropTypes.any, target: React.PropTypes.string, 'aria-controls': React.PropTypes.string }, getDefaultProps() { return { active: false, disabled: false }; }, render() { let { role, linkId, disabled, active, href, title, target, children, tabIndex, //eslint-disable-line 'aria-controls': ariaControls, ...props } = this.props; let classes = { active, disabled }; let linkProps = { role, href, title, target, tabIndex, id: linkId, onClick: this.handleClick }; if (!role && href === '#') { linkProps.role = 'button'; } return ( <li {...props} role="presentation" className={classNames(props.className, classes)}> <SafeAnchor {...linkProps} aria-selected={active} aria-controls={ariaControls}> { children } </SafeAnchor> </li> ); }, handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); export default NavItem;
ajax/libs/handsontable/0.10.5/jquery.handsontable.full.js
TerryMooreII/cdnjs
/** * Handsontable 0.10.5 * Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://handsontable.com/ * * Date: Mon Mar 31 2014 14:19:47 GMT+0200 (CEST) */ /*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */ var Handsontable = { //class namespace extension: {}, //extenstion namespace plugins: {}, //plugin namespace helper: {} //helper namespace }; (function ($, window, Handsontable) { "use strict"; //http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } /** * Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications */ if (!Array.prototype.filter) { Array.prototype.filter = function (fun, thisp) { "use strict"; if (typeof this === "undefined" || this === null) { throw new TypeError(); } if (typeof fun !== "function") { throw new TypeError(); } thisp = thisp || this; if (isNodeList(thisp)) { thisp = convertNodeListToArray(thisp); } var len = thisp.length, res = [], i, val; for (i = 0; i < len; i += 1) { if (thisp.hasOwnProperty(i)) { val = thisp[i]; // in case fun mutates this if (fun.call(thisp, val, i, thisp)) { res.push(val); } } } return res; function isNodeList(object) { return /NodeList/i.test(object.item); } function convertNodeListToArray(nodeList) { var array = []; for (var i = 0, len = nodeList.length; i < len; i++){ array[i] = nodeList[i] } return array; } }; } /* * Copyright 2012 The Polymer Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ if (typeof WeakMap === 'undefined') { (function() { var defineProperty = Object.defineProperty; try { var properDefineProperty = true; defineProperty(function(){}, 'foo', {}); } catch (e) { properDefineProperty = false; } /* IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does. M$ deserves a high five for this one :) */ var counter = +(new Date) % 1e9; var WeakMap = function() { this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__'); if(!properDefineProperty){ this._wmCache = []; } }; if(properDefineProperty){ WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {value: [key, value], writable: true}); }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, 'delete': function(key) { this.set(key, undefined); } }; } else { WeakMap.prototype = { set: function(key, value) { if(typeof key == 'undefined' || typeof value == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ this._wmCache[i].value = value; return; } } this._wmCache.push({key: key, value: value}); }, get: function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ return this._wmCache[i].value; } } return; }, 'delete': function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ Array.prototype.slice.call(this._wmCache, i, 1); } } } }; } window.WeakMap = WeakMap; })(); } Handsontable.activeGuid = null; /** * Handsontable constructor * @param rootElement The jQuery element in which Handsontable DOM will be inserted * @param userSettings * @constructor */ Handsontable.Core = function (rootElement, userSettings) { var priv , datamap , grid , selection , editorManager , autofill , instance = this , GridSettings = function () {}; Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings)); this.rootElement = rootElement; var $document = $(document.documentElement); var $body = $(document.body); this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events if (!this.rootElement[0].id) { this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id } priv = { cellSettings: [], columnSettings: [], columnsSettingConflicts: ['data', 'width'], settings: new GridSettings(), // current settings instance settingsFromDOM: {}, selStart: new Handsontable.SelectionPoint(), selEnd: new Handsontable.SelectionPoint(), isPopulated: null, scrollable: null, extensions: {}, firstRun: true }; grid = { /** * Inserts or removes rows and columns * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col" * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. */ alter: function (action, index, amount, source, keepEmptyRows) { var delta; amount = amount || 1; switch (action) { case "insert_row": delta = datamap.createRow(index, amount); if (delta) { if (priv.selStart.exists() && priv.selStart.row() >= index) { priv.selStart.row(priv.selStart.row() + delta); selection.transformEnd(delta, 0); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "insert_col": delta = datamap.createCol(index, amount); if (delta) { if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ var spliceArray = [index, 0]; spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array } if (priv.selStart.exists() && priv.selStart.col() >= index) { priv.selStart.col(priv.selStart.col() + delta); selection.transformEnd(0, delta); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "remove_row": datamap.removeRow(index, amount); priv.cellSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; case "remove_col": datamap.removeCol(index, amount); for(var row = 0, len = datamap.getAll().length; row < len; row++){ if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings priv.cellSettings[row].splice(index, amount); } } if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ if(typeof index == 'undefined'){ index = -1; } instance.getSettings().colHeaders.splice(index, amount); } priv.columnSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; default: throw new Error('There is no such action "' + action + '"'); break; } if (!keepEmptyRows) { grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh } }, /** * Makes sure there are empty rows at the bottom of the table */ adjustRowsAndCols: function () { var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols; //should I add empty rows to data source to meet minRows? rlen = instance.countRows(); if (rlen < priv.settings.minRows) { for (r = 0; r < priv.settings.minRows - rlen; r++) { datamap.createRow(instance.countRows(), 1, true); } } //should I add empty rows to meet minSpareRows? if (emptyRows < priv.settings.minSpareRows) { for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) { datamap.createRow(instance.countRows(), 1, true); } } //count currently empty cols emptyCols = instance.countEmptyCols(true); //should I add empty cols to meet minCols? if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) { for (; instance.countCols() < priv.settings.minCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } //should I add empty cols to meet minSpareCols? if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) { for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) { datamap.createCol(instance.countCols(), 1, true); } } if (priv.settings.enterBeginsEditing) { for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) { datamap.removeRow(); } } if (priv.settings.enterBeginsEditing && !priv.settings.columns) { for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) { datamap.removeCol(); } } var rowCount = instance.countRows(); var colCount = instance.countCols(); if (rowCount === 0 || colCount === 0) { selection.deselect(); } if (priv.selStart.exists()) { var selectionChanged; var fromRow = priv.selStart.row(); var fromCol = priv.selStart.col(); var toRow = priv.selEnd.row(); var toCol = priv.selEnd.col(); //if selection is outside, move selection to last row if (fromRow > rowCount - 1) { fromRow = rowCount - 1; selectionChanged = true; if (toRow > fromRow) { toRow = fromRow; } } else if (toRow > rowCount - 1) { toRow = rowCount - 1; selectionChanged = true; if (fromRow > toRow) { fromRow = toRow; } } //if selection is outside, move selection to last row if (fromCol > colCount - 1) { fromCol = colCount - 1; selectionChanged = true; if (toCol > fromCol) { toCol = fromCol; } } else if (toCol > colCount - 1) { toCol = colCount - 1; selectionChanged = true; if (fromCol > toCol) { fromCol = toCol; } } if (selectionChanged) { instance.selectCell(fromRow, fromCol, toRow, toCol); } } }, /** * Populate cells at position with 2d array * @param {Object} start Start selection position * @param {Array} input 2d array * @param {Object} [end] End selection position (only for drag-down mode) * @param {String} [source="populateFromArray"] * @param {String} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ populateFromArray: function (start, input, end, source, method) { var r, rlen, c, clen, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } var repeatCol , repeatRow , cmax , rmax; // insert data with specified pasteMode method switch (method) { case 'shift_down' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; input = Handsontable.helper.translateRowsToColumns(input); for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) { if (c < clen) { for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) { input[c].push(input[c][r % rlen]); } input[c].unshift(start.col + c, start.row, 0); instance.spliceCol.apply(instance, input[c]); } else { input[c % clen][0] = start.col + c; instance.spliceCol.apply(instance, input[c % clen]); } } break; case 'shift_right' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) { if (r < rlen) { for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) { input[r].push(input[r][c % clen]); } input[r].unshift(start.row + r, start.col, 0); instance.spliceRow.apply(instance, input[r]); } else { input[r % rlen][0] = start.row + r; instance.spliceRow.apply(instance, input[r % rlen]); } } break; case 'overwrite' : default: // overwrite and other not specified options current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) { break; } if (!instance.getCellMeta(current.row, current.col).readOnly) { setData.push([current.row, current.col, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } instance.setDataAtCell(setData, null, null, source || 'populateFromArray'); break; } }, /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ getCornerCoords: function (coordsArr) { function mapProp(func, array, prop) { function getProp(el) { return el[prop]; } if (Array.prototype.map) { return func.apply(Math, array.map(getProp)); } return func.apply(Math, $.map(array, getProp)); } return { TL: { row: mapProp(Math.min, coordsArr, "row"), col: mapProp(Math.min, coordsArr, "col") }, BR: { row: mapProp(Math.max, coordsArr, "row"), col: mapProp(Math.max, coordsArr, "col") } }; }, /** * Returns array of td objects given start and end coordinates */ getCellsAtCoords: function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(instance.view.getCellAtCoords({ row: r, col: c })); } } return output; } }; this.selection = selection = { //this public assignment is only temporary inProgress: false, /** * Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired */ begin: function () { instance.selection.inProgress = true; }, /** * Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp */ finish: function () { var sel = instance.getSelected(); instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]); instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3])); instance.selection.inProgress = false; }, isInProgress: function () { return instance.selection.inProgress; }, /** * Starts selection range on given td object * @param {Object} coords */ setRangeStart: function (coords) { priv.selStart.coords(coords); selection.setRangeEnd(coords); }, /** * Ends selection range on given td object * @param {Object} coords * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end */ setRangeEnd: function (coords, scrollToCell) { instance.selection.begin(); priv.selEnd.coords(coords); if (!priv.settings.multiSelect) { priv.selStart.coords(coords); } //set up current selection instance.view.wt.selections.current.clear(); instance.view.wt.selections.current.add(priv.selStart.arr()); //set up area selection instance.view.wt.selections.area.clear(); if (selection.isMultiple()) { instance.view.wt.selections.area.add(priv.selStart.arr()); instance.view.wt.selections.area.add(priv.selEnd.arr()); } //set up highlight if (priv.settings.currentRowClassName || priv.settings.currentColClassName) { instance.view.wt.selections.highlight.clear(); instance.view.wt.selections.highlight.add(priv.selStart.arr()); instance.view.wt.selections.highlight.add(priv.selEnd.arr()); } //trigger handlers instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()); instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col())); if (scrollToCell !== false) { instance.view.scrollViewport(coords); } selection.refreshBorders(); }, /** * Destroys editor, redraws borders around cells, prepares editor * @param {Boolean} revertOriginal * @param {Boolean} keepEditor */ refreshBorders: function (revertOriginal, keepEditor) { if (!keepEditor) { editorManager.destroyEditor(revertOriginal); } instance.view.render(); if (selection.isSelected() && !keepEditor) { editorManager.prepareEditor(); } }, /** * Returns information if we have a multiselection * @return {Boolean} */ isMultiple: function () { return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row()); }, /** * Selects cell relative to current cell (if possible) */ transformStart: function (rowDelta, colDelta, force) { if (priv.selStart.row() + rowDelta > instance.countRows() - 1) { if (force && priv.settings.minSpareRows > 0) { instance.alter("insert_row", instance.countRows()); } else if (priv.settings.autoWrapCol) { rowDelta = 1 - instance.countRows(); colDelta = priv.selStart.col() + colDelta == instance.countCols() - 1 ? 1 - instance.countCols() : 1; } } else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) { rowDelta = instance.countRows() - 1; colDelta = priv.selStart.col() + colDelta == 0 ? instance.countCols() - 1 : -1; } if (priv.selStart.col() + colDelta > instance.countCols() - 1) { if (force && priv.settings.minSpareCols > 0) { instance.alter("insert_col", instance.countCols()); } else if (priv.settings.autoWrapRow) { rowDelta = priv.selStart.row() + rowDelta == instance.countRows() - 1 ? 1 - instance.countRows() : 1; colDelta = 1 - instance.countCols(); } } else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) { rowDelta = priv.selStart.row() + rowDelta == 0 ? instance.countRows() - 1 : -1; colDelta = instance.countCols() - 1; } var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selStart.row() + rowDelta, col: priv.selStart.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeStart(coords); }, /** * Sets selection end cell relative to current selection end cell (if possible) */ transformEnd: function (rowDelta, colDelta) { if (priv.selEnd.exists()) { var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selEnd.row() + rowDelta, col: priv.selEnd.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeEnd(coords); } }, /** * Returns true if currently there is a selection on screen, false otherwise * @return {Boolean} */ isSelected: function () { return priv.selEnd.exists(); }, /** * Returns true if coords is within current selection coords * @return {Boolean} */ inInSelection: function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }, /** * Deselects all selected cells */ deselect: function () { if (!selection.isSelected()) { return; } instance.selection.inProgress = false; //needed by HT inception priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one instance.view.wt.selections.current.clear(); instance.view.wt.selections.area.clear(); editorManager.destroyEditor(); selection.refreshBorders(); instance.PluginHooks.run('afterDeselect'); }, /** * Select all cells */ selectAll: function () { if (!priv.settings.multiSelect) { return; } selection.setRangeStart({ row: 0, col: 0 }); selection.setRangeEnd({ row: instance.countRows() - 1, col: instance.countCols() - 1 }, false); }, /** * Deletes data from selected cells */ empty: function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (!instance.getCellMeta(r, c).readOnly) { changes.push([r, c, '']); } } } instance.setDataAtCell(changes); } }; this.autofill = autofill = { //this public assignment is only temporary handle: null, /** * Create fill handle and fill border objects */ init: function () { if (!autofill.handle) { autofill.handle = {}; } else { autofill.handle.disabled = false; } }, /** * Hide fill handle and fill border permanently */ disable: function () { autofill.handle.disabled = true; }, /** * Selects cells down to the last row in the left column, then fills down to that cell */ selectAdjacent: function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } data = datamap.getAll(); rows : for (r = select[2] + 1; r < instance.countRows(); r++) { for (c = select[1]; c <= select[3]; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) { maxR = r; } } if (maxR) { instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([select[0], select[1]]); instance.view.wt.selections.fill.add([maxR, select[3]]); autofill.apply(); } }, /** * Apply fill values to the area in fill border, omitting the selection border */ apply: function () { var drag, select, start, end, _data; autofill.handle.isDragged = 0; drag = instance.view.wt.selections.fill.getCorners(); if (!drag) { return; } instance.view.wt.selections.fill.clear(); if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } if (drag[0] === select[0] && drag[1] < select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: drag[2], col: select[1] - 1 }; } else if (drag[0] === select[0] && drag[3] > select[3]) { start = { row: drag[0], col: select[3] + 1 }; end = { row: drag[2], col: drag[3] }; } else if (drag[0] < select[0] && drag[1] === select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: select[0] - 1, col: drag[3] }; } else if (drag[2] > select[2] && drag[1] === select[1]) { start = { row: select[2] + 1, col: drag[1] }; end = { row: drag[2], col: drag[3] }; } if (start) { _data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords())); instance.PluginHooks.run('beforeAutofill', start, end, _data); grid.populateFromArray(start, _data, end, 'autofill'); selection.setRangeStart({row: drag[0], col: drag[1]}); selection.setRangeEnd({row: drag[2], col: drag[3]}); } /*else { //reset to avoid some range bug selection.refreshBorders(); }*/ }, /** * Show fill border */ showBorder: function (coords) { coords.row = coords[0]; coords.col = coords[1]; var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = [coords.row, corners.BR.col]; } else if (priv.settings.fillHandle !== 'vertical') { coords = [corners.BR.row, coords.col]; } else { return; //wrong direction } instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]); instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]); instance.view.wt.selections.fill.add(coords); instance.view.render(); } }; this.init = function () { instance.PluginHooks.run('beforeInit'); this.view = new Handsontable.TableView(this); editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap); this.updateSettings(priv.settings, true); this.parseSettingsFromDOM(); this.forceFullRender = true; //used when data was changed this.view.render(); if (typeof priv.firstRun === 'object') { instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]); priv.firstRun = false; } instance.PluginHooks.run('afterInit'); }; function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file var resolved = false; return { validatorsInQueue: 0, addValidatorToQueue: function () { this.validatorsInQueue++; resolved = false; }, removeValidatorFormQueue: function () { this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1; this.checkIfQueueIsEmpty(); }, onQueueEmpty: function () { }, checkIfQueueIsEmpty: function () { if (this.validatorsInQueue == 0 && resolved == false) { resolved = true; this.onQueueEmpty(); } } }; } function validateChanges(changes, source, callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = resolve; for (var i = changes.length - 1; i >= 0; i--) { if (changes[i] === null) { changes.splice(i, 1); } else { var row = changes[i][0]; var col = datamap.propToCol(changes[i][1]); var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user) var cellProperties = instance.getCellMeta(row, logicalCol); if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') { if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) { changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string } } if (instance.getCellValidator(cellProperties)) { waitingForValidator.addValidatorToQueue(); instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) { return function (result) { if (typeof result !== 'boolean') { throw new Error("Validation error: result is not boolean"); } if (result === false && cellProperties.allowInvalid === false) { changes.splice(i, 1); // cancel the change cellProperties.valid = true; // we cancelled the change, so cell value is still valid --i; } waitingForValidator.removeValidatorFormQueue(); } })(i, cellProperties) , source); } } } waitingForValidator.checkIfQueueIsEmpty(); function resolve() { var beforeChangeResult; if (changes.length) { beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source); if (typeof beforeChangeResult === 'function') { $.when(result).then(function () { callback(); //called when async validators and async beforeChange are resolved }); } else if (beforeChangeResult === false) { changes.splice(0, changes.length); //invalidate all changes (remove everything from array) } } if (typeof beforeChangeResult !== 'function') { callback(); //called when async validators are resolved and beforeChange was not async } } } /** * Internal function to apply changes. Called after validateChanges * @param {Array} changes Array in form of [row, prop, oldValue, newValue] * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ function applyChanges(changes, source) { var i = changes.length - 1; if (i < 0) { return; } for (; 0 <= i; i--) { if (changes[i] === null) { changes.splice(i, 1); continue; } if (priv.settings.minSpareRows) { while (changes[i][0] > instance.countRows() - 1) { datamap.createRow(); } } if (instance.dataType === 'array' && priv.settings.minSpareCols) { while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) { datamap.createCol(); } } datamap.set(changes[i][0], changes[i][1], changes[i][3]); } instance.forceFullRender = true; //used when data was changed grid.adjustRowsAndCols(); selection.refreshBorders(null, true); instance.PluginHooks.run('afterChange', changes, source || 'edit'); } this.validateCell = function (value, cellProperties, callback, source) { var validator = instance.getCellValidator(cellProperties); if (Object.prototype.toString.call(validator) === '[object RegExp]') { validator = (function (validator) { return function (value, callback) { callback(validator.test(value)); } })(validator); } if (typeof validator == 'function') { value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source); // To provide consistent behaviour, validation should be always asynchronous setTimeout(function () { validator.call(cellProperties, value, function (valid) { cellProperties.valid = valid; valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source); callback(valid); }); }); } else { //resolve callback even if validator function was not found cellProperties.valid = true; callback(true); } }; function setDataInputToArray(row, prop_or_col, value) { if (typeof row === "object") { //is it an array of changes return row; } else if ($.isPlainObject(value)) { //backwards compatibility return value; } else { return [ [row, prop_or_col, value] ]; } } /** * Set data at given cell * @public * @param {Number|Array} row or array of changes in format [[row, col, value], ...] * @param {Number|String} col or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtCell = function (row, col, value, source) { var input = setDataInputToArray(row, col, value) , i , ilen , changes = [] , prop; for (i = 0, ilen = input.length; i < ilen; i++) { if (typeof input[i] !== 'object') { throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter'); } if (typeof input[i][1] !== 'number') { throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`'); } prop = datamap.colToProp(input[i][1]); changes.push([ input[i][0], prop, datamap.get(input[i][0], prop), input[i][2] ]); } if (!source && typeof row === "object") { source = col; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Set data at given row property * @public * @param {Number|Array} row or array of changes in format [[row, prop, value], ...] * @param {String} prop or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtRowProp = function (row, prop, value, source) { var input = setDataInputToArray(row, prop, value) , i , ilen , changes = []; for (i = 0, ilen = input.length; i < ilen; i++) { changes.push([ input[i][0], input[i][1], datamap.get(input[i][0], input[i][1]), input[i][2] ]); } if (!source && typeof row === "object") { source = prop; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Listen to document body keyboard input */ this.listen = function () { Handsontable.activeGuid = instance.guid; if (document.activeElement && document.activeElement !== document.body) { document.activeElement.blur(); } else if (!document.activeElement) { //IE document.body.focus(); } }; /** * Stop listening to document body keyboard input */ this.unlisten = function () { Handsontable.activeGuid = null; }; /** * Returns true if current Handsontable instance is listening on document body keyboard input */ this.isListening = function () { return Handsontable.activeGuid === instance.guid; }; /** * Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { selection.refreshBorders(revertOriginal); }; /** * Populate cells at position with 2d array * @param {Number} row Start row * @param {Number} col Start column * @param {Array} input 2d array * @param {Number=} endRow End row (use when you want to cut input when certain row is reached) * @param {Number=} endCol End column (use when you want to cut input when certain column is reached) * @param {String=} [source="populateFromArray"] * @param {String=} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ this.populateFromArray = function (row, col, input, endRow, endCol, source, method) { if (!(typeof input === 'object' && typeof input[0] === 'object')) { throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly } return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method); }; /** * Adds/removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceCol = function (col, index, amount/*, elements... */) { return datamap.spliceCol.apply(datamap, arguments); }; /** * Adds/removes data from the row * @param {Number} row Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceRow = function (row, index, amount/*, elements... */) { return datamap.spliceRow.apply(datamap, arguments); }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ this.getCornerCoords = function (coordsArr) { return grid.getCornerCoords(coordsArr); }; /** * Returns current selection. Returns undefined if there is no selection. * @public * @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`] */ this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl if (selection.isSelected()) { return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()]; } }; /** * Parse settings from DOM and CSS * @public */ this.parseSettingsFromDOM = function () { var overflow = this.rootElement.css('overflow'); if (overflow === 'scroll' || overflow === 'auto') { this.rootElement[0].style.overflow = 'visible'; priv.settingsFromDOM.overflow = overflow; } else if (priv.settings.width === void 0 || priv.settings.height === void 0) { priv.settingsFromDOM.overflow = 'auto'; } if (priv.settings.width === void 0) { priv.settingsFromDOM.width = this.rootElement.width(); } else { priv.settingsFromDOM.width = void 0; } priv.settingsFromDOM.height = void 0; if (priv.settings.height === void 0) { if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') { //this needs to read only CSS/inline style and not actual height //so we need to call getComputedStyle on cloned container var clone = this.rootElement[0].cloneNode(false); var parent = this.rootElement[0].parentNode; if (parent) { clone.removeAttribute('id'); parent.appendChild(clone); var computedClientHeight = parseInt(clone.clientHeight, 10); var computedPaddingTop = parseInt(window.getComputedStyle(clone, null).getPropertyValue('paddingTop'), 10) || 0; var computedPaddingBottom = parseInt(window.getComputedStyle(clone, null).getPropertyValue('paddingBottom'), 10) || 0; var computedHeight = computedClientHeight - computedPaddingTop - computedPaddingBottom; if(isNaN(computedHeight) && clone.currentStyle){ computedHeight = parseInt(clone.currentStyle.height, 10) } if (computedHeight > 0) { priv.settingsFromDOM.height = computedHeight; } parent.removeChild(clone); } } } }; /** * Render visible data * @public */ this.render = function () { if (instance.view) { instance.forceFullRender = true; //used when data was changed instance.parseSettingsFromDOM(); selection.refreshBorders(null, true); } }; /** * Load data from array * @public * @param {Array} data */ this.loadData = function (data) { if (typeof data === 'object' && data !== null) { if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it //when data is not an array, attempt to make a single-row array of it data = [data]; } } else if(data === null) { data = []; var row; for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) { row = []; for (var c = 0, clen = priv.settings.startCols; c < clen; c++) { row.push(null); } data.push(row); } } else { throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)"); } priv.isPopulated = false; GridSettings.prototype.data = data; if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) { instance.dataType = 'array'; } else if (typeof priv.settings.dataSchema === 'function') { instance.dataType = 'function'; } else { instance.dataType = 'object'; } datamap = new Handsontable.DataMap(instance, priv, GridSettings); clearCellSettingCache(); grid.adjustRowsAndCols(); instance.PluginHooks.run('afterLoadData'); if (priv.firstRun) { priv.firstRun = [null, 'loadData']; } else { instance.PluginHooks.run('afterChange', null, 'loadData'); instance.render(); } priv.isPopulated = true; function clearCellSettingCache() { priv.cellSettings.length = 0; } }; /** * Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data * @public * @param {Number} r (Optional) From row * @param {Number} c (Optional) From col * @param {Number} r2 (Optional) To row * @param {Number} c2 (Optional) To col * @return {Array|Object} */ this.getData = function (r, c, r2, c2) { if (typeof r === 'undefined') { return datamap.getAll(); } else { return datamap.getRange({row: r, col: c}, {row: r2, col: c2}, datamap.DESTINATION_RENDERER); } }; this.getCopyableData = function (startRow, startCol, endRow, endCol) { return datamap.getCopyableText({row: startRow, col: startCol}, {row: endRow, col: endCol}); } /** * Update settings * @public */ this.updateSettings = function (settings, init) { var i, clen; if (typeof settings.rows !== "undefined") { throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?"); } if (typeof settings.cols !== "undefined") { throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?"); } for (i in settings) { if (i === 'data') { continue; //loadData will be triggered later } else { if (instance.PluginHooks.hooks[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) { if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) { instance.PluginHooks.add(i, settings[i]); } } else { // Update settings if (!init && settings.hasOwnProperty(i)) { GridSettings.prototype[i] = settings[i]; } //launch extensions if (Handsontable.extension[i]) { priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]); } } } } // Load data or create data map if (settings.data === void 0 && priv.settings.data === void 0) { instance.loadData(null); //data source created just now } else if (settings.data !== void 0) { instance.loadData(settings.data); //data source given as option } else if (settings.columns !== void 0) { datamap.createMap(); } // Init columns constructors configuration clen = instance.countCols(); //Clear cellSettings cache priv.cellSettings.length = 0; if (clen > 0) { var proto, column; for (i = 0; i < clen; i++) { priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); // shortcut for prototype proto = priv.columnSettings[i].prototype; // Use settings provided by user if (GridSettings.prototype.columns) { column = GridSettings.prototype.columns[i]; Handsontable.helper.extend(proto, column); Handsontable.helper.extend(proto, expandType(column)); } } } if (typeof settings.fillHandle !== "undefined") { if (autofill.handle && settings.fillHandle === false) { autofill.disable(); } else if (!autofill.handle && settings.fillHandle !== false) { autofill.init(); } } if (typeof settings.className !== "undefined") { if (GridSettings.prototype.className) { instance.rootElement.removeClass(GridSettings.prototype.className); } if (settings.className) { instance.rootElement.addClass(settings.className); } } if (!init) { instance.PluginHooks.run('afterUpdateSettings'); } grid.adjustRowsAndCols(); if (instance.view && !priv.firstRun) { instance.forceFullRender = true; //used when data was changed selection.refreshBorders(null, true); } }; this.getValue = function () { var sel = instance.getSelected(); if (GridSettings.prototype.getValue) { if (typeof GridSettings.prototype.getValue === 'function') { return GridSettings.prototype.getValue.call(instance); } else if (sel) { return instance.getData()[sel[0]][GridSettings.prototype.getValue]; } } else if (sel) { return instance.getDataAtCell(sel[0], sel[1]); } }; function expandType(obj) { if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type var type, expandedType = {}; if (typeof obj.type === 'object') { type = obj.type; } else if (typeof obj.type === 'string') { type = Handsontable.cellTypes[obj.type]; if (type === void 0) { throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } } for (var i in type) { if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) { expandedType[i] = type[i]; } } return expandedType; } /** * Returns current settings object * @return {Object} */ this.getSettings = function () { return priv.settings; }; /** * Returns current settingsFromDOM object * @return {Object} */ this.getSettingsFromDOM = function () { return priv.settingsFromDOM; }; /** * Clears grid * @public */ this.clear = function () { selection.selectAll(); selection.empty(); }; /** * Inserts or removes rows and columns * @param {String} action See grid.alter for possible values * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. * @public */ this.alter = function (action, index, amount, source, keepEmptyRows) { grid.alter(action, index, amount, source, keepEmptyRows); }; /** * Returns <td> element corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Element} */ this.getCell = function (row, col) { return instance.view.getCellAtCoords({row: row, col: col}); }; /** * Returns property name associated with column number * @param {Number} col * @public * @return {String} */ this.colToProp = function (col) { return datamap.colToProp(col); }; /** * Returns column number associated with property name * @param {String} prop * @public * @return {Number} */ this.propToCol = function (prop) { return datamap.propToCol(prop); }; /** * Return value at `row`, `col` * @param {Number} row * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCell = function (row, col) { return datamap.get(row, datamap.colToProp(col)); }; /** * Return value at `row`, `prop` * @param {Number} row * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtRowProp = function (row, prop) { return datamap.get(row, prop); }; /** * Return value at `col` * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCol = function (col) { return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `prop` * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtProp = function (prop) { return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `row` * @param {Number} row * @public * @return value (mixed data type) */ this.getDataAtRow = function (row) { return priv.settings.data[row]; }; /** * Returns cell meta data object corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Object} */ this.getCellMeta = function (row, col) { var prop = datamap.colToProp(col) , cellProperties; row = translateRowIndex(row); col = translateColIndex(col); if ("undefined" === typeof priv.columnSettings[col]) { priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); } if (!priv.cellSettings[row]) { priv.cellSettings[row] = []; } if (!priv.cellSettings[row][col]) { priv.cellSettings[row][col] = new priv.columnSettings[col](); } cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache cellProperties.row = row; cellProperties.col = col; cellProperties.prop = prop; cellProperties.instance = instance; instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties); Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta if (cellProperties.cells) { var settings = cellProperties.cells.call(cellProperties, row, col, prop); if (settings) { Handsontable.helper.extend(cellProperties, settings); Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells } } instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties); return cellProperties; /** * If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied) * we need to translate logical (stored) row index to physical (displayed) index. * @param row - original row index * @returns {int} translated row index */ function translateRowIndex(row){ var getVars = {row: row}; instance.PluginHooks.execute('beforeGet', getVars); return getVars.row; } /** * If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin) * we need to translate logical (stored) column index to physical (displayed) index. * @param col - original column index * @returns {int} - translated column index */ function translateColIndex(col){ return Handsontable.PluginHooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp } }; var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer'); this.getCellRenderer = function (row, col) { var renderer = rendererLookup.call(this, row, col); return Handsontable.renderers.getRenderer(renderer); }; this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor'); this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator'); /** * Validates all cells using their validator functions and calls callback when finished. Does not render the view * @param callback */ this.validateCells = function (callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = callback; var i = instance.countRows() - 1; while (i >= 0) { var j = instance.countCols() - 1; while (j >= 0) { waitingForValidator.addValidatorToQueue(); instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () { waitingForValidator.removeValidatorFormQueue(); }, 'validateCells'); j--; } i--; } waitingForValidator.checkIfQueueIsEmpty(); }; /** * Return array of row headers (if they are enabled). If param `row` given, return header at given row as string * @param {Number} row (Optional) * @return {Array|String} */ this.getRowHeader = function (row) { if (row === void 0) { var out = []; for (var i = 0, ilen = instance.countRows(); i < ilen; i++) { out.push(instance.getRowHeader(i)); } return out; } else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) { return priv.settings.rowHeaders[row]; } else if (typeof priv.settings.rowHeaders === 'function') { return priv.settings.rowHeaders(row); } else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') { return row + 1; } else { return priv.settings.rowHeaders; } }; /** * Returns information of this table is configured to display row headers * @returns {boolean} */ this.hasRowHeaders = function () { return !!priv.settings.rowHeaders; }; /** * Returns information of this table is configured to display column headers * @returns {boolean} */ this.hasColHeaders = function () { if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null return !!priv.settings.colHeaders; } for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { if (instance.getColHeader(i)) { return true; } } return false; }; /** * Return array of column headers (if they are enabled). If param `col` given, return header at given column as string * @param {Number} col (Optional) * @return {Array|String} */ this.getColHeader = function (col) { if (col === void 0) { var out = []; for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { out.push(instance.getColHeader(i)); } return out; } else { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) { return priv.settings.columns[col].title; } else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) { return priv.settings.colHeaders[col]; } else if (typeof priv.settings.colHeaders === 'function') { return priv.settings.colHeaders(col); } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') { return Handsontable.helper.spreadsheetColumnLabel(col); } else { return priv.settings.colHeaders; } } }; /** * Return column width from settings (no guessing). Private use intended * @param {Number} col * @return {Number} */ this._getColWidthFromSettings = function (col) { var cellProperties = instance.getCellMeta(0, col); var width = cellProperties.width; if (width === void 0 || width === priv.settings.width) { width = cellProperties.colWidths; } if (width !== void 0 && width !== null) { switch (typeof width) { case 'object': //array width = width[col]; break; case 'function': width = width(col); break; } if (typeof width === 'string') { width = parseInt(width, 10); } } return width; }; /** * Return column width * @param {Number} col * @return {Number} */ this.getColWidth = function (col) { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); var response = { width: instance._getColWidthFromSettings(col) }; if (!response.width) { response.width = 50; } instance.PluginHooks.run('afterGetColWidth', col, response); return response.width; }; /** * Return total number of rows in grid * @return {Number} */ this.countRows = function () { return priv.settings.data.length; }; /** * Return total number of columns in grid * @return {Number} */ this.countCols = function () { if (instance.dataType === 'object' || instance.dataType === 'function') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else { return datamap.colToPropCache.length; } } else if (instance.dataType === 'array') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) { return priv.settings.data[0].length; } else { return 0; } } }; /** * Return index of first visible row * @return {Number} */ this.rowOffset = function () { return instance.view.wt.getSetting('offsetRow'); }; /** * Return index of first visible column * @return {Number} */ this.colOffset = function () { return instance.view.wt.getSetting('offsetColumn'); }; /** * Return number of visible rows. Returns -1 if table is not visible * @return {Number} */ this.countVisibleRows = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1; }; /** * Return number of visible columns. Returns -1 if table is not visible * @return {Number} */ this.countVisibleCols = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1; }; /** * Return number of empty rows * @return {Boolean} ending If true, will only count empty rows at the end of the data source */ this.countEmptyRows = function (ending) { var i = instance.countRows() - 1 , empty = 0; while (i >= 0) { datamap.get(i, 0); if (instance.isEmptyRow(datamap.getVars.row)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return number of empty columns * @return {Boolean} ending If true, will only count empty columns at the end of the data source row */ this.countEmptyCols = function (ending) { if (instance.countRows() < 1) { return 0; } var i = instance.countCols() - 1 , empty = 0; while (i >= 0) { if (instance.isEmptyCol(i)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return true if the row at the given index is empty, false otherwise * @param {Number} r Row index * @return {Boolean} */ this.isEmptyRow = function (r) { return priv.settings.isEmptyRow.call(instance, r); }; /** * Return true if the column at the given index is empty, false otherwise * @param {Number} c Column index * @return {Boolean} */ this.isEmptyCol = function (c) { return priv.settings.isEmptyCol.call(instance, c); }; /** * Selects cell on grid. Optionally selects range to another cell * @param {Number} row * @param {Number} col * @param {Number} [endRow] * @param {Number} [endCol] * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection * @public * @return {Boolean} */ this.selectCell = function (row, col, endRow, endCol, scrollToCell) { if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) { return false; } if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) { return false; } if (typeof endRow !== "undefined") { if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) { return false; } if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) { return false; } } priv.selStart.coords({row: row, col: col}); if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) { document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell) } instance.listen(); if (typeof endRow === "undefined") { selection.setRangeEnd({row: row, col: col}, scrollToCell); } else { selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell); } instance.selection.finish(); return true; }; this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) { arguments[1] = datamap.propToCol(arguments[1]); if (typeof arguments[3] !== "undefined") { arguments[3] = datamap.propToCol(arguments[3]); } return instance.selectCell.apply(instance, arguments); }; /** * Deselects current sell selection on grid * @public */ this.deselectCell = function () { selection.deselect(); }; /** * Remove grid from DOM * @public */ this.destroy = function () { instance.clearTimeouts(); if (instance.view) { //in case HT is destroyed before initialization has finished instance.view.wt.destroy(); } instance.rootElement.empty(); instance.rootElement.removeData('handsontable'); instance.rootElement.off('.handsontable'); $(window).off('.' + instance.guid); $document.off('.' + instance.guid); $body.off('.' + instance.guid); instance.PluginHooks.run('afterDestroy'); }; /** * Returns active editor object * @returns {Object} */ this.getActiveEditor = function(){ return editorManager.getActiveEditor(); }; /** * Return Handsontable instance * @public * @return {Object} */ this.getInstance = function () { return instance.rootElement.data("handsontable"); }; (function () { // Create new instance of plugin hooks instance.PluginHooks = new Handsontable.PluginHookClass(); // Upgrade methods to call of global PluginHooks instance var _run = instance.PluginHooks.run , _exe = instance.PluginHooks.execute; instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) { _run.call(this, instance, key, p1, p2, p3, p4, p5); Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5); }; instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) { var globalHandlerResult = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5); var localHandlerResult = _exe.call(this, instance, key, globalHandlerResult, p2, p3, p4, p5); return typeof localHandlerResult == 'undefined' ? globalHandlerResult : localHandlerResult; }; // Map old API with new methods instance.addHook = function () { instance.PluginHooks.add.apply(instance.PluginHooks, arguments); }; instance.addHookOnce = function () { instance.PluginHooks.once.apply(instance.PluginHooks, arguments); }; instance.removeHook = function () { instance.PluginHooks.remove.apply(instance.PluginHooks, arguments); }; instance.runHooks = function () { instance.PluginHooks.run.apply(instance.PluginHooks, arguments); }; instance.runHooksAndReturn = function () { return instance.PluginHooks.execute.apply(instance.PluginHooks, arguments); }; })(); this.timeouts = {}; /** * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called * @public */ this.registerTimeout = function (key, handle, ms) { clearTimeout(this.timeouts[key]); this.timeouts[key] = setTimeout(handle, ms || 0); }; /** * Clears all known timeouts * @public */ this.clearTimeouts = function () { for (var key in this.timeouts) { if (this.timeouts.hasOwnProperty(key)) { clearTimeout(this.timeouts[key]); } } }; /** * Handsontable version */ this.version = '0.10.5'; //inserted by grunt from package.json }; var DefaultSettings = function () {}; DefaultSettings.prototype = { data: void 0, width: void 0, height: void 0, startRows: 5, startCols: 5, rowHeaders: null, colHeaders: null, minRows: 0, minCols: 0, maxRows: Infinity, maxCols: Infinity, minSpareRows: 0, minSpareCols: 0, multiSelect: true, fillHandle: true, fixedRowsTop: 0, fixedColumnsLeft: 0, outsideClickDeselects: true, enterBeginsEditing: true, enterMoves: {row: 1, col: 0}, tabMoves: {row: 0, col: 1}, autoWrapRow: false, autoWrapCol: false, copyRowsLimit: 1000, copyColsLimit: 1000, pasteMode: 'overwrite', currentRowClassName: void 0, currentColClassName: void 0, stretchH: 'hybrid', isEmptyRow: function (r) { var val; for (var c = 0, clen = this.countCols(); c < clen; c++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, isEmptyCol: function (c) { var val; for (var r = 0, rlen = this.countRows(); r < rlen; r++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, observeDOMVisibility: true, allowInvalid: true, invalidCellClassName: 'htInvalid', placeholderCellClassName: 'htPlaceholder', readOnlyCellClassName: 'htDimmed', fragmentSelection: false, readOnly: false, nativeScrollbars: false, type: 'text', copyable: true, debug: false //shows debug overlays in Walkontable }; Handsontable.DefaultSettings = DefaultSettings; $.fn.handsontable = function (action) { var i , ilen , args , output , userSettings , $this = this.first() // Use only first element from list , instance = $this.data('handsontable'); // Init case if (typeof action !== 'string') { userSettings = action || {}; if (instance) { instance.updateSettings(userSettings); } else { instance = new Handsontable.Core($this, userSettings); $this.data('handsontable', instance); instance.init(); } return $this; } // Action case else { args = []; if (arguments.length > 1) { for (i = 1, ilen = arguments.length; i < ilen; i++) { args.push(arguments[i]); } } if (instance) { if (typeof instance[action] !== 'undefined') { output = instance[action].apply(instance, args); } else { throw new Error('Handsontable do not provide action: ' + action); } } return output; } }; (function (window) { 'use strict'; function MultiMap() { var map = { arrayMap: [], weakMap: new WeakMap() }; return { 'get': function (key) { if (canBeAnArrayMapKey(key)) { return map.arrayMap[key]; } else if (canBeAWeakMapKey(key)) { return map.weakMap.get(key); } }, 'set': function (key, value) { if (canBeAnArrayMapKey(key)) { map.arrayMap[key] = value; } else if (canBeAWeakMapKey(key)) { map.weakMap.set(key, value); } else { throw new Error('Invalid key type'); } }, 'delete': function (key) { if (canBeAnArrayMapKey(key)) { delete map.arrayMap[key]; } else if (canBeAWeakMapKey(key)) { map.weakMap['delete'](key); //Delete must be called using square bracket notation, because IE8 does not handle using `delete` with dot notation } } }; function canBeAnArrayMapKey(obj){ return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number'); } function canBeAWeakMapKey(obj){ return obj !== null && (typeof obj == 'object' || typeof obj == 'function'); } function isNaNSymbol(obj){ return obj !== obj; // NaN === NaN is always false } } if (!window.MultiMap){ window.MultiMap = MultiMap; } })(window); /** * Handsontable TableView constructor * @param {Object} instance */ Handsontable.TableView = function (instance) { var that = this , $window = $(window) , $documentElement = $(document.documentElement); this.instance = instance; this.settings = instance.getSettings(); this.settingsFromDOM = instance.getSettingsFromDOM(); instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions // in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+ instance.rootElement.addClass('handsontable'); var table = document.createElement('TABLE'); table.className = 'htCore'; this.THEAD = document.createElement('THEAD'); table.appendChild(this.THEAD); this.TBODY = document.createElement('TBODY'); table.appendChild(this.TBODY); instance.$table = $(table); instance.rootElement.prepend(instance.$table); instance.rootElement.on('mousedown.handsontable', function (event) { if (!that.isTextSelectionAllowed(event.target)) { clearTextSelection(); event.preventDefault(); window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe. } }); $documentElement.on('keyup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && !event.shiftKey) { instance.selection.finish(); } }); var isMouseDown; $documentElement.on('mouseup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button instance.selection.finish(); } isMouseDown = false; if (instance.autofill.handle && instance.autofill.handle.isDragged) { if (instance.autofill.handle.isDragged > 1) { instance.autofill.apply(); } instance.autofill.handle.isDragged = 0; } if (Handsontable.helper.isOutsideInput(document.activeElement)) { instance.unlisten(); } }); $documentElement.on('mousedown.' + instance.guid, function (event) { var next = event.target; if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar while (next !== document.documentElement) { if (next === null) { return; //click on something that was a row but now is detached (possibly because your click triggered a rerender) } if (next === instance.rootElement[0] || next.nodeName === 'HANDSONTABLE-TABLE') { return; //click inside container or Web Component (HANDSONTABLE-TABLE is the name of the custom element) } next = next.parentNode; } } if (that.settings.outsideClickDeselects) { instance.deselectCell(); } else { instance.destroyEditor(); } }); instance.rootElement.on('mousedown.handsontable', '.dragdealer', function () { instance.destroyEditor(); }); instance.$table.on('selectstart', function (event) { if (that.settings.fragmentSelection) { return; } //https://github.com/warpech/jquery-handsontable/issues/160 //selectstart is IE only event. Prevent text from being selected when performing drag down in IE8 event.preventDefault(); }); var clearTextSelection = function () { //http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? document.selection.empty(); } }; var walkontableConfig = { debug: function () { return that.settings.debug; }, table: table, stretchH: this.settings.stretchH, data: instance.getDataAtCell, totalRows: instance.countRows, totalColumns: instance.countCols, nativeScrollbars: this.settings.nativeScrollbars, offsetRow: 0, offsetColumn: 0, width: this.getWidth(), height: this.getHeight(), fixedColumnsLeft: function () { return that.settings.fixedColumnsLeft; }, fixedRowsTop: function () { return that.settings.fixedRowsTop; }, rowHeaders: function () { return instance.hasRowHeaders() ? [function (index, TH) { that.appendRowHeader(index, TH); }] : [] }, columnHeaders: function () { return instance.hasColHeaders() ? [function (index, TH) { that.appendColHeader(index, TH); }] : [] }, columnWidth: instance.getColWidth, cellRenderer: function (row, col, TD) { var prop = that.instance.colToProp(col) , cellProperties = that.instance.getCellMeta(row, col) , renderer = that.instance.getCellRenderer(cellProperties); var value = that.instance.getDataAtRowProp(row, prop); renderer(that.instance, TD, row, col, prop, value, cellProperties); that.instance.PluginHooks.run('afterRenderer', TD, row, col, prop, value, cellProperties); }, selections: { current: { className: 'current', border: { width: 2, color: '#5292F7', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple() } } }, area: { className: 'area', border: { width: 1, color: '#89AFF9', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple() } } }, highlight: { highlightRowClassName: that.settings.currentRowClassName, highlightColumnClassName: that.settings.currentColClassName }, fill: { className: 'fill', border: { width: 1, color: 'red', style: 'solid' } } }, hideBorderOnMouseDownOver: function () { return that.settings.fragmentSelection; }, onCellMouseDown: function (event, coords, TD) { instance.listen(); isMouseDown = true; var coordsObj = {row: coords[0], col: coords[1]}; if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button //do nothing } else if (event.shiftKey) { instance.selection.setRangeEnd(coordsObj); } else { instance.selection.setRangeStart(coordsObj); } instance.PluginHooks.run('afterOnCellMouseDown', event, coords, TD); }, /*onCellMouseOut: function (/*event, coords, TD* /) { if (isMouseDown && that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection } },*/ onCellMouseOver: function (event, coords, TD) { var coordsObj = {row: coords[0], col: coords[1]}; if (isMouseDown) { /*if (that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection }*/ instance.selection.setRangeEnd(coordsObj); } else if (instance.autofill.handle && instance.autofill.handle.isDragged) { instance.autofill.handle.isDragged++; instance.autofill.showBorder(coords); } instance.PluginHooks.run('afterOnCellMouseOver', event, coords, TD); }, onCellCornerMouseDown: function (event) { instance.autofill.handle.isDragged = 1; event.preventDefault(); instance.PluginHooks.run('afterOnCellCornerMouseDown', event); }, onCellCornerDblClick: function () { instance.autofill.selectAdjacent(); }, beforeDraw: function (force) { that.beforeRender(force); }, onDraw: function(force){ that.onDraw(force); }, onScrollVertically: function () { instance.runHooks('afterScrollVertically'); }, onScrollHorizontally: function () { instance.runHooks('afterScrollHorizontally'); } }; instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig); this.wt = new Walkontable(walkontableConfig); $window.on('resize.' + instance.guid, function () { instance.registerTimeout('resizeTimeout', function () { instance.parseSettingsFromDOM(); var newWidth = that.getWidth(); var newHeight = that.getHeight(); if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) { instance.forceFullRender = true; that.render(); walkontableConfig.width = newWidth; walkontableConfig.height = newHeight; } }, 60); }); $(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) { if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar event.stopPropagation(); } }); $documentElement.on('click.' + instance.guid, function () { if (that.settings.observeDOMVisibility) { if (that.wt.drawInterrupted) { that.instance.forceFullRender = true; that.render(); } } }); }; Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) { if ( Handsontable.helper.isInput(el) ) { return (true); } if (this.settings.fragmentSelection && this.wt.wtDom.isChildOf(el, this.TBODY)) { return (true); } return false; }; Handsontable.TableView.prototype.isCellEdited = function () { var activeEditor = this.instance.getActiveEditor(); return activeEditor && activeEditor.isOpened(); }; Handsontable.TableView.prototype.getWidth = function () { var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.getHeight = function () { var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.beforeRender = function (force) { if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? this.wt.update('width', this.getWidth()); this.wt.update('height', this.getHeight()); } }; Handsontable.TableView.prototype.onDraw = function(force){ if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? } }; Handsontable.TableView.prototype.render = function () { this.wt.draw(!this.instance.forceFullRender); this.instance.forceFullRender = false; this.instance.rootElement.triggerHandler('render.handsontable'); }; /** * Returns td object given coordinates */ Handsontable.TableView.prototype.getCellAtCoords = function (coords) { var td = this.wt.wtTable.getCell([coords.row, coords.col]); if (td < 0) { //there was an exit code (cell is out of bounds) return null; } else { return td; } }; /** * Scroll viewport to selection * @param coords */ Handsontable.TableView.prototype.scrollViewport = function (coords) { this.wt.scrollViewport([coords.row, coords.col]); }; /** * Append row header to a TH element * @param row * @param TH */ Handsontable.TableView.prototype.appendRowHeader = function (row, TH) { if (row > -1) { this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row)); } else { var DIV = document.createElement('DIV'); DIV.className = 'relative'; this.wt.wtDom.fastInnerText(DIV, '\u00A0'); this.wt.wtDom.empty(TH); TH.appendChild(DIV); } }; /** * Append column header to a TH element * @param col * @param TH */ Handsontable.TableView.prototype.appendColHeader = function (col, TH) { var DIV = document.createElement('DIV') , SPAN = document.createElement('SPAN'); DIV.className = 'relative'; SPAN.className = 'colHeader'; this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col)); DIV.appendChild(SPAN); this.wt.wtDom.empty(TH); TH.appendChild(DIV); this.instance.PluginHooks.run('afterGetColHeader', col, TH); }; /** * Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar) * @param {Number} left * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementWidth = function (left) { var rootWidth = this.wt.wtViewport.getWorkspaceWidth(); if(this.settings.nativeScrollbars) { return rootWidth; } return rootWidth - left; }; /** * Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar) * @param {Number} top * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementHeight = function (top) { var rootHeight = this.wt.wtViewport.getWorkspaceHeight(); if(this.settings.nativeScrollbars) { return rootHeight; } return rootHeight - top; }; /** * Utility to register editors and common namespace for keeping reference to all editor classes */ (function (Handsontable) { 'use strict'; function RegisteredEditor(editorClass) { var clazz, instances; instances = {}; clazz = editorClass; this.getInstance = function (hotInstance) { if (!(hotInstance.guid in instances)) { instances[hotInstance.guid] = new clazz(hotInstance); } return instances[hotInstance.guid]; } } var registeredEditorNames = {}; var registeredEditorClasses = new WeakMap(); Handsontable.editors = { /** * Registers editor under given name * @param {String} editorName * @param {Function} editorClass */ registerEditor: function (editorName, editorClass) { var editor = new RegisteredEditor(editorClass); if (typeof editorName === "string") { registeredEditorNames[editorName] = editor; } registeredEditorClasses.set(editorClass, editor); }, /** * Returns instance (singleton) of editor class * @param {String|Function} editorName/editorClass * @returns {Function} editorClass */ getEditor: function (editorName, hotInstance) { var editor; if (typeof editorName == 'function') { if (!(registeredEditorClasses.get(editorName))) { this.registerEditor(null, editorName); } editor = registeredEditorClasses.get(editorName); } else if (typeof editorName == 'string') { editor = registeredEditorNames[editorName]; } else { throw Error('Only strings and functions can be passed as "editor" parameter '); } if (!editor) { throw Error('No editor registered under name "' + editorName + '"'); } return editor.getInstance(hotInstance); } }; })(Handsontable); (function(Handsontable){ 'use strict'; Handsontable.EditorManager = function(instance, priv, selection){ var that = this; var $document = $(document); var keyCodes = Handsontable.helper.keyCode; var activeEditor; var init = function () { function onKeyDown(event) { if (!instance.isListening()) { return; } if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin priv.settings.beforeOnKeyDown.call(instance, event); } instance.PluginHooks.run('beforeKeyDown', event); if (!event.isImmediatePropagationStopped()) { priv.lastKeyCode = event.keyCode; if (selection.isSelected()) { var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (!activeEditor.isWaiting()) { if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) { that.openEditor(''); event.stopPropagation(); //required by HandsontableEditor return; } } var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart; switch (event.keyCode) { case keyCodes.A: if (ctrlDown) { selection.selectAll(); //select all cells event.preventDefault(); event.stopPropagation(); break; } case keyCodes.ARROW_UP: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionUp(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_DOWN: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionDown(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_RIGHT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionRight(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_LEFT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionLeft(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.TAB: var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves; if (event.shiftKey) { selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left } else { selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed) } event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.BACKSPACE: case keyCodes.DELETE: selection.empty(event); that.prepareEditor(); event.preventDefault(); break; case keyCodes.F2: /* F2 */ that.openEditor(); event.preventDefault(); //prevent Opera from opening Go to Page dialog break; case keyCodes.ENTER: /* return/enter */ if(that.isEditorOpened()){ if (activeEditor.state !== Handsontable.EditorState.WAITING){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionAfterEnter(event.shiftKey); } else { if (instance.getSettings().enterBeginsEditing){ that.openEditor(); } else { moveSelectionAfterEnter(event.shiftKey); } } event.preventDefault(); //don't add newline to field event.stopImmediatePropagation(); //required by HandsontableEditor break; case keyCodes.ESCAPE: if(that.isEditorOpened()){ that.closeEditorAndRestoreOriginalValue(ctrlDown); } event.preventDefault(); break; case keyCodes.HOME: if (event.ctrlKey || event.metaKey) { rangeModifier({row: 0, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: 0}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.END: if (event.ctrlKey || event.metaKey) { rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_UP: selection.transformStart(-instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(-instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page up the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_DOWN: selection.transformStart(instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page down the window event.stopPropagation(); //required by HandsontableEditor break; default: break; } } } } $document.on('keydown.handsontable.' + instance.guid, onKeyDown); function onDblClick() { // that.instance.destroyEditor(); that.openEditor(); } instance.view.wt.update('onCellDblClick', onDblClick); instance.addHook('afterDestroy', function(){ $document.off('keydown.handsontable.' + instance.guid); }); function moveSelectionAfterEnter(shiftKey){ var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves; if (shiftKey) { selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up } else { selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed) } } function moveSelectionUp(shiftKey){ if (shiftKey) { selection.transformEnd(-1, 0); } else { selection.transformStart(-1, 0); } } function moveSelectionDown(shiftKey){ if (shiftKey) { selection.transformEnd(1, 0); //expanding selection down with shift } else { selection.transformStart(1, 0); //move selection down } } function moveSelectionRight(shiftKey){ if (shiftKey) { selection.transformEnd(0, 1); } else { selection.transformStart(0, 1); } } function moveSelectionLeft(shiftKey){ if (shiftKey) { selection.transformEnd(0, -1); } else { selection.transformStart(0, -1); } } }; /** * Destroy current editor, if exists * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { this.closeEditor(revertOriginal); }; this.getActiveEditor = function () { return activeEditor; }; /** * Prepare text input to be displayed at given grid cell */ this.prepareEditor = function () { if (activeEditor && activeEditor.isWaiting()){ this.closeEditor(false, false, function(dataSaved){ if(dataSaved){ that.prepareEditor(); } }); return; } var row = priv.selStart.row(); var col = priv.selStart.col(); var prop = instance.colToProp(col); var td = instance.getCell(row, col); var originalValue = instance.getDataAtCell(row, col); var cellProperties = instance.getCellMeta(row, col); var editorClass = instance.getCellEditor(cellProperties); activeEditor = Handsontable.editors.getEditor(editorClass, instance); activeEditor.prepare(row, col, prop, td, originalValue, cellProperties); }; this.isEditorOpened = function () { return activeEditor.isOpened(); }; this.openEditor = function (initialValue) { if (!activeEditor.cellProperties.readOnly){ activeEditor.beginEditing(initialValue); } }; this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) { if (!activeEditor){ if(callback) { callback(false); } } else { activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback); } }; this.closeEditorAndSaveChanges = function(ctrlDown){ return this.closeEditor(false, ctrlDown); }; this.closeEditorAndRestoreOriginalValue = function(ctrlDown){ return this.closeEditor(true, ctrlDown); }; init(); }; })(Handsontable); /** * Utility to register renderers and common namespace for keeping reference to all renderers classes */ (function (Handsontable) { 'use strict'; var registeredRenderers = {}; Handsontable.renderers = { /** * Registers renderer under given name * @param {String} rendererName * @param {Function} rendererFunction */ registerRenderer: function (rendererName, rendererFunction) { registeredRenderers[rendererName] = rendererFunction }, /** * @param {String|Function} rendererName/rendererFunction * @returns {Function} rendererFunction */ getRenderer: function (rendererName) { if (typeof rendererName == 'function'){ return rendererName; } if (typeof rendererName != 'string'){ throw Error('Only strings and functions can be passed as "renderer" parameter '); } if (!(rendererName in registeredRenderers)) { throw Error('No editor registered under name "' + rendererName + '"'); } return registeredRenderers[rendererName]; } }; })(Handsontable); /** * DOM helper optimized for maximum performance * It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery * @type {WalkonableDom} */ Handsontable.Dom = new WalkontableDom(); /** * Returns true if keyCode represents a printable character * @param {Number} keyCode * @return {Boolean} */ Handsontable.helper.isPrintableChar = function (keyCode) { return ((keyCode == 32) || //space (keyCode >= 48 && keyCode <= 57) || //0-9 (keyCode >= 96 && keyCode <= 111) || //numpad (keyCode >= 186 && keyCode <= 192) || //;=,-./` (keyCode >= 219 && keyCode <= 222) || //[]{}\|"' keyCode >= 226 || //special chars (229 for Asian chars) (keyCode >= 65 && keyCode <= 90)); //a-z }; Handsontable.helper.isMetaKey = function (keyCode) { var keyCodes = Handsontable.helper.keyCode; var metaKeys = [ keyCodes.ARROW_DOWN, keyCodes.ARROW_UP, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT, keyCodes.HOME, keyCodes.END, keyCodes.DELETE, keyCodes.BACKSPACE, keyCodes.F1, keyCodes.F2, keyCodes.F3, keyCodes.F4, keyCodes.F5, keyCodes.F6, keyCodes.F7, keyCodes.F8, keyCodes.F9, keyCodes.F10, keyCodes.F11, keyCodes.F12, keyCodes.TAB, keyCodes.PAGE_DOWN, keyCodes.PAGE_UP, keyCodes.ENTER, keyCodes.ESCAPE, keyCodes.SHIFT, keyCodes.CAPS_LOCK, keyCodes.ALT ]; return metaKeys.indexOf(keyCode) != -1; }; Handsontable.helper.isCtrlKey = function (keyCode) { var keys = Handsontable.helper.keyCode; return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1; }; /** * Converts a value to string * @param value * @return {String} */ Handsontable.helper.stringify = function (value) { switch (typeof value) { case 'string': case 'number': return value + ''; break; case 'object': if (value === null) { return ''; } else { return value.toString(); } break; case 'undefined': return ''; break; default: return value.toString(); } }; /** * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc * @param index * @returns {String} */ Handsontable.helper.spreadsheetColumnLabel = function (index) { var dividend = index + 1; var columnLabel = ''; var modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnLabel = String.fromCharCode(65 + modulo) + columnLabel; dividend = parseInt((dividend - modulo) / 26, 10); } return columnLabel; }; /** * Checks if value of n is a numeric one * http://jsperf.com/isnan-vs-isnumeric/4 * @param n * @returns {boolean} */ Handsontable.helper.isNumeric = function (n) { var t = typeof n; return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false; }; Handsontable.helper.isArray = function (obj) { return Object.prototype.toString.call(obj).match(/array/i) !== null; }; /** * Checks if child is a descendant of given parent node * http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another * @param parent * @param child * @returns {boolean} */ Handsontable.helper.isDescendant = function (parent, child) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Generates a random hex string. Used as namespace for Handsontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ Handsontable.helper.randomString = function () { return walkontableRandomString(); }; /** * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. * Creates temporary dummy function to call it as constructor. * Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516 * @param {Object} Child child class * @param {Object} Parent parent class * @return {Object} extended Child */ Handsontable.helper.inherit = function (Child, Parent) { Parent.prototype.constructor = Parent; Child.prototype = new Parent(); Child.prototype.constructor = Child; return Child; }; /** * Perform shallow extend of a target object with extension's own properties * @param {Object} target An object that will receive the new properties * @param {Object} extension An object containing additional properties to merge into the target */ Handsontable.helper.extend = function (target, extension) { for (var i in extension) { if (extension.hasOwnProperty(i)) { target[i] = extension[i]; } } }; Handsontable.helper.getPrototypeOf = function (obj) { var prototype; if(typeof obj.__proto__ == "object"){ prototype = obj.__proto__; } else { var oldConstructor, constructor = obj.constructor; if (typeof obj.constructor == "function") { oldConstructor = constructor; if (delete obj.constructor){ constructor = obj.constructor; // get real constructor obj.constructor = oldConstructor; // restore constructor } } prototype = constructor ? constructor.prototype : null; // needed for IE } return prototype; }; /** * Factory for columns constructors. * @param {Object} GridSettings * @param {Array} conflictList * @return {Object} ColumnSettings */ Handsontable.helper.columnFactory = function (GridSettings, conflictList) { function ColumnSettings () {} Handsontable.helper.inherit(ColumnSettings, GridSettings); // Clear conflict settings for (var i = 0, len = conflictList.length; i < len; i++) { ColumnSettings.prototype[conflictList[i]] = void 0; } return ColumnSettings; }; Handsontable.helper.translateRowsToColumns = function (input) { var i , ilen , j , jlen , output = [] , olen = 0; for (i = 0, ilen = input.length; i < ilen; i++) { for (j = 0, jlen = input[i].length; j < jlen; j++) { if (j == olen) { output.push([]); olen++; } output[j].push(input[i][j]) } } return output; }; Handsontable.helper.to2dArray = function (arr) { var i = 0 , ilen = arr.length; while (i < ilen) { arr[i] = [arr[i]]; i++; } }; Handsontable.helper.extendArray = function (arr, extension) { var i = 0 , ilen = extension.length; while (i < ilen) { arr.push(extension[i]); i++; } }; /** * Determines if the given DOM element is an input field. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isInput = function (element) { var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return inputs.indexOf(element.nodeName) > -1; } /** * Determines if the given DOM element is an input field placed OUTSIDE of HOT. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isOutsideInput = function (element) { return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1; }; Handsontable.helper.keyCode = { MOUSE_LEFT: 1, MOUSE_RIGHT: 3, MOUSE_MIDDLE: 2, BACKSPACE: 8, COMMA: 188, DELETE: 46, END: 35, ENTER: 13, ESCAPE: 27, CONTROL_LEFT: 91, COMMAND_LEFT: 17, COMMAND_RIGHT: 93, ALT: 18, HOME: 36, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, SPACE: 32, SHIFT: 16, CAPS_LOCK: 20, TAB: 9, ARROW_RIGHT: 39, ARROW_LEFT: 37, ARROW_UP: 38, ARROW_DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, A: 65, X: 88, C: 67, V: 86 }; /** * Determines whether given object is a plain Object. * Note: String and Array are not plain Objects * @param {*} obj * @returns {boolean} */ Handsontable.helper.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; /** * Determines whether given object is an Array. * Note: String is not an Array * @param {*} obj * @returns {boolean} */ Handsontable.helper.isArray = function(obj){ return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]'; }; Handsontable.helper.pivot = function (arr) { var pivotedArr = []; if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){ return pivotedArr; } var rowCount = arr.length; var colCount = arr[0].length; for(var i = 0; i < rowCount; i++){ for(var j = 0; j < colCount; j++){ if(!pivotedArr[j]){ pivotedArr[j] = []; } pivotedArr[j][i] = arr[i][j]; } } return pivotedArr; }; Handsontable.helper.proxy = function (fun, context) { return function () { return fun.apply(context, arguments); }; }; /** * Factory that produces a function for searching methods (or any properties) which could be defined directly in * table configuration or implicitly, within cell type definition. * * For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be * defined implicitly using "type" property. * * Methods/properties defined explicitly always takes precedence over those defined through "type". * * If the method/property is not found in an object, searching is continued recursively through prototype chain, until * it reaches the Object.prototype. * * * @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable') * @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type" * @returns {Function} */ Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) { allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined; return function cellMethodLookup (row, col) { return (function getMethodFromProperties(properties) { if (!properties){ return; //method not found } else if (properties.hasOwnProperty(methodName) && properties[methodName]) { //check if it is own and is not empty return properties[methodName]; //method defined directly } else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty var type; if(typeof properties.type != 'string' ){ throw new Error('Cell type must be a string '); } type = translateTypeNameToObject(properties.type); if (type.hasOwnProperty(methodName)) { return type[methodName]; //method defined in type. } else if (allowUndefined) { return; //method does not defined in type (eg. validator), returns undefined } } return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties)); })(typeof row == 'number' ? this.getCellMeta(row, col) : row); }; function translateTypeNameToObject(typeName) { var type = Handsontable.cellTypes[typeName]; if(typeof type == 'undefined'){ throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } return type; } }; Handsontable.helper.toString = function (obj) { return '' + obj; }; Handsontable.SelectionPoint = function () { this._row = null; //private use intended this._col = null; }; Handsontable.SelectionPoint.prototype.exists = function () { return (this._row !== null); }; Handsontable.SelectionPoint.prototype.row = function (val) { if (val !== void 0) { this._row = val; } return this._row; }; Handsontable.SelectionPoint.prototype.col = function (val) { if (val !== void 0) { this._col = val; } return this._col; }; Handsontable.SelectionPoint.prototype.coords = function (coords) { if (coords !== void 0) { this._row = coords.row; this._col = coords.col; } return { row: this._row, col: this._col } }; Handsontable.SelectionPoint.prototype.arr = function (arr) { if (arr !== void 0) { this._row = arr[0]; this._col = arr[1]; } return [this._row, this._col] }; (function (Handsontable) { 'use strict'; /** * Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names * TODO refactor arguments of methods getRange, getText to be numbers (not objects) * TODO remove priv, GridSettings from object constructor * * @param instance * @param priv * @param GridSettings * @constructor */ Handsontable.DataMap = function (instance, priv, GridSettings) { this.instance = instance; this.priv = priv; this.GridSettings = GridSettings; this.dataSource = this.instance.getSettings().data; if (this.dataSource[0]) { this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]); } else { this.duckSchema = {}; } this.createMap(); this.getVars = {}; //used by modifier this.setVars = {}; //used by modifier }; Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1; Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2; Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) { var schema; if ($.isPlainObject(obj)) { schema = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { if ($.isPlainObject(obj[i])) { schema[i] = this.recursiveDuckSchema(obj[i]); } else { schema[i] = null; } } } } else { schema = []; } return schema; }; Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) { var prop, i; if (typeof lastCol === 'undefined') { lastCol = 0; parent = ''; } if ($.isPlainObject(schema)) { for (i in schema) { if (schema.hasOwnProperty(i)) { if (schema[i] === null) { prop = parent + i; this.colToPropCache.push(prop); this.propToColCache.set(prop, lastCol); lastCol++; } else { lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.'); } } } } return lastCol; }; Handsontable.DataMap.prototype.createMap = function () { if (typeof this.getSchema() === "undefined") { throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`"); } var i, ilen, schema = this.getSchema(); this.colToPropCache = []; this.propToColCache = new MultiMap(); var columns = this.instance.getSettings().columns; if (columns) { for (i = 0, ilen = columns.length; i < ilen; i++) { if (typeof columns[i].data != 'undefined'){ this.colToPropCache[i] = columns[i].data; this.propToColCache.set(columns[i].data, i); } } } else { this.recursiveDuckColumns(schema); } }; Handsontable.DataMap.prototype.colToProp = function (col) { col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') { return this.colToPropCache[col]; } else { return col; } }; Handsontable.DataMap.prototype.propToCol = function (prop) { var col; if (typeof this.propToColCache.get(prop) !== 'undefined') { col = this.propToColCache.get(prop); } else { col = prop; } col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); return col; }; Handsontable.DataMap.prototype.getSchema = function () { var schema = this.instance.getSettings().dataSchema; if (schema) { if (typeof schema === 'function') { return schema(); } return schema; } return this.duckSchema; }; /** * Creates row at the bottom of the data array * @param {Number} [index] Optional. Index of the row before which the new row will be inserted */ Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) { var row , colCount = this.instance.countCols() , numberOfCreatedRows = 0 , currentIndex; if (!amount) { amount = 1; } if (typeof index !== 'number' || index >= this.instance.countRows()) { index = this.instance.countRows(); } currentIndex = index; var maxRows = this.instance.getSettings().maxRows; while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) { if (this.instance.dataType === 'array') { row = []; for (var c = 0; c < colCount; c++) { row.push(null); } } else if (this.instance.dataType === 'function') { row = this.instance.getSettings().dataSchema(index); } else { row = $.extend(true, {}, this.getSchema()); } if (index === this.instance.countRows()) { this.dataSource.push(row); } else { this.dataSource.splice(index, 0, row); } numberOfCreatedRows++; currentIndex++; } this.instance.PluginHooks.run('afterCreateRow', index, numberOfCreatedRows, createdAutomatically); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedRows; }; /** * Creates col at the right of the data array * @param {Number} [index] Optional. Index of the column before which the new column will be inserted * * @param {Number} [amount] Optional. */ Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("Cannot create new column. When data source in an object, " + "you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." + "If you want to be able to add new columns, you have to use array datasource."); } var rlen = this.instance.countRows() , data = this.dataSource , constructor , numberOfCreatedCols = 0 , currentIndex; if (!amount) { amount = 1; } currentIndex = index; var maxCols = this.instance.getSettings().maxCols; while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) { constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts); if (typeof index !== 'number' || index >= this.instance.countCols()) { for (var r = 0; r < rlen; r++) { if (typeof data[r] === 'undefined') { data[r] = []; } data[r].push(null); } // Add new column constructor this.priv.columnSettings.push(constructor); } else { for (var r = 0; r < rlen; r++) { data[r].splice(currentIndex, 0, null); } // Add new column constructor at given index this.priv.columnSettings.splice(currentIndex, 0, constructor); } numberOfCreatedCols++; currentIndex++; } this.instance.PluginHooks.run('afterCreateCol', index, numberOfCreatedCols, createdAutomatically); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedCols; }; /** * Removes row from the data array * @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed * @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed */ Handsontable.DataMap.prototype.removeRow = function (index, amount) { if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countRows() + index) % this.instance.countRows(); // We have to map the physical row ids to logical and than perform removing with (possibly) new row id var logicRows = this.physicalRowsToLogical(index, amount); var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveRow', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; var newData = data.filter(function (row, index) { return logicRows.indexOf(index) == -1; }); data.length = 0; Array.prototype.push.apply(data, newData); this.instance.PluginHooks.run('afterRemoveRow', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Removes column from the data array * @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed * @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed */ Handsontable.DataMap.prototype.removeCol = function (index, amount) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("cannot remove column with object data source or columns option specified"); } if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countCols() + index) % this.instance.countCols(); var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveCol', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) { data[r].splice(index, amount); } this.priv.columnSettings.splice(index, amount); this.instance.PluginHooks.run('afterRemoveCol', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Add / removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var colData = this.instance.getDataAtCol(col); var removed = colData.slice(index, index + amount); var after = colData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } Handsontable.helper.to2dArray(elements); this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol'); return removed; }; /** * Add / removes data from the row * @param {Number} row Index of row in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var rowData = this.instance.getDataAtRow(row); var removed = rowData.slice(index, index + amount); var after = rowData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow'); return removed; }; /** * Returns single value from the data array * @param {Number} row * @param {Number} prop */ Handsontable.DataMap.prototype.get = function (row, prop) { this.getVars.row = row; this.getVars.prop = prop; this.instance.PluginHooks.run('beforeGet', this.getVars); if (typeof this.getVars.prop === 'string' && this.getVars.prop.indexOf('.') > -1) { var sliced = this.getVars.prop.split("."); var out = this.dataSource[this.getVars.row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else if (typeof this.getVars.prop === 'function') { /** * allows for interacting with complex structures, for example * d3/jQuery getter/setter properties: * * {columns: [{ * data: function(row, value){ * if(arguments.length === 1){ * return row.property(); * } * row.property(value); * } * }]} */ return this.getVars.prop(this.dataSource.slice( this.getVars.row, this.getVars.row + 1 )[0]); } else { return this.dataSource[this.getVars.row] ? this.dataSource[this.getVars.row][this.getVars.prop] : null; } }; var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false); /** * Returns single value from the data array (intended for clipboard copy to an external application) * @param {Number} row * @param {Number} prop * @return {String} */ Handsontable.DataMap.prototype.getCopyable = function (row, prop) { if (copyableLookup.call(this.instance, row, this.propToCol(prop))) { return this.get(row, prop); } return ''; }; /** * Saves single value to the data array * @param {Number} row * @param {Number} prop * @param {String} value * @param {String} [source] Optional. Source of hook runner. */ Handsontable.DataMap.prototype.set = function (row, prop, value, source) { this.setVars.row = row; this.setVars.prop = prop; this.setVars.value = value; this.instance.PluginHooks.run('beforeSet', this.setVars, source || "datamapGet"); if (typeof this.setVars.prop === 'string' && this.setVars.prop.indexOf('.') > -1) { var sliced = this.setVars.prop.split("."); var out = this.dataSource[this.setVars.row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = this.setVars.value; } else if (typeof this.setVars.prop === 'function') { /* see the `function` handler in `get` */ this.setVars.prop(this.dataSource.slice( this.setVars.row, this.setVars.row + 1 )[0], this.setVars.value); } else { this.dataSource[this.setVars.row][this.setVars.prop] = this.setVars.value; } }; /** * This ridiculous piece of code maps rows Id that are present in table data to those displayed for user. * The trick is, the physical row id (stored in settings.data) is not necessary the same * as the logical (displayed) row id (e.g. when sorting is applied). */ Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) { var totalRows = this.instance.countRows(); var physicRow = (totalRows + index) % totalRows; var logicRows = []; var rowsToRemove = amount; while (physicRow < totalRows && rowsToRemove) { this.get(physicRow, 0); //this performs an actual mapping and saves the result to getVars logicRows.push(this.getVars.row); rowsToRemove--; physicRow++; } return logicRows; }; /** * Clears the data array */ Handsontable.DataMap.prototype.clear = function () { for (var r = 0; r < this.instance.countRows(); r++) { for (var c = 0; c < this.instance.countCols(); c++) { this.set(r, this.colToProp(c), ''); } } }; /** * Returns the data array * @return {Array} */ Handsontable.DataMap.prototype.getAll = function () { return this.dataSource; }; /** * Returns data range as array * @param {Object} start Start selection position * @param {Object} end End selection position * @param {Number} destination Destination of datamap.get * @return {Array} */ Handsontable.DataMap.prototype.getRange = function (start, end, destination) { var r, rlen, c, clen, output = [], row; var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(getFn.call(this, r, this.colToProp(c))); } output.push(row); } return output; }; /** * Return data as text (tab separated columns) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER)); }; /** * Return data as copyable text (tab separated columns intended for clipboard copy to an external application) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getCopyableText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR)); }; })(Handsontable); (function (Handsontable) { 'use strict'; /* Adds appropriate CSS class to table cell, based on cellProperties */ Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) { if (cellProperties.readOnly) { instance.view.wt.wtDom.addClass(TD, cellProperties.readOnlyCellClassName); } if (cellProperties.valid === false && cellProperties.invalidCellClassName) { instance.view.wt.wtDom.addClass(TD, cellProperties.invalidCellClassName); } if (!value && cellProperties.placeholder) { instance.view.wt.wtDom.addClass(TD, cellProperties.placeholderCellClassName); } } })(Handsontable); /** * Default text renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.cellDecorator.apply(this, arguments); if (!value && cellProperties.placeholder) { value = cellProperties.placeholder; } var escaped = Handsontable.helper.stringify(value); if (cellProperties.rendererTemplate) { instance.view.wt.wtDom.empty(TD); var TEMPLATE = document.createElement('TEMPLATE'); TEMPLATE.setAttribute('bind', '{{}}'); TEMPLATE.innerHTML = cellProperties.rendererTemplate; HTMLTemplateElement.decorate(TEMPLATE); TEMPLATE.model = instance.getDataAtRow(row); TD.appendChild(TEMPLATE); } else { instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } }; //Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility Handsontable.renderers.TextRenderer = TextRenderer; Handsontable.renderers.registerRenderer('text', TextRenderer); })(Handsontable); (function (Handsontable) { var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; clonableARROW.appendChild(document.createTextNode('\u25BC')); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips var wrapTdContentWithWrapper = function(TD, WRAPPER){ WRAPPER.innerHTML = TD.innerHTML; Handsontable.Dom.empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); Handsontable.Dom.addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals &nbsp; for a text node //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } if (!instance.acArrowListener) { //not very elegant but easy and fast instance.acArrowListener = function () { instance.view.wt.getSetting('onCellDblClick'); }; instance.rootElement.on('mousedown.htAutocompleteArrow', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead //We need to unbind the listener after the table has been destroyed instance.addHookOnce('afterDestroy', function () { this.rootElement.off('mousedown.htAutocompleteArrow'); }); } }; Handsontable.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer); })(Handsontable); /** * Checkbox renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var clonableINPUT = document.createElement('INPUT'); clonableINPUT.className = 'htCheckboxRendererInput'; clonableINPUT.type = 'checkbox'; clonableINPUT.setAttribute('autocomplete', 'off'); var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (typeof cellProperties.checkedTemplate === "undefined") { cellProperties.checkedTemplate = true; } if (typeof cellProperties.uncheckedTemplate === "undefined") { cellProperties.uncheckedTemplate = false; } instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) { INPUT.checked = true; TD.appendChild(INPUT); } else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) { TD.appendChild(INPUT); } else if (value === null) { //default value INPUT.className += ' noValue'; TD.appendChild(INPUT); } else { instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } var $input = $(INPUT); if (cellProperties.readOnly) { $input.on('click', function (event) { event.preventDefault(); }); } else { $input.on('mousedown', function (event) { event.stopPropagation(); //otherwise can confuse cell mousedown handler }); $input.on('mouseup', function (event) { event.stopPropagation(); //otherwise can confuse cell dblclick handler }); $input.on('change', function(){ if (this.checked) { instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate); } else { instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate); } }); } if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){ instance.CheckboxRenderer = { beforeKeyDownHookBound : true }; instance.addHook('beforeKeyDown', function(event){ if(event.keyCode == Handsontable.helper.keyCode.SPACE){ var selection = instance.getSelected(); var cell, checkbox, cellProperties; var selStart = { row: Math.min(selection[0], selection[2]), col: Math.min(selection[1], selection[3]) }; var selEnd = { row: Math.max(selection[0], selection[2]), col: Math.max(selection[1], selection[3]) }; for(var row = selStart.row; row <= selEnd.row; row++ ){ for(var col = selEnd.col; col <= selEnd.col; col++){ cell = instance.getCell(row, col); cellProperties = instance.getCellMeta(row, col); checkbox = cell.querySelectorAll('input[type=checkbox]'); if(checkbox.length > 0 && !cellProperties.readOnly){ if(!event.isImmediatePropagationStopped()){ event.stopImmediatePropagation(); event.preventDefault(); } for(var i = 0, len = checkbox.length; i < len; i++){ checkbox[i].checked = !checkbox[i].checked; $(checkbox[i]).trigger('change'); } } } } } }); } }; Handsontable.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer); })(Handsontable); /** * Numeric cell renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (Handsontable.helper.isNumeric(value)) { if (typeof cellProperties.language !== 'undefined') { numeral.language(cellProperties.language) } value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/ instance.view.wt.wtDom.addClass(TD, 'htNumeric'); } Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); }; Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0 Handsontable.renderers.NumericRenderer = NumericRenderer; Handsontable.renderers.registerRenderer('numeric', NumericRenderer); })(Handsontable); (function(Handosntable){ 'use strict'; var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.TextRenderer.apply(this, arguments); value = TD.innerHTML; var hash; var hashLength = cellProperties.hashLength || value.length; var hashSymbol = cellProperties.hashSymbol || '*'; for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol); instance.view.wt.wtDom.fastInnerHTML(TD, hash); }; Handosntable.PasswordRenderer = PasswordRenderer; Handosntable.renderers.PasswordRenderer = PasswordRenderer; Handosntable.renderers.registerRenderer('password', PasswordRenderer); })(Handsontable); (function (Handsontable) { function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){ Handsontable.renderers.cellDecorator.apply(this, arguments); Handsontable.Dom.fastInnerHTML(TD, value); } Handsontable.renderers.registerRenderer('html', HtmlRenderer); Handsontable.renderers.HtmlRenderer = HtmlRenderer; })(Handsontable); (function (Handsontable) { 'use strict'; Handsontable.EditorState = { VIRGIN: 'STATE_VIRGIN', //before editing EDITING: 'STATE_EDITING', WAITING: 'STATE_WAITING', //waiting for async validation FINISHED: 'STATE_FINISHED' }; function BaseEditor(instance) { this.instance = instance; this.state = Handsontable.EditorState.VIRGIN; this._opened = false; this._closeCallback = null; this.init(); } BaseEditor.prototype._fireCallbacks = function(result) { if(this._closeCallback){ this._closeCallback(result); this._closeCallback = null; } } BaseEditor.prototype.init = function(){}; BaseEditor.prototype.getValue = function(){ throw Error('Editor getValue() method unimplemented'); }; BaseEditor.prototype.setValue = function(newValue){ throw Error('Editor setValue() method unimplemented'); }; BaseEditor.prototype.open = function(){ throw Error('Editor open() method unimplemented'); }; BaseEditor.prototype.close = function(){ throw Error('Editor close() method unimplemented'); }; BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){ this.TD = td; this.row = row; this.col = col; this.prop = prop; this.originalValue = originalValue; this.cellProperties = cellProperties; this.state = Handsontable.EditorState.VIRGIN; }; BaseEditor.prototype.extend = function(){ var baseClass = this.constructor; function Editor(){ baseClass.apply(this, arguments); } function inherit(Child, Parent){ function Bridge() { } Bridge.prototype = Parent.prototype; Child.prototype = new Bridge(); Child.prototype.constructor = Child; return Child; } return inherit(Editor, baseClass); }; BaseEditor.prototype.saveValue = function (val, ctrlDown) { if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = this.instance.getSelected(); this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit'); } else { this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit'); } }; BaseEditor.prototype.beginEditing = function(initialValue){ if (this.state != Handsontable.EditorState.VIRGIN) { return; } this.instance.view.scrollViewport({row: this.row, col: this.col}); this.instance.view.render(); this.state = Handsontable.EditorState.EDITING; initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue; this.setValue(Handsontable.helper.stringify(initialValue)); this.open(); this._opened = true; this.focus(); this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered) }; BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) { if (callback) { var previousCloseCallback = this._closeCallback; this._closeCallback = function (result) { if(previousCloseCallback){ previousCloseCallback(result); } callback(result); }; } if (this.isWaiting()) { return; } if (this.state == Handsontable.EditorState.VIRGIN) { var that = this; setTimeout(function () { that._fireCallbacks(true); }); return; } if (this.state == Handsontable.EditorState.EDITING) { if (restoreOriginalValue) { this.cancelChanges(); return; } var val = [ [String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js ]; this.state = Handsontable.EditorState.WAITING; this.saveValue(val, ctrlDown); if(this.instance.getCellValidator(this.cellProperties)){ var that = this; this.instance.addHookOnce('afterValidate', function (result) { that.state = Handsontable.EditorState.FINISHED; that.discardEditor(result); }); } else { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(true); } } }; BaseEditor.prototype.cancelChanges = function () { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(); }; BaseEditor.prototype.discardEditor = function (result) { if (this.state !== Handsontable.EditorState.FINISHED) { return; } if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed this.instance.selectCell(this.row, this.col); this.focus(); this.state = Handsontable.EditorState.EDITING; this._fireCallbacks(false); } else { this.close(); this._opened = false; this.state = Handsontable.EditorState.VIRGIN; this._fireCallbacks(true); } }; BaseEditor.prototype.isOpened = function(){ return this._opened; }; BaseEditor.prototype.isWaiting = function () { return this.state === Handsontable.EditorState.WAITING; }; Handsontable.editors.BaseEditor = BaseEditor; })(Handsontable); (function(Handsontable){ var TextEditor = Handsontable.editors.BaseEditor.prototype.extend(); TextEditor.prototype.init = function(){ this.createElements(); this.bindEvents(); }; TextEditor.prototype.getValue = function(){ return this.TEXTAREA.value }; TextEditor.prototype.setValue = function(newValue){ this.TEXTAREA.value = newValue; }; var onBeforeKeyDown = function onBeforeKeyDown(event){ var instance = this; var that = instance.getActiveEditor(); var keyCodes = Handsontable.helper.keyCode; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) //Process only events that have been fired in the editor if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){ return; } if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) { //when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea event.stopImmediatePropagation(); return; } switch (event.keyCode) { case keyCodes.ARROW_RIGHT: if (that.wtDom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) { event.stopImmediatePropagation(); } break; case keyCodes.ARROW_LEFT: /* arrow left */ if (that.wtDom.getCaretPosition(that.TEXTAREA) !== 0) { event.stopImmediatePropagation(); } break; case keyCodes.ENTER: var selected = that.instance.getSelected(); var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]); if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line if(that.isOpened()){ that.setValue(that.getValue() + '\n'); that.focus(); } else { that.beginEditing(that.originalValue + '\n') } event.stopImmediatePropagation(); } event.preventDefault(); //don't add newline to field break; case keyCodes.A: case keyCodes.X: case keyCodes.C: case keyCodes.V: if(ctrlDown){ event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context) break; } case keyCodes.BACKSPACE: case keyCodes.DELETE: case keyCodes.HOME: case keyCodes.END: event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context) break; } }; TextEditor.prototype.open = function(){ this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348 this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.close = function(){ this.textareaParentStyle.display = 'none'; if (document.activeElement === this.TEXTAREA) { this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose } this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.focus = function(){ this.TEXTAREA.focus(); this.wtDom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length); }; TextEditor.prototype.createElements = function () { this.$body = $(document.body); this.wtDom = new WalkontableDom(); this.TEXTAREA = document.createElement('TEXTAREA'); this.$textarea = $(this.TEXTAREA); this.wtDom.addClass(this.TEXTAREA, 'handsontableInput'); this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.TEXTAREA_PARENT = document.createElement('DIV'); this.wtDom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder'); this.textareaParentStyle = this.TEXTAREA_PARENT.style; this.textareaParentStyle.top = 0; this.textareaParentStyle.left = 0; this.textareaParentStyle.display = 'none'; this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT); var that = this; Handsontable.PluginHooks.add('afterRender', function () { that.instance.registerTimeout('refresh_editor_dimensions', function () { that.refreshDimensions(); }, 0); }); }; TextEditor.prototype.refreshDimensions = function () { if (this.state !== Handsontable.EditorState.EDITING) { return; } ///start prepare textarea position this.TD = this.instance.getCell(this.row, this.col); if (!this.TD) { //TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited return; } var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport var currentOffset = this.wtDom.offset(this.TD); var containerOffset = this.wtDom.offset(this.instance.rootElement[0]); var scrollTop = this.instance.rootElement.scrollTop(); var scrollLeft = this.instance.rootElement.scrollLeft(); var editTop = currentOffset.top - containerOffset.top + scrollTop - 1; var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1; var settings = this.instance.getSettings(); var rowHeadersCount = settings.rowHeaders === false ? 0 : 1; var colHeadersCount = settings.colHeaders === false ? 0 : 1; if (editTop < 0) { editTop = 0; } if (editLeft < 0) { editLeft = 0; } if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) { editTop += 1; } if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) { editLeft += 1; } this.textareaParentStyle.top = editTop + 'px'; this.textareaParentStyle.left = editLeft + 'px'; ///end prepare textarea position var width = $td.width() , maxWidth = this.instance.view.maximumVisibleElementWidth(editLeft) - 10 //10 is TEXTAREAs border and padding , height = $td.outerHeight() - 4 , maxHeight = this.instance.view.maximumVisibleElementHeight(editTop) - 5; //10 is TEXTAREAs border and padding if (parseInt($td.css('border-top-width'), 10) > 0) { height -= 1; } if (parseInt($td.css('border-left-width'), 10) > 0) { if (rowHeadersCount > 0) { width -= 1; } } //in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize this.$textarea.autoResize({ minHeight: Math.min(height, maxHeight), maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) minWidth: Math.min(width, maxWidth), maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) animate: false, extraSpace: 0 }); this.textareaParentStyle.display = 'block'; }; TextEditor.prototype.bindEvents = function () { this.$textarea.on('cut.editor', function (event) { event.stopPropagation(); }); this.$textarea.on('paste.editor', function (event) { event.stopPropagation(); }); }; Handsontable.editors.TextEditor = TextEditor; Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor); })(Handsontable); (function(Handsontable){ //Blank editor, because all the work is done by renderer var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend(); CheckboxEditor.prototype.beginEditing = function () { var checkbox = this.TD.querySelector('input[type="checkbox"]'); if (checkbox) { $(checkbox).trigger('click'); } }; CheckboxEditor.prototype.finishEditing = function () {}; CheckboxEditor.prototype.init = function () {}; CheckboxEditor.prototype.open = function () {}; CheckboxEditor.prototype.close = function () {}; CheckboxEditor.prototype.getValue = function () {}; CheckboxEditor.prototype.setValue = function () {}; CheckboxEditor.prototype.focus = function () {}; Handsontable.editors.CheckboxEditor = CheckboxEditor; Handsontable.editors.registerEditor('checkbox', CheckboxEditor); })(Handsontable); (function (Handsontable) { var DateEditor = Handsontable.editors.TextEditor.prototype.extend(); DateEditor.prototype.init = function () { if (!$.datepicker) { throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?"); } Handsontable.editors.TextEditor.prototype.init.apply(this, arguments); this.isCellEdited = false; var that = this; this.instance.addHook('afterDestroy', function () { that.destroyElements(); }) }; DateEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.datePicker = document.createElement('DIV'); this.instance.view.wt.wtDom.addClass(this.datePicker, 'htDatepickerHolder'); this.datePickerStyle = this.datePicker.style; this.datePickerStyle.position = 'absolute'; this.datePickerStyle.top = 0; this.datePickerStyle.left = 0; this.datePickerStyle.zIndex = 99; document.body.appendChild(this.datePicker); this.$datePicker = $(this.datePicker); var that = this; var defaultOptions = { dateFormat: "yy-mm-dd", showButtonPanel: true, changeMonth: true, changeYear: true, onSelect: function (dateStr) { that.setValue(dateStr); that.finishEditing(false); } }; this.$datePicker.datepicker(defaultOptions); /** * Prevent recognizing clicking on jQuery Datepicker as clicking outside of table */ this.$datePicker.on('mousedown', function (event) { event.stopPropagation(); }); this.hideDatepicker(); }; DateEditor.prototype.destroyElements = function () { this.$datePicker.datepicker('destroy'); this.$datePicker.remove(); }; DateEditor.prototype.open = function () { Handsontable.editors.TextEditor.prototype.open.call(this); this.showDatepicker(); }; DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { this.hideDatepicker(); Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; DateEditor.prototype.showDatepicker = function () { var $td = $(this.TD); var offset = $td.offset(); this.datePickerStyle.top = (offset.top + $td.height()) + 'px'; this.datePickerStyle.left = offset.left + 'px'; var dateOptions = { defaultDate: this.originalValue || void 0 }; $.extend(dateOptions, this.cellProperties); this.$datePicker.datepicker("option", dateOptions); if (this.originalValue) { this.$datePicker.datepicker("setDate", this.originalValue); } this.datePickerStyle.display = 'block'; }; DateEditor.prototype.hideDatepicker = function () { this.datePickerStyle.display = 'none'; }; Handsontable.editors.DateEditor = DateEditor; Handsontable.editors.registerEditor('date', DateEditor); })(Handsontable); /** * This is inception. Using Handsontable as Handsontable editor */ (function (Handsontable) { "use strict"; var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend(); HandsontableEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); var DIV = document.createElement('DIV'); DIV.className = 'handsontableEditor'; this.TEXTAREA_PARENT.appendChild(DIV); this.$htContainer = $(DIV); this.$htContainer.handsontable(); }; HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) { Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments); var parent = this; var options = { startRows: 0, startCols: 0, minRows: 0, minCols: 0, className: 'listbox', copyPaste: false, cells: function () { return { readOnly: true } }, fillHandle: false, afterOnCellMouseDown: function () { var value = this.getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); }, beforeOnKeyDown: function (event) { var instance = this; switch (event.keyCode) { case Handsontable.helper.keyCode.ESCAPE: parent.instance.destroyEditor(true); event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ENTER: //enter var sel = instance.getSelected(); var value = this.getDataAtCell(sel[0], sel[1]); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); break; case Handsontable.helper.keyCode.ARROW_UP: if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){ instance.deselectCell(); parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } break; } } }; if (this.cellProperties.handsontable) { options = $.extend(options, cellProperties.handsontable); } this.$htContainer.handsontable('destroy'); this.$htContainer.handsontable(options); }; var onBeforeKeyDown = function (event) { if (event.isImmediatePropagationStopped()) { return; } var editor = this.getActiveEditor(); var innerHOT = editor.$htContainer.handsontable('getInstance'); if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) { if (!innerHOT.getSelected()){ innerHOT.selectCell(0, 0); } else { var selectedRow = innerHOT.getSelected()[0]; var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow; innerHOT.selectCell(rowToSelect, 0); } event.preventDefault(); event.stopImmediatePropagation(); } }; HandsontableEditor.prototype.open = function () { this.instance.addHook('beforeKeyDown', onBeforeKeyDown); Handsontable.editors.TextEditor.prototype.open.apply(this, arguments); this.$htContainer.handsontable('render'); if (this.cellProperties.strict) { this.$htContainer.handsontable('selectCell', 0, 0); this.$textarea[0].style.visibility = 'hidden'; } else { this.$htContainer.handsontable('deselectCell'); this.$textarea[0].style.visibility = 'visible'; } this.wtDom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length); }; HandsontableEditor.prototype.close = function () { this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); this.instance.listen(); Handsontable.editors.TextEditor.prototype.close.apply(this, arguments); }; HandsontableEditor.prototype.focus = function () { this.instance.listen(); Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments); }; HandsontableEditor.prototype.beginEditing = function (initialValue) { var onBeginEditing = this.instance.getSettings().onBeginEditing; if (onBeginEditing && onBeginEditing() === false) { return; } Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments); }; HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor this.instance.listen(); //return the focus to the parent HOT instance } if (this.$htContainer.handsontable('getSelected')) { var value = this.$htContainer.handsontable('getInstance').getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value this.setValue(value); } } return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; Handsontable.editors.HandsontableEditor = HandsontableEditor; Handsontable.editors.registerEditor('handsontable', HandsontableEditor); })(Handsontable); (function (Handsontable) { var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend(); AutocompleteEditor.prototype.init = function () { Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments); this.query = null; this.choices = []; }; AutocompleteEditor.prototype.createElements = function(){ Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments); this.$htContainer.addClass('autocompleteEditor'); }; AutocompleteEditor.prototype.bindEvents = function(){ var that = this; this.$textarea.on('keydown.autocompleteEditor', function(event){ if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){ setTimeout(function () { that.queryChoices(that.$textarea.val()); }); } else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){ that.$htContainer.handsontable('deselectCell'); } }); this.$htContainer.on('mouseleave', function () { if(that.cellProperties.strict === true){ that.highlightBestMatchingChoice(); } }); this.$htContainer.on('mouseenter', function () { that.$htContainer.handsontable('deselectCell'); }); Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments); }; var onBeforeKeyDownInner; AutocompleteEditor.prototype.open = function () { Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments); this.$textarea[0].style.visibility = 'visible'; this.focus(); var choicesListHot = this.$htContainer.handsontable('getInstance'); var that = this; choicesListHot.updateSettings({ 'colWidths': [this.wtDom.outerWidth(this.TEXTAREA) - 2], afterRenderer: function (TD, row, col, prop, value) { var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true; var indexOfMatch = caseSensitive ? value.indexOf(this.query) : value.toLowerCase().indexOf(that.query.toLowerCase()); if(indexOfMatch != -1){ var match = value.substr(indexOfMatch, that.query.length); TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>'); } } }); onBeforeKeyDownInner = function (event) { var instance = this; if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){ if (instance.getSelected() && instance.getSelected()[0] == 0){ if(!parent.cellProperties.strict){ instance.deselectCell(); } parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } } }; choicesListHot.addHook('beforeKeyDown', onBeforeKeyDownInner); this.queryChoices(this.TEXTAREA.value); }; AutocompleteEditor.prototype.close = function () { this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner); Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments); }; AutocompleteEditor.prototype.queryChoices = function(query){ this.query = query; if (typeof this.cellProperties.source == 'function'){ var that = this; this.cellProperties.source(query, function(choices){ that.updateChoicesList(choices) }); } else if (Handsontable.helper.isArray(this.cellProperties.source)) { var choices; if(!query || this.cellProperties.filter === false){ choices = this.cellProperties.source; } else { var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true; var lowerCaseQuery = query.toLowerCase(); choices = this.cellProperties.source.filter(function(choice){ if (filteringCaseSensitive) { return choice.indexOf(query) != -1; } else { return choice.toLowerCase().indexOf(lowerCaseQuery) != -1; } }); } this.updateChoicesList(choices) } else { this.updateChoicesList([]); } }; AutocompleteEditor.prototype.updateChoicesList = function (choices) { this.choices = choices; this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices])); if(this.cellProperties.strict === true){ this.highlightBestMatchingChoice(); } this.focus(); }; AutocompleteEditor.prototype.highlightBestMatchingChoice = function () { var bestMatchingChoice = this.findBestMatchingChoice(); if ( typeof bestMatchingChoice == 'undefined' && this.cellProperties.allowInvalid === false){ bestMatchingChoice = 0; } if(typeof bestMatchingChoice == 'undefined'){ this.$htContainer.handsontable('deselectCell'); } else { this.$htContainer.handsontable('selectCell', bestMatchingChoice, 0); } }; AutocompleteEditor.prototype.findBestMatchingChoice = function(){ var bestMatch = {}; var valueLength = this.getValue().length; var currentItem; var indexOfValue; var charsLeft; for(var i = 0, len = this.choices.length; i < len; i++){ currentItem = this.choices[i]; if(valueLength > 0){ indexOfValue = currentItem.indexOf(this.getValue()) } else { indexOfValue = currentItem === this.getValue() ? 0 : -1; } if(indexOfValue == -1) continue; charsLeft = currentItem.length - indexOfValue - valueLength; if( typeof bestMatch.indexOfValue == 'undefined' || bestMatch.indexOfValue > indexOfValue || ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){ bestMatch.indexOfValue = indexOfValue; bestMatch.charsLeft = charsLeft; bestMatch.index = i; } } return bestMatch.index; }; Handsontable.editors.AutocompleteEditor = AutocompleteEditor; Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor); })(Handsontable); (function(Handsontable){ var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend(); var wtDom = new WalkontableDom(); PasswordEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.TEXTAREA = document.createElement('input'); this.TEXTAREA.setAttribute('type', 'password'); this.TEXTAREA.className = 'handsontableInput'; this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.$textarea = $(this.TEXTAREA); wtDom.empty(this.TEXTAREA_PARENT); this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); }; Handsontable.editors.PasswordEditor = PasswordEditor; Handsontable.editors.registerEditor('password', PasswordEditor); })(Handsontable); (function (Handsontable) { var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend(); SelectEditor.prototype.init = function(){ this.select = document.createElement('SELECT'); Handsontable.Dom.addClass(this.select, 'htSelectEditor'); this.select.style.display = 'none'; this.instance.rootElement[0].appendChild(this.select); }; SelectEditor.prototype.prepare = function(){ Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments); var selectOptions = this.cellProperties.selectOptions; var options; if (typeof selectOptions == 'function'){ options = this.prepareOptions(selectOptions(this.row, this.col, this.prop)) } else { options = this.prepareOptions(selectOptions); } Handsontable.Dom.empty(this.select); for (var option in options){ if (options.hasOwnProperty(option)){ var optionElement = document.createElement('OPTION'); optionElement.value = option; Handsontable.Dom.fastInnerHTML(optionElement, options[option]); this.select.appendChild(optionElement); } } }; SelectEditor.prototype.prepareOptions = function(optionsToPrepare){ var preparedOptions = {}; if (Handsontable.helper.isArray(optionsToPrepare)){ for(var i = 0, len = optionsToPrepare.length; i < len; i++){ preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i]; } } else if (typeof optionsToPrepare == 'object') { preparedOptions = optionsToPrepare; } return preparedOptions; }; SelectEditor.prototype.getValue = function () { return this.select.value; }; SelectEditor.prototype.setValue = function (value) { this.select.value = value; }; var onBeforeKeyDown = function (event) { var instance = this; var editor = instance.getActiveEditor(); switch (event.keyCode){ case Handsontable.helper.keyCode.ARROW_UP: var previousOption = editor.select.find('option:selected').prev(); if (previousOption.length == 1){ previousOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ARROW_DOWN: var nextOption = editor.select.find('option:selected').next(); if (nextOption.length == 1){ nextOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; } }; SelectEditor.prototype.open = function () { var width = Handsontable.Dom.outerWidth(this.TD); //important - group layout reads together for better performance var height = Handsontable.Dom.outerHeight(this.TD); var rootOffset = Handsontable.Dom.offset(this.instance.rootElement[0]); var tdOffset = Handsontable.Dom.offset(this.TD); this.select.style.height = height + 'px'; this.select.style.minWidth = width + 'px'; this.select.style.top = tdOffset.top - rootOffset.top + 'px'; this.select.style.left = tdOffset.left - rootOffset.left - 2 + 'px'; //2 is cell border this.select.style.display = ''; this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.close = function () { this.select.style.display = 'none'; this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.focus = function () { this.select.focus(); }; Handsontable.editors.SelectEditor = SelectEditor; Handsontable.editors.registerEditor('select', SelectEditor); })(Handsontable); (function (Handsontable) { var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend(); DropdownEditor.prototype.prepare = function () { Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments); this.cellProperties.filter = false; this.cellProperties.strict = true; }; Handsontable.editors.DropdownEditor = DropdownEditor; Handsontable.editors.registerEditor('dropdown', DropdownEditor); })(Handsontable); /** * Numeric cell validator * @param {*} value - Value of edited cell * @param {*} callback - Callback called with validation result */ Handsontable.NumericValidator = function (value, callback) { if (value === null) { value = ''; } callback(/^-?\d*\.?\d*$/.test(value)); }; /** * Function responsible for validation of autocomplete value * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ var process = function (value, callback) { var originalVal = value; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { // changes[i][3] = source[s]; //good match, fix the case << TODO? found = true; break; } } callback(found); } }; /** * Autocomplete cell validator * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ Handsontable.AutocompleteValidator = function (value, callback) { if (this.strict && this.source) { typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source); } else { callback(true); } }; /** * Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta) */ Handsontable.AutocompleteCell = { editor: Handsontable.editors.AutocompleteEditor, renderer: Handsontable.renderers.AutocompleteRenderer, validator: Handsontable.AutocompleteValidator }; Handsontable.CheckboxCell = { editor: Handsontable.editors.CheckboxEditor, renderer: Handsontable.renderers.CheckboxRenderer }; Handsontable.TextCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.TextRenderer }; Handsontable.NumericCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.NumericRenderer, validator: Handsontable.NumericValidator, dataType: 'number' }; Handsontable.DateCell = { editor: Handsontable.editors.DateEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.HandsontableCell = { editor: Handsontable.editors.HandsontableEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.PasswordCell = { editor: Handsontable.editors.PasswordEditor, renderer: Handsontable.renderers.PasswordRenderer, copyable: false }; Handsontable.DropdownCell = { editor: Handsontable.editors.DropdownEditor, renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell validator: Handsontable.AutocompleteValidator }; //here setup the friendly aliases that are used by cellProperties.type Handsontable.cellTypes = { text: Handsontable.TextCell, date: Handsontable.DateCell, numeric: Handsontable.NumericCell, checkbox: Handsontable.CheckboxCell, autocomplete: Handsontable.AutocompleteCell, handsontable: Handsontable.HandsontableCell, password: Handsontable.PasswordCell, dropdown: Handsontable.DropdownCell }; //here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor Handsontable.cellLookup = { validator: { numeric: Handsontable.NumericValidator, autocomplete: Handsontable.AutocompleteValidator } }; /* * jQuery.fn.autoResize 1.1+ * -- * https://github.com/warpech/jQuery.fn.autoResize * * This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically). * It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future. * * originally forked from: * https://github.com/jamespadolsey/jQuery.fn.autoResize * which is now located here: * https://github.com/alexbardas/jQuery.fn.autoResize * though the mostly maintained for is here: * https://github.com/dpashkevich/jQuery.fn.autoResize/network * * -- * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ (function($){ autoResize.defaults = { onResize: function(){}, animate: { duration: 200, complete: function(){} }, extraSpace: 50, minHeight: 'original', maxHeight: 500, minWidth: 'original', maxWidth: 500 }; autoResize.cloneCSSProperties = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'padding' ]; autoResize.cloneCSSValues = { position: 'absolute', top: -9999, left: -9999, opacity: 0, overflow: 'hidden', overflowX: 'hidden', overflowY: 'hidden', border: '1px solid black', padding: '0.49em' //this must be about the width of caps W character }; autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]'; autoResize.AutoResizer = AutoResizer; $.fn.autoResize = autoResize; function autoResize(config) { this.filter(autoResize.resizableFilterSelector).each(function(){ new AutoResizer( $(this), config ); }); return this; } function AutoResizer(el, config) { if(this.clones) return; this.config = $.extend({}, autoResize.defaults, config); this.el = el; this.nodeName = el[0].nodeName.toLowerCase(); this.previousScrollTop = null; if (config.maxWidth === 'original') config.maxWidth = el.width(); if (config.minWidth === 'original') config.minWidth = el.width(); if (config.maxHeight === 'original') config.maxHeight = el.height(); if (config.minHeight === 'original') config.minHeight = el.height(); if (this.nodeName === 'textarea') { el.css({ resize: 'none', overflowY: 'none' }); } el.data('AutoResizer', this); this.createClone(); this.injectClone(); this.bind(); } AutoResizer.prototype = { bind: function() { var check = $.proxy(function(){ this.check(); return true; }, this); this.unbind(); this.el .bind('keyup.autoResize', check) //.bind('keydown.autoResize', check) .bind('change.autoResize', check); this.check(null, true); }, unbind: function() { this.el.unbind('.autoResize'); }, createClone: function() { var el = this.el, self = this, config = this.config; this.clones = $(); if (config.minHeight !== 'original' || config.maxHeight !== 'original') { this.hClone = el.clone().height('auto'); this.clones = this.clones.add(this.hClone); } if (config.minWidth !== 'original' || config.maxWidth !== 'original') { this.wClone = $('<div/>').width('auto').css({ whiteSpace: 'nowrap', 'float': 'left' }); this.clones = this.clones.add(this.wClone); } $.each(autoResize.cloneCSSProperties, function(i, p){ self.clones.css(p, el.css(p)); }); this.clones .removeAttr('name') .removeAttr('id') .attr('tabIndex', -1) .css(autoResize.cloneCSSValues) .css('overflowY', 'scroll'); }, check: function(e, immediate) { var config = this.config, wClone = this.wClone, hClone = this.hClone, el = this.el, value = el.val(); if (wClone) { wClone.text(value); // Calculate new width + whether to change var cloneWidth = wClone.outerWidth(), newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ? cloneWidth + config.extraSpace : config.minWidth, currentWidth = el.width(); newWidth = Math.min(newWidth, config.maxWidth); if ( (newWidth < currentWidth && newWidth >= config.minWidth) || (newWidth >= config.minWidth && newWidth <= config.maxWidth) ) { config.onResize.call(el); el.scrollLeft(0); config.animate && !immediate ? el.stop(1,1).animate({ width: newWidth }, config.animate) : el.width(newWidth); } } if (hClone) { if (newWidth) { hClone.width(newWidth); } hClone.height(0).val(value).scrollTop(10000); var scrollTop = hClone[0].scrollTop + config.extraSpace; // Don't do anything if scrollTop hasen't changed: if (this.previousScrollTop === scrollTop) { return; } this.previousScrollTop = scrollTop; if (scrollTop >= config.maxHeight) { scrollTop = config.maxHeight; } if (scrollTop < config.minHeight) { scrollTop = config.minHeight; } if(scrollTop == config.maxHeight && newWidth == config.maxWidth) { el.css('overflowY', 'scroll'); } else { el.css('overflowY', 'hidden'); } config.onResize.call(el); // Either animate or directly apply height: config.animate && !immediate ? el.stop(1,1).animate({ height: scrollTop }, config.animate) : el.height(scrollTop); } }, destroy: function() { this.unbind(); this.el.removeData('AutoResizer'); this.clones.remove(); delete this.el; delete this.hClone; delete this.wClone; delete this.clones; }, injectClone: function() { ( autoResize.cloneContainer || (autoResize.cloneContainer = $('<arclones/>').appendTo('body')) ).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once } }; })(jQuery); /** * SheetClip - Spreadsheet Clipboard Parser * version 0.2 * * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice, * Google Docs and Microsoft Excel. * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://github.com/warpech/sheetclip/ */ /*jslint white: true*/ (function (global) { "use strict"; function countQuotes(str) { return str.split('"').length - 1; } global.SheetClip = { parse: function (str) { var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last; rows = str.split('\n'); if (rows.length > 1 && rows[rows.length - 1] === '') { rows.pop(); } for (r = 0, rlen = rows.length; r < rlen; r += 1) { rows[r] = rows[r].split('\t'); for (c = 0, clen = rows[r].length; c < clen; c += 1) { if (!arr[a]) { arr[a] = []; } if (multiline && c === 0) { last = arr[a].length - 1; arr[a][last] = arr[a][last] + '\n' + rows[r][0]; if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2 multiline = false; arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"'); } } else { if (c === clen - 1 && rows[r][c].indexOf('"') === 0) { arr[a].push(rows[r][c].substring(1).replace(/""/g, '"')); multiline = true; } else { arr[a].push(rows[r][c].replace(/""/g, '"')); multiline = false; } } } if (!multiline) { a += 1; } } return arr; }, stringify: function (arr) { var r, rlen, c, clen, str = '', val; for (r = 0, rlen = arr.length; r < rlen; r += 1) { for (c = 0, clen = arr[r].length; c < clen; c += 1) { if (c > 0) { str += '\t'; } val = arr[r][c]; if (typeof val === 'string') { if (val.indexOf('\n') > -1) { str += '"' + val.replace(/"/g, '""') + '"'; } else { str += val; } } else if (val === null || val === void 0) { //void 0 resolves to undefined str += ''; } else { str += val; } } str += '\n'; } return str; } }; }(window)); /** * CopyPaste.js * Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused * In future we may implement a better driver when better APIs are available * @constructor */ var CopyPaste = (function () { var instance; return { getInstance: function () { if (!instance) { instance = new CopyPasteClass(); } else if (instance.hasBeenDestroyed()){ instance.init(); } instance.refCounter++; return instance; } }; })(); function CopyPasteClass() { this.refCounter = 0; this.init(); } CopyPasteClass.prototype.init = function () { var that = this , style , parent; this.copyCallbacks = []; this.cutCallbacks = []; this.pasteCallbacks = []; this.listenerElement = document.documentElement; parent = document.body; if (document.getElementById('CopyPasteDiv')) { this.elDiv = document.getElementById('CopyPasteDiv'); this.elTextarea = this.elDiv.firstChild; } else { this.elDiv = document.createElement('DIV'); this.elDiv.id = 'CopyPasteDiv'; style = this.elDiv.style; style.position = 'fixed'; style.top = '-10000px'; style.left = '-10000px'; parent.appendChild(this.elDiv); this.elTextarea = document.createElement('TEXTAREA'); this.elTextarea.className = 'copyPaste'; style = this.elTextarea.style; style.width = '10000px'; style.height = '10000px'; style.overflow = 'hidden'; this.elDiv.appendChild(this.elTextarea); if (typeof style.opacity !== 'undefined') { style.opacity = 0; } else { /*@cc_on @if (@_jscript) if(typeof style.filter === 'string') { style.filter = 'alpha(opacity=0)'; } @end @*/ } } this.keydownListener = function (event) { var isCtrlDown = false; if (event.metaKey) { //mac isCtrlDown = true; } else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc isCtrlDown = true; } if (isCtrlDown) { if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) { return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected } that.selectNodeText(that.elTextarea); setTimeout(function () { that.selectNodeText(that.elTextarea); }, 0); } /* 67 = c * 86 = v * 88 = x */ if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) { // that.selectNodeText(that.elTextarea); if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12 setTimeout(function () { that.triggerCut(event); }, 0); } else if (event.keyCode === 86) { setTimeout(function () { that.triggerPaste(event); }, 0); } } } this._bindEvent(this.listenerElement, 'keydown', this.keydownListener); }; //http://jsperf.com/textara-selection //http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie CopyPasteClass.prototype.selectNodeText = function (el) { el.select(); }; //http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text CopyPasteClass.prototype.getSelectionText = function () { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }; CopyPasteClass.prototype.copyable = function (str) { if (typeof str !== 'string' && str.toString === void 0) { throw new Error('copyable requires string parameter'); } this.elTextarea.value = str; }; /*CopyPasteClass.prototype.onCopy = function (fn) { this.copyCallbacks.push(fn); };*/ CopyPasteClass.prototype.onCut = function (fn) { this.cutCallbacks.push(fn); }; CopyPasteClass.prototype.onPaste = function (fn) { this.pasteCallbacks.push(fn); }; CopyPasteClass.prototype.removeCallback = function (fn) { var i, ilen; for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) { if (this.copyCallbacks[i] === fn) { this.copyCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) { if (this.cutCallbacks[i] === fn) { this.cutCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) { if (this.pasteCallbacks[i] === fn) { this.pasteCallbacks.splice(i, 1); return true; } } return false; }; CopyPasteClass.prototype.triggerCut = function (event) { var that = this; if (that.cutCallbacks) { setTimeout(function () { for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) { that.cutCallbacks[i](event); } }, 50); } }; CopyPasteClass.prototype.triggerPaste = function (event, str) { var that = this; if (that.pasteCallbacks) { setTimeout(function () { var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) { that.pasteCallbacks[i](val, event); } }, 50); } }; CopyPasteClass.prototype.destroy = function () { if(!this.hasBeenDestroyed() && --this.refCounter == 0){ if (this.elDiv && this.elDiv.parentNode) { this.elDiv.parentNode.removeChild(this.elDiv); } this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener); } }; CopyPasteClass.prototype.hasBeenDestroyed = function () { return !this.refCounter; }; //old version used this: // - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ // - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization //but that cannot work with jQuery.trigger CopyPasteClass.prototype._bindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).on(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); CopyPasteClass.prototype._unbindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).off(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); // json-patch-duplex.js 0.3.6 // (c) 2013 Joachim Wester // MIT license var jsonpatch; (function (jsonpatch) { var objOps = { add: function (obj, key) { obj[key] = this.value; return true; }, remove: function (obj, key) { delete obj[key]; return true; }, replace: function (obj, key) { obj[key] = this.value; return true; }, move: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "remove", path: this.from } ]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, copy: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, test: function (obj, key) { return (JSON.stringify(obj[key]) === JSON.stringify(this.value)); }, _get: function (obj, key) { this.value = obj[key]; } }; var arrOps = { add: function (arr, i) { arr.splice(i, 0, this.value); return true; }, remove: function (arr, i) { arr.splice(i, 1); return true; }, replace: function (arr, i) { arr[i] = this.value; return true; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; var observeOps = { add: function (patches, path) { var patch = { op: "add", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); }, 'delete': function (patches, path) { var patch = { op: "remove", path: path + escapePathComponent(this.name) }; patches.push(patch); }, update: function (patches, path) { var patch = { op: "replace", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); } }; function escapePathComponent(str) { if (str.indexOf('/') === -1 && str.indexOf('~') === -1) return str; return str.replace(/~/g, '~0').replace(/\//g, '~1'); } function _getPathRecursive(root, obj) { var found; for (var key in root) { if (root.hasOwnProperty(key)) { if (root[key] === obj) { return escapePathComponent(key) + '/'; } else if (typeof root[key] === 'object') { found = _getPathRecursive(root[key], obj); if (found != '') { return escapePathComponent(key) + '/' + found; } } } } return ''; } function getPath(root, obj) { if (root === obj) { return '/'; } var path = _getPathRecursive(root, obj); if (path === '') { throw new Error("Object not found in root"); } return '/' + path; } var beforeDict = []; jsonpatch.intervals; var Mirror = (function () { function Mirror(obj) { this.observers = []; this.obj = obj; } return Mirror; })(); var ObserverInfo = (function () { function ObserverInfo(callback, observer) { this.callback = callback; this.observer = observer; } return ObserverInfo; })(); function getMirror(obj) { for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === obj) { return beforeDict[i]; } } } function getObserverFromMirror(mirror, callback) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].callback === callback) { return mirror.observers[j].observer; } } } function removeObserverFromMirror(mirror, observer) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].observer === observer) { mirror.observers.splice(j, 1); return; } } } function unobserve(root, observer) { generate(observer); if (Object.observe) { _unobserve(observer, root); } else { clearTimeout(observer.next); } var mirror = getMirror(root); removeObserverFromMirror(mirror, observer); } jsonpatch.unobserve = unobserve; function observe(obj, callback) { var patches = []; var root = obj; var observer; var mirror = getMirror(obj); if (!mirror) { mirror = new Mirror(obj); beforeDict.push(mirror); } else { observer = getObserverFromMirror(mirror, callback); } if (observer) { return observer; } if (Object.observe) { observer = function (arr) { //This "refresh" is needed to begin observing new object properties _unobserve(observer, obj); _observe(observer, obj); var a = 0, alen = arr.length; while (a < alen) { if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) { var type = arr[a].type; switch (type) { case 'new': type = 'add'; break; case 'deleted': type = 'delete'; break; case 'updated': type = 'update'; break; } observeOps[type].call(arr[a], patches, getPath(root, arr[a].object)); } a++; } if (patches) { if (callback) { callback(patches); } } observer.patches = patches; patches = []; }; } else { observer = {}; mirror.value = JSON.parse(JSON.stringify(obj)); if (callback) { //callbacks.push(callback); this has no purpose observer.callback = callback; observer.next = null; var intervals = this.intervals || [100, 1000, 10000, 60000]; var currentInterval = 0; var dirtyCheck = function () { generate(observer); }; var fastCheck = function () { clearTimeout(observer.next); observer.next = setTimeout(function () { dirtyCheck(); currentInterval = 0; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }, 0); }; var slowCheck = function () { dirtyCheck(); if (currentInterval == intervals.length) currentInterval = intervals.length - 1; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }; if (typeof window !== 'undefined') { if (window.addEventListener) { window.addEventListener('mousedown', fastCheck); window.addEventListener('mouseup', fastCheck); window.addEventListener('keydown', fastCheck); } else { window.attachEvent('onmousedown', fastCheck); window.attachEvent('onmouseup', fastCheck); window.attachEvent('onkeydown', fastCheck); } } observer.next = setTimeout(slowCheck, intervals[currentInterval++]); } } observer.patches = patches; observer.object = obj; mirror.observers.push(new ObserverInfo(callback, observer)); return _observe(observer, obj); } jsonpatch.observe = observe; /// Listen to changes on an object tree, accumulate patches function _observe(observer, obj) { if (Object.observe) { Object.observe(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _observe(observer, v); } } } } return observer; } function _unobserve(observer, obj) { if (Object.observe) { Object.unobserve(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _unobserve(observer, v); } } } } return observer; } function generate(observer) { if (Object.observe) { Object.deliverChangeRecords(observer); } else { var mirror; for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === observer.object) { mirror = beforeDict[i]; break; } } _generate(mirror.value, observer.object, observer.patches, ""); } var temp = observer.patches; if (temp.length > 0) { observer.patches = []; if (observer.callback) { observer.callback(temp); } } return temp; } jsonpatch.generate = generate; var _objectKeys; if (Object.keys) { _objectKeys = Object.keys; } else { _objectKeys = function (obj) { var keys = []; for (var o in obj) { if (obj.hasOwnProperty(o)) { keys.push(o); } } return keys; }; } // Dirty check if obj is different from mirror, generate patches and update mirror function _generate(mirror, obj, patches, path) { var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var changed = false; var deleted = false; for (var t = oldKeys.length - 1; t >= 0; t--) { var key = oldKeys[t]; var oldVal = mirror[key]; if (obj.hasOwnProperty(key)) { var newVal = obj[key]; if (oldVal instanceof Object) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key)); } else { if (oldVal != newVal) { changed = true; patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal }); mirror[key] = newVal; } } } else { patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); delete mirror[key]; deleted = true; } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t = 0; t < newKeys.length; t++) { var key = newKeys[t]; if (!mirror.hasOwnProperty(key)) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] }); mirror[key] = JSON.parse(JSON.stringify(obj[key])); } } } var _isArray; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (obj) { return obj.push && typeof obj.length === 'number'; }; } /// Apply a json-patch operation on an object tree function apply(tree, patches) { var result = false, p = 0, plen = patches.length, patch; while (p < plen) { patch = patches[p]; // Find the object var keys = patch.path.split('/'); var obj = tree; var t = 1; var len = keys.length; while (true) { if (_isArray(obj)) { var index = parseInt(keys[t], 10); t++; if (t >= len) { result = arrOps[patch.op].call(patch, obj, index, tree); break; } obj = obj[index]; } else { var key = keys[t]; if (key.indexOf('~') != -1) key = key.replace(/~1/g, '/').replace(/~0/g, '~'); t++; if (t >= len) { result = objOps[patch.op].call(patch, obj, key, tree); break; } obj = obj[key]; } } p++; } return result; } jsonpatch.apply = apply; })(jsonpatch || (jsonpatch = {})); if (typeof exports !== "undefined") { exports.apply = jsonpatch.apply; exports.observe = jsonpatch.observe; exports.unobserve = jsonpatch.unobserve; exports.generate = jsonpatch.generate; } Handsontable.PluginHookClass = (function () { var Hooks = function () { return { // Hooks beforeInitWalkontable: [], beforeInit: [], beforeRender: [], beforeChange: [], beforeRemoveCol: [], beforeRemoveRow: [], beforeValidate: [], beforeGet: [], beforeSet: [], beforeGetCellMeta: [], beforeAutofill: [], beforeKeyDown: [], beforeColumnSort: [], afterInit : [], afterLoadData : [], afterUpdateSettings: [], afterRender : [], afterRenderer : [], afterChange : [], afterValidate: [], afterGetCellMeta: [], afterGetColHeader: [], afterGetColWidth: [], afterDestroy: [], afterRemoveRow: [], afterCreateRow: [], afterRemoveCol: [], afterCreateCol: [], afterColumnResize: [], afterColumnMove: [], afterColumnSort: [], afterDeselect: [], afterSelection: [], afterSelectionByProp: [], afterSelectionEnd: [], afterSelectionEndByProp: [], afterCopyLimit: [], afterOnCellMouseDown: [], afterOnCellMouseOver: [], afterOnCellCornerMouseDown: [], afterScrollVertically: [], afterScrollHorizontally: [], // Modifiers modifyCol: [] } }; var legacy = { onBeforeChange: "beforeChange", onChange: "afterChange", onCreateRow: "afterCreateRow", onCreateCol: "afterCreateCol", onSelection: "afterSelection", onCopyLimit: "afterCopyLimit", onSelectionEnd: "afterSelectionEnd", onSelectionByProp: "afterSelectionByProp", onSelectionEndByProp: "afterSelectionEndByProp" }; function PluginHookClass() { this.hooks = Hooks(); this.legacy = legacy; } PluginHookClass.prototype.add = function (key, fn) { //if fn is array, run this for all the array items if (Handsontable.helper.isArray(fn)) { for (var i = 0, len = fn.length; i < len; i++) { this.add(key, fn[i]); } } else { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] === "undefined") { this.hooks[key] = []; } if (this.hooks[key].indexOf(fn) == -1) { this.hooks[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored) } } return this; }; PluginHookClass.prototype.once = function(key, fn){ if(Handsontable.helper.isArray(fn)){ for(var i = 0, len = fn.length; i < len; i++){ fn[i].runOnce = true; this.add(key, fn[i]); } } else { fn.runOnce = true; this.add(key, fn); } }; PluginHookClass.prototype.remove = function (key, fn) { var status = false; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] !== 'undefined') { for (var i = 0, leni = this.hooks[key].length; i < leni; i++) { if (this.hooks[key][i] == fn) { delete this.hooks[key][i].runOnce; this.hooks[key].splice(i, 1); status = true; break; } } } return status; }; PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { //Make a copy of handler array var handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { handlers[i].call(instance, p1, p2, p3, p4, p5); if(handlers[i].runOnce){ this.remove(key, handlers[i]); } } } }; PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) { var res, handlers; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { res = handlers[i].call(instance, p1, p2, p3, p4, p5); if (res !== void 0) { p1 = res; } if(handlers[i].runOnce){ this.remove(key, handlers[i]); } if(res === false){ //if any handler returned false return false; //event has been cancelled and further execution of handler queue is being aborted } } } return p1; }; return PluginHookClass; })(); Handsontable.PluginHooks = new Handsontable.PluginHookClass(); (function (Handsontable) { function HandsontableAutoColumnSize() { var plugin = this , sampleCount = 5; //number of samples to take of each value length this.beforeInit = function () { var instance = this; instance.autoColumnWidths = []; if (instance.getSettings().autoColumnSize !== false) { if (!instance.autoColumnSizeTmp) { instance.autoColumnSizeTmp = { table: null, tableStyle: null, theadTh: null, tbody: null, container: null, containerStyle: null, determineBeforeNextRender: true }; instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.addHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy); instance.determineColumnWidth = plugin.determineColumnWidth; } } else { if (instance.autoColumnSizeTmp) { instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.removeHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy); delete instance.determineColumnWidth; plugin.afterDestroy.call(instance); } } }; this.determineIfChanged = function (force) { if (force) { htAutoColumnSize.determineColumnsWidth.apply(this, arguments); } }; this.determineColumnWidth = function (col) { var instance = this , tmp = instance.autoColumnSizeTmp; if (!tmp.container) { createTmpContainer.call(tmp, instance); } tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize'; tmp.table.className = instance.$table[0].className; var rows = instance.countRows(); var samples = {}; var maxLen = 0; for (var r = 0; r < rows; r++) { var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col)); var len = value.length; if (len > maxLen) { maxLen = len; } if (!samples[len]) { samples[len] = { needed: sampleCount, strings: [] }; } if (samples[len].needed) { samples[len].strings.push({value: value, row: r}); samples[len].needed--; } } var settings = instance.getSettings(); if (settings.colHeaders) { instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML } instance.view.wt.wtDom.empty(tmp.tbody); for (var i in samples) { if (samples.hasOwnProperty(i)) { for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) { var row = samples[i].strings[j].row; var cellProperties = instance.getCellMeta(row, col); cellProperties.col = col; cellProperties.row = row; var renderer = instance.getCellRenderer(cellProperties); var tr = document.createElement('tr'); var td = document.createElement('td'); renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties); r++; tr.appendChild(td); tmp.tbody.appendChild(tr); } } } var parent = instance.rootElement[0].parentNode; parent.appendChild(tmp.container); var width = instance.view.wt.wtDom.outerWidth(tmp.table); parent.removeChild(tmp.container); if (!settings.nativeScrollbars) { //with native scrollbars a cell size can safely exceed the width of the viewport var maxWidth = instance.view.wt.wtViewport.getViewportWidth() - 2; //2 is some overhead for cell border if (width > maxWidth) { width = maxWidth; } } return width; }; this.determineColumnsWidth = function () { var instance = this; var settings = this.getSettings(); if (settings.autoColumnSize || !settings.colWidths) { var cols = this.countCols(); for (var c = 0; c < cols; c++) { if (!instance._getColWidthFromSettings(c)) { this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c); } } } }; this.getColWidth = function (col, response) { if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) { response.width = this.autoColumnWidths[col]; } }; this.afterDestroy = function () { var instance = this; if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) { instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container); } instance.autoColumnSizeTmp = null; }; function createTmpContainer(instance) { var d = document , tmp = this; tmp.table = d.createElement('table'); tmp.theadTh = d.createElement('th'); tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh); tmp.tableStyle = tmp.table.style; tmp.tableStyle.tableLayout = 'auto'; tmp.tableStyle.width = 'auto'; tmp.tbody = d.createElement('tbody'); tmp.table.appendChild(tmp.tbody); tmp.container = d.createElement('div'); tmp.container.className = instance.rootElement[0].className + ' hidden'; tmp.containerStyle = tmp.container.style; tmp.container.appendChild(tmp.table); } } var htAutoColumnSize = new HandsontableAutoColumnSize(); Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit); Handsontable.PluginHooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit); })(Handsontable); /** * This plugin sorts the view by a column (but does not sort the data source!) * @constructor */ function HandsontableColumnSorting() { var plugin = this; this.init = function (source) { var instance = this; var sortingSettings = instance.getSettings().columnSorting; var sortingColumn, sortingOrder; instance.sortingEnabled = !!(sortingSettings); if (instance.sortingEnabled) { instance.sortIndex = []; var loadedSortingState = loadSortingState.call(instance); if (typeof loadedSortingState != 'undefined') { sortingColumn = loadedSortingState.sortColumn; sortingOrder = loadedSortingState.sortOrder; } else { sortingColumn = sortingSettings.column; sortingOrder = sortingSettings.sortOrder; } plugin.sortByColumn.call(instance, sortingColumn, sortingOrder); instance.sort = function(){ var args = Array.prototype.slice.call(arguments); return plugin.sortByColumn.apply(instance, args) }; if (typeof instance.getSettings().observeChanges == 'undefined'){ enableObserveChangesPlugin.call(instance); } if (source == 'afterInit') { bindColumnSortingAfterClick.call(instance); instance.addHook('afterCreateRow', plugin.afterCreateRow); instance.addHook('afterRemoveRow', plugin.afterRemoveRow); instance.addHook('afterLoadData', plugin.init); } } else { delete instance.sort; instance.removeHook('afterCreateRow', plugin.afterCreateRow); instance.removeHook('afterRemoveRow', plugin.afterRemoveRow); instance.removeHook('afterLoadData', plugin.init); } }; this.setSortingColumn = function (col, order) { var instance = this; if (typeof col == 'undefined') { delete instance.sortColumn; delete instance.sortOrder; return; } else if (instance.sortColumn === col && typeof order == 'undefined') { instance.sortOrder = !instance.sortOrder; } else { instance.sortOrder = typeof order != 'undefined' ? order : true; } instance.sortColumn = col; }; this.sortByColumn = function (col, order) { var instance = this; plugin.setSortingColumn.call(instance, col, order); if(typeof instance.sortColumn == 'undefined'){ return; } instance.PluginHooks.run('beforeColumnSort', instance.sortColumn, instance.sortOrder); plugin.sort.call(instance); instance.render(); saveSortingState.call(instance); instance.PluginHooks.run('afterColumnSort', instance.sortColumn, instance.sortOrder); }; var saveSortingState = function () { var instance = this; var sortingState = {}; if (typeof instance.sortColumn != 'undefined') { sortingState.sortColumn = instance.sortColumn; } if (typeof instance.sortOrder != 'undefined') { sortingState.sortOrder = instance.sortOrder; } if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) { instance.PluginHooks.run('persistentStateSave', 'columnSorting', sortingState); } }; var loadSortingState = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'columnSorting', storedState); return storedState.value; }; var bindColumnSortingAfterClick = function () { var instance = this; instance.rootElement.on('click.handsontable', '.columnSorting', function (e) { if (instance.view.wt.wtDom.hasClass(e.target, 'columnSorting')) { var col = getColumn(e.target); plugin.sortByColumn.call(instance, col); } }); function countRowHeaders() { var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th'); return THs.length; } function getColumn(target) { var TH = instance.view.wt.wtDom.closest(target, 'TH'); return instance.view.wt.wtDom.index(TH) - countRowHeaders(); } }; function enableObserveChangesPlugin () { var instance = this; instance.registerTimeout('enableObserveChanges', function(){ instance.updateSettings({ observeChanges: true }); }, 0); } function defaultSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } if (a[1] < b[1]) return sortOrder ? -1 : 1; if (a[1] > b[1]) return sortOrder ? 1 : -1; return 0; } } function dateSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } var aDate = new Date(a[1]); var bDate = new Date(b[1]); if (aDate < bDate) return sortOrder ? -1 : 1; if (aDate > bDate) return sortOrder ? 1 : -1; return 0; } } this.sort = function () { var instance = this; if (typeof instance.sortOrder == 'undefined') { return; } instance.sortingEnabled = false; //this is required by translateRow plugin hook instance.sortIndex.length = 0; var colOffset = this.colOffset(); for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) { this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } var colMeta = instance.getCellMeta(0, instance.sortColumn); var sortFunction; switch (colMeta.type) { case 'date': sortFunction = dateSort; break; default: sortFunction = defaultSort; } this.sortIndex.sort(sortFunction(instance.sortOrder)); //Append spareRows for(var i = this.sortIndex.length; i < instance.countRows(); i++){ this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } instance.sortingEnabled = true; //this is required by translateRow plugin hook }; this.translateRow = function (row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) { return instance.sortIndex[row][0]; } return row; }; this.onBeforeGetSet = function (getVars) { var instance = this; getVars.row = plugin.translateRow.call(instance, getVars.row); }; this.untranslateRow = function (row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) { for (var i = 0; i < instance.sortIndex.length; i++) { if (instance.sortIndex[i][0] == row) { return i; } } } }; this.getColHeader = function (col, TH) { if (this.getSettings().columnSorting) { this.view.wt.wtDom.addClass(TH.querySelector('.colHeader'), 'columnSorting'); } }; function isSorted(instance){ return typeof instance.sortColumn != 'undefined'; } this.afterCreateRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] >= index){ instance.sortIndex[i][0] += amount; } } for(var i=0; i < amount; i++){ instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]); } saveSortingState.call(instance); }; this.afterRemoveRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } var physicalRemovedIndex = plugin.translateRow.call(instance, index); instance.sortIndex.splice(index, amount); for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] > physicalRemovedIndex){ instance.sortIndex[i][0] -= amount; } } saveSortingState.call(instance); }; this.afterChangeSort = function (changes/*, source*/) { var instance = this; var sortColumnChanged = false; var selection = {}; if (!changes) { return; } for (var i = 0; i < changes.length; i++) { if (changes[i][1] == instance.sortColumn) { sortColumnChanged = true; selection.row = plugin.translateRow.call(instance, changes[i][0]); selection.col = changes[i][1]; break; } } if (sortColumnChanged) { setTimeout(function () { plugin.sort.call(instance); instance.render(); instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col); }, 0); } }; } var htSortColumn = new HandsontableColumnSorting(); Handsontable.PluginHooks.add('afterInit', function () { htSortColumn.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htSortColumn.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('beforeGet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('beforeSet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader); (function (Handsontable) { 'use strict'; function ContextMenu(instance, customOptions){ this.instance = instance; var contextMenu = this; this.menu = createMenu(); this.enabled = true; this.bindMouseEvents(); this.bindTableEvents(); this.instance.addHook('afterDestroy', function () { contextMenu.destroy(); }); this.defaultOptions = { items: { 'row_above': { name: 'Insert row above', callback: function(key, selection){ this.alter("insert_row", selection.start.row()); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, 'row_below': { name: 'Insert row below', callback: function(key, selection){ this.alter("insert_row", selection.end.row() + 1); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, "hsep1": ContextMenu.SEPARATOR, 'col_left': { name: 'Insert column on the left', callback: function(key, selection){ this.alter("insert_col", selection.start.col()); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, 'col_right': { name: 'Insert column on the right', callback: function(key, selection){ this.alter("insert_col", selection.end.col() + 1); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, "hsep2": ContextMenu.SEPARATOR, 'remove_row': { name: 'Remove row', callback: function(key, selection){ var amount = selection.end.row() - selection.start.row() + 1; this.alter("remove_row", selection.start.row(), amount); } }, 'remove_col': { name: 'Remove column', callback: function(key, selection){ var amount = selection.end.col() - selection.start.col() + 1; this.alter("remove_col", selection.start.col(), amount); } }, "hsep3": ContextMenu.SEPARATOR, 'undo': { name: 'Undo', callback: function(){ this.undo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isUndoAvailable(); } }, 'redo': { name: 'Redo', callback: function(){ this.redo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isRedoAvailable(); } } } }; this.options = {}; Handsontable.helper.extend(this.options, this.defaultOptions); this.updateOptions(customOptions); function createMenu(){ var menu = $('body > .htContextMenu')[0]; if(!menu){ menu = document.createElement('DIV'); Handsontable.Dom.addClass(menu, 'htContextMenu'); document.getElementsByTagName('body')[0].appendChild(menu); } return menu; } } ContextMenu.prototype.bindMouseEvents = function (){ function contextMenuOpenListener(event){ event.preventDefault(); if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){ return; } this.show(event.pageY, event.pageX); $(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this)); } this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this)); }; ContextMenu.prototype.bindTableEvents = function () { var that = this; this._afterScrollCallback = function () { that.close(); }; this.instance.addHook('afterScrollVertically', this._afterScrollCallback); this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback); }; ContextMenu.prototype.unbindTableEvents = function () { var that = this; if(this._afterScrollCallback){ this.instance.removeHook('afterScrollVertically', this._afterScrollCallback); this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback); this._afterScrollCallback = null; } }; ContextMenu.prototype.performAction = function (){ var hot = $(this.menu).handsontable('getInstance'); var selectedItemIndex = hot.getSelected()[0]; var selectedItem = hot.getData()[selectedItemIndex]; if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){ return; } if(typeof selectedItem.callback != 'function'){ return; } var corners = this.instance.getSelected(); var normalizedSelection = ContextMenu.utils.normalizeSelection(corners); selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection); }; ContextMenu.prototype.unbindMouseEvents = function () { this.instance.rootElement.off('contextmenu.htContextMenu'); $(document).off('mousedown.htContextMenu'); }; ContextMenu.prototype.show = function(top, left){ this.menu.style.display = 'block'; $(this.menu) .off('mousedown.htContextMenu') .on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this)); $(this.menu).handsontable({ data: ContextMenu.utils.convertItemsToArray(this.getItems()), colHeaders: false, colWidths: [160], readOnly: true, copyPaste: false, columns: [ { data: 'name', renderer: Handsontable.helper.proxy(this.renderer, this) } ], beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this) }); this.bindTableEvents(); this.setMenuPosition(top, left); $(this.menu).handsontable('listen'); }; ContextMenu.prototype.close = function () { this.hide(); $(document).off('mousedown.htContextMenu'); this.unbindTableEvents(); this.instance.listen(); }; ContextMenu.prototype.hide = function(){ this.menu.style.display = 'none'; $(this.menu).handsontable('destroy'); }; ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){ var contextMenu = this; var item = instance.getData()[row]; var wrapper = document.createElement('DIV'); Handsontable.Dom.empty(TD); TD.appendChild(wrapper); if(itemIsSeparator(item)){ Handsontable.Dom.addClass(TD, 'htSeparator'); } else { Handsontable.Dom.fastInnerText(wrapper, value); } if (itemIsDisabled(item, contextMenu.instance)){ Handsontable.Dom.addClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.deselectCell(); }); } else { Handsontable.Dom.removeClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.selectCell(row, col); }); } function itemIsSeparator(item){ return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name); } function itemIsDisabled(item, instance){ return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true); } }; ContextMenu.prototype.onBeforeKeyDown = function (event) { var contextMenu = this; var instance = $(contextMenu.menu).handsontable('getInstance'); var selection = instance.getSelected(); switch(event.keyCode){ case Handsontable.helper.keyCode.ESCAPE: contextMenu.close(); event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ENTER: if(instance.getSelected()){ contextMenu.performAction(); contextMenu.close(); } break; case Handsontable.helper.keyCode.ARROW_DOWN: if(!selection){ selectFirstCell(instance); } else { selectNextCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ARROW_UP: if(!selection){ selectLastCell(instance); } else { selectPrevCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; } function selectFirstCell(instance) { var firstCell = instance.getCell(0, 0); if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){ selectNextCell(0, 0, instance); } else { instance.selectCell(0, 0); } } function selectLastCell(instance) { var lastRow = instance.countRows() - 1; var lastCell = instance.getCell(lastRow, 0); if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){ selectPrevCell(lastRow, 0, instance); } else { instance.selectCell(lastRow, 0); } } function selectNextCell(row, col, instance){ var nextRow = row + 1; var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null; if(!nextCell){ return; } if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){ selectNextCell(nextRow, col, instance); } else { instance.selectCell(nextRow, col); } } function selectPrevCell(row, col, instance) { var prevRow = row - 1; var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null; if (!prevCell) { return; } if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){ selectPrevCell(prevRow, col, instance); } else { instance.selectCell(prevRow, col); } } }; ContextMenu.prototype.getItems = function () { var items = {}; function Item(rawItem){ if(typeof rawItem == 'string'){ this.name = rawItem; } else { Handsontable.helper.extend(this, rawItem); } } Item.prototype = this.options; for(var itemName in this.options.items){ if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){ items[itemName] = new Item(this.options.items[itemName]); } } return items; }; ContextMenu.prototype.updateOptions = function(newOptions){ newOptions = newOptions || {}; if(newOptions.items){ for(var itemName in newOptions.items){ var item = {}; if(newOptions.items.hasOwnProperty(itemName)) { if(this.defaultOptions.items.hasOwnProperty(itemName) && Handsontable.helper.isObject(newOptions.items[itemName])){ Handsontable.helper.extend(item, this.defaultOptions.items[itemName]); Handsontable.helper.extend(item, newOptions.items[itemName]); newOptions.items[itemName] = item; } } } } Handsontable.helper.extend(this.options, newOptions); }; ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) { var cursor = { top: cursorY, topRelative: cursorY - document.documentElement.scrollTop, left: cursorX, leftRelative:cursorX - document.documentElement.scrollLeft }; if(this.menuFitsBelowCursor(cursor)){ this.positionMenuBelowCursor(cursor); } else { this.positionMenuAboveCursor(cursor); } if(this.menuFitsOnRightOfCursor(cursor)){ this.positionMenuOnRightOfCursor(cursor); } else { this.positionMenuOnLeftOfCursor(cursor); } }; ContextMenu.prototype.menuFitsBelowCursor = function (cursor) { return cursor.topRelative + this.menu.offsetHeight <= document.documentElement.scrollTop + document.documentElement.clientHeight; }; ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) { return cursor.leftRelative + this.menu.offsetWidth <= document.documentElement.scrollLeft + document.documentElement.clientWidth; }; ContextMenu.prototype.positionMenuBelowCursor = function (cursor) { this.menu.style.top = cursor.top + 'px'; }; ContextMenu.prototype.positionMenuAboveCursor = function (cursor) { this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px'; }; ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) { this.menu.style.left = cursor.left + 'px'; }; ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) { this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px'; }; ContextMenu.utils = {}; ContextMenu.utils.convertItemsToArray = function (items) { var itemArray = []; var item; for(var itemName in items){ if(items.hasOwnProperty(itemName)){ if(typeof items[itemName] == 'string'){ item = {name: items[itemName]}; } else if (items[itemName].visible !== false) { item = items[itemName]; } else { continue; } item.key = itemName; itemArray.push(item); } } return itemArray; }; ContextMenu.utils.normalizeSelection = function(corners){ var selection = { start: new Handsontable.SelectionPoint(), end: new Handsontable.SelectionPoint() }; selection.start.row(Math.min(corners[0], corners[2])); selection.start.col(Math.min(corners[1], corners[3])); selection.end.row(Math.max(corners[0], corners[2])); selection.end.col(Math.max(corners[1], corners[3])); return selection; }; ContextMenu.utils.isSeparator = function (cell) { return Handsontable.Dom.hasClass(cell, 'htSeparator'); }; ContextMenu.utils.isDisabled = function (cell) { return Handsontable.Dom.hasClass(cell, 'htDisabled'); }; ContextMenu.prototype.enable = function () { if(!this.enabled){ this.enabled = true; this.bindMouseEvents(); } }; ContextMenu.prototype.disable = function () { if(this.enabled){ this.enabled = false; this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); } }; ContextMenu.prototype.destroy = function () { this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); if(!this.isMenuEnabledByOtherHotInstance()){ this.removeMenu(); } }; ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () { var hotContainers = $('.handsontable'); var menuEnabled = false; for(var i = 0, len = hotContainers.length; i < len; i++){ var instance = $(hotContainers[i]).handsontable('getInstance'); if(instance && instance.getSettings().contextMenu){ menuEnabled = true; break; } } return menuEnabled; }; ContextMenu.prototype.removeMenu = function () { if(this.menu.parentNode){ this.menu.parentNode.removeChild(this.menu); } } ContextMenu.prototype.filterItems = function(itemsToLeave){ this.itemsFilter = itemsToLeave; }; ContextMenu.SEPARATOR = "---------"; function init(){ var instance = this; var contextMenuSetting = instance.getSettings().contextMenu; var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {}; if(contextMenuSetting){ if(!instance.contextMenu){ instance.contextMenu = new ContextMenu(instance, customOptions); } instance.contextMenu.enable(); if(Handsontable.helper.isArray(contextMenuSetting)){ instance.contextMenu.filterItems(contextMenuSetting); } } else if(instance.contextMenu){ instance.contextMenu.destroy(); delete instance.contextMenu; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); Handsontable.ContextMenu = ContextMenu; })(Handsontable); /** * This plugin adds support for legacy features, deprecated APIs, etc. */ /** * Support for old autocomplete syntax * For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete */ Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) { //isWritable - deprecated since 0.8.0 cellProperties.isWritable = !cellProperties.readOnly; //autocomplete - deprecated since 0.7.1 (see CHANGELOG.md) if (cellProperties.autoComplete) { throw new Error("Support for legacy autocomplete syntax was removed in Handsontable 0.10.0. Please remove the property named 'autoComplete' from your config. For replacement instructions, see wiki page https://github.com/warpech/jquery-handsontable/wiki/Migration-guide-to-0.10.x"); } }); function HandsontableManualColumnMove() { var pressed , startCol , endCol , startX , startOffset; var ghost = document.createElement('DIV') , ghostStyle = ghost.style; ghost.className = 'ghost'; ghostStyle.position = 'absolute'; ghostStyle.top = '25px'; ghostStyle.left = 0; ghostStyle.width = '10px'; ghostStyle.height = '10px'; ghostStyle.backgroundColor = '#CCC'; ghostStyle.opacity = 0.7; var saveManualColumnPositions = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions); }; var loadManualColumnPositions = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnPositions', storedState); return storedState.value; }; var bindMoveColEvents = function () { var instance = this; instance.rootElement.on('mousemove.manualColumnMove', function (e) { if (pressed) { ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px'; if (ghostStyle.display === 'none') { ghostStyle.display = 'block'; } } }); instance.rootElement.on('mouseup.manualColumnMove', function () { if (pressed) { if (startCol < endCol) { endCol--; } if (instance.getSettings().rowHeaders) { startCol--; endCol--; } instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]); $('.manualColumnMover.active').removeClass('active'); pressed = false; instance.forceFullRender = true; instance.view.render(); //updates all ghostStyle.display = 'none'; saveManualColumnPositions.call(instance); instance.PluginHooks.run('afterColumnMove', startCol, endCol); } }); instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) { var mover = e.currentTarget; var TH = instance.view.wt.wtDom.closest(mover, 'TH'); startCol = instance.view.wt.wtDom.index(TH) + instance.colOffset(); endCol = startCol; pressed = true; startX = e.pageX; var TABLE = instance.$table[0]; TABLE.parentNode.appendChild(ghost); ghostStyle.width = instance.view.wt.wtDom.outerWidth(TH) + 'px'; ghostStyle.height = instance.view.wt.wtDom.outerHeight(TABLE) + 'px'; startOffset = parseInt(instance.view.wt.wtDom.offset(TH).left - instance.view.wt.wtDom.offset(TABLE).left, 10); ghostStyle.left = startOffset + 6 + 'px'; }); instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () { if (pressed) { var active = instance.view.THEAD.querySelector('.manualColumnMover.active'); if (active) { instance.view.wt.wtDom.removeClass(active, 'active'); } endCol = instance.view.wt.wtDom.index(this) + instance.colOffset(); var THs = instance.view.THEAD.querySelectorAll('th'); var mover = THs[endCol].querySelector('.manualColumnMover'); instance.view.wt.wtDom.addClass(mover, 'active'); } }); instance.addHook('afterDestroy', unbindMoveColEvents); }; var unbindMoveColEvents = function(){ var instance = this; instance.rootElement.off('mouseup.manualColumnMove'); instance.rootElement.off('mousemove.manualColumnMove'); instance.rootElement.off('mousedown.manualColumnMove'); instance.rootElement.off('mouseenter.manualColumnMove'); }; this.beforeInit = function () { this.manualColumnPositions = []; }; this.init = function (source) { var instance = this; var manualColMoveEnabled = !!(this.getSettings().manualColumnMove); if (manualColMoveEnabled) { var initialManualColumnPositions = this.getSettings().manualColumnMove; var loadedManualColumnPositions = loadManualColumnPositions.call(instance); if (typeof loadedManualColumnPositions != 'undefined') { this.manualColumnPositions = loadedManualColumnPositions; } else if (initialManualColumnPositions instanceof Array) { this.manualColumnPositions = initialManualColumnPositions; } else { this.manualColumnPositions = []; } instance.forceFullRender = true; if (source == 'afterInit') { bindMoveColEvents.call(this); if (this.manualColumnPositions.length > 0) { this.forceFullRender = true; this.render(); } } } else { unbindMoveColEvents.call(this); this.manualColumnPositions = []; } }; this.modifyCol = function (col) { //TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2 if (this.getSettings().manualColumnMove) { if (typeof this.manualColumnPositions[col] === 'undefined') { this.manualColumnPositions[col] = col; } return this.manualColumnPositions[col]; } return col; }; this.getColHeader = function (col, TH) { if (this.getSettings().manualColumnMove) { var DIV = document.createElement('DIV'); DIV.className = 'manualColumnMover'; TH.firstChild.appendChild(DIV); } }; } var htManualColumnMove = new HandsontableManualColumnMove(); Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnMove.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnMove.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader); Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol); function HandsontableManualColumnResize() { var pressed , currentTH , currentCol , currentWidth , instance , newSize , startX , startWidth , startOffset , resizer = document.createElement('DIV') , handle = document.createElement('DIV') , line = document.createElement('DIV') , lineStyle = line.style; resizer.className = 'manualColumnResizer'; handle.className = 'manualColumnResizerHandle'; resizer.appendChild(handle); line.className = 'manualColumnResizerLine'; resizer.appendChild(line); var $document = $(document); $document.mousemove(function (e) { if (pressed) { currentWidth = startWidth + (e.pageX - startX); newSize = setManualSize(currentCol, currentWidth); //save col width resizer.style.left = startOffset + currentWidth + 'px'; } }); $document.mouseup(function () { if (pressed) { instance.view.wt.wtDom.removeClass(resizer, 'active'); pressed = false; if(newSize != startWidth){ instance.forceFullRender = true; instance.view.render(); //updates all saveManualColumnWidths.call(instance); instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } refreshResizerPosition.call(instance, currentTH); } }); var saveManualColumnWidths = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths); }; var loadManualColumnWidths = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnWidths', storedState); return storedState.value; }; function refreshResizerPosition(TH) { instance = this; currentTH = TH; var col = this.view.wt.wtTable.getCoords(TH)[1]; //getCoords returns array [row, col] if (col >= 0) { //if not row header currentCol = col; var rootOffset = this.view.wt.wtDom.offset(this.rootElement[0]).left; var thOffset = this.view.wt.wtDom.offset(TH).left; startOffset = (thOffset - rootOffset) - 6; resizer.style.left = startOffset + parseInt(this.view.wt.wtDom.outerWidth(TH), 10) + 'px'; this.rootElement[0].appendChild(resizer); } } function refreshLinePosition() { var instance = this; startWidth = parseInt(this.view.wt.wtDom.outerWidth(currentTH), 10); instance.view.wt.wtDom.addClass(resizer, 'active'); lineStyle.height = instance.view.wt.wtDom.outerHeight(instance.$table[0]) + 'px'; pressed = instance; } var bindManualColumnWidthEvents = function () { var instance = this; var dblclick = 0; var autoresizeTimeout = null; this.rootElement.on('mouseenter.handsontable', 'th', function (e) { if (!pressed) { refreshResizerPosition.call(instance, e.currentTarget); } }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () { if (autoresizeTimeout == null) { autoresizeTimeout = setTimeout(function () { if (dblclick >= 2) { newSize = instance.determineColumnWidth.call(instance, currentCol); setManualSize(currentCol, newSize); instance.forceFullRender = true; instance.view.render(); //updates all instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } dblclick = 0; autoresizeTimeout = null; }, 500); } dblclick++; }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) { startX = e.pageX; refreshLinePosition.call(instance); newSize = startWidth; }); }; this.beforeInit = function () { this.manualColumnWidths = []; }; this.init = function (source) { var instance = this; var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize); if (manualColumnWidthEnabled) { var initialColumnWidths = this.getSettings().manualColumnResize; var loadedManualColumnWidths = loadManualColumnWidths.call(instance); if (typeof loadedManualColumnWidths != 'undefined') { this.manualColumnWidths = loadedManualColumnWidths; } else if (initialColumnWidths instanceof Array) { this.manualColumnWidths = initialColumnWidths; } else { this.manualColumnWidths = []; } if (source == 'afterInit') { bindManualColumnWidthEvents.call(this); instance.forceFullRender = true; instance.render(); } } }; var setManualSize = function (col, width) { width = Math.max(width, 20); /** * We need to run col through modifyCol hook, in case the order of displayed columns is different than the order * in data source. For instance, this order can be modified by manualColumnMove plugin. */ col = instance.PluginHooks.execute('modifyCol', col); instance.manualColumnWidths[col] = width; return width; }; this.getColWidth = function (col, response) { if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) { response.width = this.manualColumnWidths[col]; } }; } var htManualColumnResize = new HandsontableManualColumnResize(); Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnResize.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnResize.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth); (function HandsontableObserveChanges() { Handsontable.PluginHooks.add('afterLoadData', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); function init() { var instance = this; var pluginEnabled = instance.getSettings().observeChanges; if (pluginEnabled) { if(instance.observer) { destroy.call(instance); //destroy observer for old data object } createObserver.call(instance); bindEvents.call(instance); } else if (!pluginEnabled){ destroy.call(instance); } } function createObserver(){ var instance = this; instance.observeChangesActive = true; instance.pauseObservingChanges = function(){ instance.observeChangesActive = false; }; instance.resumeObservingChanges = function(){ instance.observeChangesActive = true; }; instance.observedData = instance.getData(); instance.observer = jsonpatch.observe(instance.observedData, function (patches) { if(instance.observeChangesActive){ runHookForOperation.call(instance, patches); instance.render(); } instance.runHooks('afterChangesObserved'); }); } function runHookForOperation(rawPatches){ var instance = this; var patches = cleanPatches(rawPatches); for(var i = 0, len = patches.length; i < len; i++){ var patch = patches[i]; var parsedPath = parsePath(patch.path); switch(patch.op){ case 'add': if(isNaN(parsedPath.col)){ instance.runHooks('afterCreateRow', parsedPath.row); } else { instance.runHooks('afterCreateCol', parsedPath.col); } break; case 'remove': if(isNaN(parsedPath.col)){ instance.runHooks('afterRemoveRow', parsedPath.row, 1); } else { instance.runHooks('afterRemoveCol', parsedPath.col, 1); } break; case 'replace': instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external'); break; } } function cleanPatches(rawPatches){ var patches; patches = removeLengthRelatedPatches(rawPatches); patches = removeMultipleAddOrRemoveColPatches(patches); return patches; } /** * Removing or adding column will produce one patch for each table row. * This function leaves only one patch for each column add/remove operation */ function removeMultipleAddOrRemoveColPatches(rawPatches){ var newOrRemovedColumns = []; return rawPatches.filter(function(patch){ var parsedPath = parsePath(patch.path); if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){ if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){ return false; } else { newOrRemovedColumns.push(parsedPath.col); } } return true; }); } /** * If observeChanges uses native Object.observe method, then it produces patches for length property. * This function removes them. */ function removeLengthRelatedPatches(rawPatches){ return rawPatches.filter(function(patch){ return !/[/]length/ig.test(patch.path); }) } function parsePath(path){ var match = path.match(/^\/(\d+)\/?(.*)?$/); return { row: parseInt(match[1], 10), col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2] } } } function destroy(){ var instance = this; if (instance.observer){ destroyObserver.call(instance); unbindEvents.call(instance); } } function destroyObserver(){ var instance = this; jsonpatch.unobserve(instance.observedData, instance.observer); delete instance.observeChangesActive; delete instance.pauseObservingChanges; delete instance.resumeObservingChanges; } function bindEvents(){ var instance = this; instance.addHook('afterDestroy', destroy); instance.addHook('afterCreateRow', afterTableAlter); instance.addHook('afterRemoveRow', afterTableAlter); instance.addHook('afterCreateCol', afterTableAlter); instance.addHook('afterRemoveCol', afterTableAlter); instance.addHook('afterChange', function(changes, source){ if(source != 'loadData'){ afterTableAlter.call(this); } }); } function unbindEvents(){ var instance = this; instance.removeHook('afterDestroy', destroy); instance.removeHook('afterCreateRow', afterTableAlter); instance.removeHook('afterRemoveRow', afterTableAlter); instance.removeHook('afterCreateCol', afterTableAlter); instance.removeHook('afterRemoveCol', afterTableAlter); instance.removeHook('afterChange', afterTableAlter); } function afterTableAlter(){ var instance = this; instance.pauseObservingChanges(); instance.addHookOnce('afterChangesObserved', function(){ instance.resumeObservingChanges(); }); } })(); /* * * Plugin enables saving table state * * */ function Storage(prefix) { var savedKeys; var saveSavedKeys = function () { window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys); }; var loadSavedKeys = function () { var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys']; var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0; savedKeys = keys ? keys : []; }; var clearSavedKeys = function () { savedKeys = []; saveSavedKeys(); }; loadSavedKeys(); this.saveValue = function (key, value) { window.localStorage[prefix + '_' + key] = JSON.stringify(value); if (savedKeys.indexOf(key) == -1) { savedKeys.push(key); saveSavedKeys(); } }; this.loadValue = function (key, defaultValue) { key = typeof key != 'undefined' ? key : defaultValue; var value = window.localStorage[prefix + '_' + key]; return typeof value == "undefined" ? void 0 : JSON.parse(value); }; this.reset = function (key) { window.localStorage.removeItem(prefix + '_' + key); }; this.resetAll = function () { for (var index = 0; index < savedKeys.length; index++) { window.localStorage.removeItem(prefix + '_' + savedKeys[index]); } clearSavedKeys(); }; } (function (StorageClass) { function HandsontablePersistentState() { var plugin = this; this.init = function () { var instance = this, pluginSettings = instance.getSettings()['persistentState']; plugin.enabled = !!(pluginSettings); if (!plugin.enabled) { removeHooks.call(instance); return; } if (!instance.storage) { instance.storage = new StorageClass(instance.rootElement[0].id); } instance.resetState = plugin.resetValue; addHooks.call(instance); }; this.saveValue = function (key, value) { var instance = this; instance.storage.saveValue(key, value); }; this.loadValue = function (key, saveTo) { var instance = this; saveTo.value = instance.storage.loadValue(key); }; this.resetValue = function (key) { var instance = this; if (typeof key != 'undefined') { instance.storage.reset(key); } else { instance.storage.resetAll(); } }; var hooks = { 'persistentStateSave': plugin.saveValue, 'persistentStateLoad': plugin.loadValue, 'persistentStateReset': plugin.resetValue }; function addHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && !hookExists.call(instance, hookName)) { instance.PluginHooks.add(hookName, hooks[hookName]); } } } function removeHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && hookExists.call(instance, hookName)) { instance.PluginHooks.remove(hookName, hooks[hookName]); } } } function hookExists(hookName) { var instance = this; return instance.PluginHooks.hooks.hasOwnProperty(hookName); } } var htPersistentState = new HandsontablePersistentState(); Handsontable.PluginHooks.add('beforeInit', htPersistentState.init); Handsontable.PluginHooks.add('afterUpdateSettings', htPersistentState.init); })(Storage); /** * Handsontable UndoRedo class */ (function(Handsontable){ Handsontable.UndoRedo = function (instance) { var plugin = this; this.instance = instance; this.doneActions = []; this.undoneActions = []; this.ignoreNewActions = false; instance.addHook("afterChange", function (changes, origin) { if(changes){ var action = new Handsontable.UndoRedo.ChangeAction(changes); plugin.done(action); } }); instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateRowAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveRow", function (index, amount) { var originalData = plugin.instance.getData(); index = ( originalData.length + index ) % originalData.length; var removedData = originalData.slice(index, index + amount); var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData); plugin.done(action); }); instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) { if (createdAutomatically) { return; } var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveCol", function (index, amount) { var originalData = plugin.instance.getData(); index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols(); var removedData = []; for (var i = 0, len = originalData.length; i < len; i++) { removedData[i] = originalData[i].slice(index, index + amount); } var headers; if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ headers = instance.getSettings().colHeaders.slice(index, index + removedData.length); } var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers); plugin.done(action); }); }; Handsontable.UndoRedo.prototype.done = function (action) { if (!this.ignoreNewActions) { this.doneActions.push(action); this.undoneActions.length = 0; } }; /** * Undo operation from current revision */ Handsontable.UndoRedo.prototype.undo = function () { if (this.isUndoAvailable()) { var action = this.doneActions.pop(); this.ignoreNewActions = true; var that = this; action.undo(this.instance, function () { that.ignoreNewActions = false; that.undoneActions.push(action); }); } }; /** * Redo operation from current revision */ Handsontable.UndoRedo.prototype.redo = function () { if (this.isRedoAvailable()) { var action = this.undoneActions.pop(); this.ignoreNewActions = true; var that = this; action.redo(this.instance, function () { that.ignoreNewActions = false; that.doneActions.push(action); }); } }; /** * Returns true if undo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isUndoAvailable = function () { return this.doneActions.length > 0; }; /** * Returns true if redo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isRedoAvailable = function () { return this.undoneActions.length > 0; }; /** * Clears undo history */ Handsontable.UndoRedo.prototype.clear = function () { this.doneActions.length = 0; this.undoneActions.length = 0; }; Handsontable.UndoRedo.Action = function () { }; Handsontable.UndoRedo.Action.prototype.undo = function () { }; Handsontable.UndoRedo.Action.prototype.redo = function () { }; Handsontable.UndoRedo.ChangeAction = function (changes) { this.changes = changes; }; Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance, undoneCallback) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(3, 1); } instance.addHookOnce('afterChange', undoneCallback); instance.setDataAtRowProp(data, null, null, 'undo'); }; Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance, onFinishCallback) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(2, 1); } instance.addHookOnce('afterChange', onFinishCallback); instance.setDataAtRowProp(data, null, null, 'redo'); }; Handsontable.UndoRedo.CreateRowAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance, undoneCallback) { instance.addHookOnce('afterRemoveRow', undoneCallback); instance.alter('remove_row', this.index, this.amount); }; Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance, redoneCallback) { instance.addHookOnce('afterCreateRow', redoneCallback); instance.alter('insert_row', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveRowAction = function (index, data) { this.index = index; this.data = data; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance, undoneCallback) { var spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data); Array.prototype.splice.apply(instance.getData(), spliceArgs); instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance, redoneCallback) { instance.addHookOnce('afterRemoveRow', redoneCallback); instance.alter('remove_row', this.index, this.data.length); }; Handsontable.UndoRedo.CreateColumnAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance, undoneCallback) { instance.addHookOnce('afterRemoveCol', undoneCallback); instance.alter('remove_col', this.index, this.amount); }; Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance, redoneCallback) { instance.addHookOnce('afterCreateCol', redoneCallback); instance.alter('insert_col', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) { this.index = index; this.data = data; this.amount = this.data[0].length; this.headers = headers; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance, undoneCallback) { var row, spliceArgs; for (var i = 0, len = instance.getData().length; i < len; i++) { row = instance.getDataAtRow(i); spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data[i]); Array.prototype.splice.apply(row, spliceArgs); } if(typeof this.headers != 'undefined'){ spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.headers); Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs); } instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance, redoneCallback) { instance.addHookOnce('afterRemoveCol', redoneCallback); instance.alter('remove_col', this.index, this.amount); }; })(Handsontable); (function(Handsontable){ function init(){ var instance = this; var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo; if(pluginEnabled){ if(!instance.undoRedo){ instance.undoRedo = new Handsontable.UndoRedo(instance); exposeUndoRedoMethods(instance); instance.addHook('beforeKeyDown', onBeforeKeyDown); instance.addHook('afterChange', onAfterChange); } } else { if(instance.undoRedo){ delete instance.undoRedo; removeExposedUndoRedoMethods(instance); instance.removeHook('beforeKeyDown', onBeforeKeyDown); instance.removeHook('afterChange', onAfterChange); } } } function onBeforeKeyDown(event){ var instance = this; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if(ctrlDown){ if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z instance.undoRedo.redo(); event.stopImmediatePropagation(); } else if (event.keyCode === 90) { //CTRL + Z instance.undoRedo.undo(); event.stopImmediatePropagation(); } } } function onAfterChange(changes, source){ var instance = this; if (source == 'loadData'){ return instance.undoRedo.clear(); } } function exposeUndoRedoMethods(instance){ instance.undo = function(){ return instance.undoRedo.undo(); }; instance.redo = function(){ return instance.undoRedo.redo(); }; instance.isUndoAvailable = function(){ return instance.undoRedo.isUndoAvailable(); }; instance.isRedoAvailable = function(){ return instance.undoRedo.isRedoAvailable(); }; instance.clearUndo = function(){ return instance.undoRedo.clear(); }; } function removeExposedUndoRedoMethods(instance){ delete instance.undo; delete instance.redo; delete instance.isUndoAvailable; delete instance.isRedoAvailable; delete instance.clearUndo; } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable); /** * Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport * @constructor */ function DragToScroll() { this.boundaries = null; this.callback = null; } /** * @param boundaries {Object} compatible with getBoundingClientRect */ DragToScroll.prototype.setBoundaries = function (boundaries) { this.boundaries = boundaries; }; /** * @param callback {Function} */ DragToScroll.prototype.setCallback = function (callback) { this.callback = callback; }; /** * Check if mouse position (x, y) is outside of the viewport * @param x * @param y */ DragToScroll.prototype.check = function (x, y) { var diffX = 0; var diffY = 0; if (y < this.boundaries.top) { //y is less than top diffY = y - this.boundaries.top; } else if (y > this.boundaries.bottom) { //y is more than bottom diffY = y - this.boundaries.bottom; } if (x < this.boundaries.left) { //x is less than left diffX = x - this.boundaries.left; } else if (x > this.boundaries.right) { //x is more than right diffX = x - this.boundaries.right; } this.callback(diffX, diffY); }; var listening = false; var dragToScroll; var instance; if (typeof Handsontable !== 'undefined') { var setupListening = function (instance) { var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll dragToScroll = new DragToScroll(); if (scrollHandler === window) { //not much we can do currently return; } else if (scrollHandler) { dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect()); } else { dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect()); } dragToScroll.setCallback(function (scrollX, scrollY) { if (scrollX < 0) { if (scrollHandler) { scrollHandler.scrollLeft -= 50; } else { instance.view.wt.scrollHorizontal(-1).draw(); } } else if (scrollX > 0) { if (scrollHandler) { scrollHandler.scrollLeft += 50; } else { instance.view.wt.scrollHorizontal(1).draw(); } } if (scrollY < 0) { if (scrollHandler) { scrollHandler.scrollTop -= 20; } else { instance.view.wt.scrollVertical(-1).draw(); } } else if (scrollY > 0) { if (scrollHandler) { scrollHandler.scrollTop += 20; } else { instance.view.wt.scrollVertical(1).draw(); } } }); listening = true; }; Handsontable.PluginHooks.add('afterInit', function () { $(document).on('mouseup.' + this.guid, function () { listening = false; }); $(document).on('mousemove.' + this.guid, function (event) { if (listening) { dragToScroll.check(event.clientX, event.clientY); } }); }); Handsontable.PluginHooks.add('destroy', function () { $(document).off('.' + this.guid); }); Handsontable.PluginHooks.add('afterOnCellMouseDown', function () { setupListening(this); }); Handsontable.PluginHooks.add('afterOnCellCornerMouseDown', function () { setupListening(this); }); Handsontable.plugins.DragToScroll = DragToScroll; } (function (Handsontable, CopyPaste, SheetClip) { function CopyPastePlugin(instance) { this.copyPasteInstance = CopyPaste.getInstance(); this.copyPasteInstance.onCut(onCut); this.copyPasteInstance.onPaste(onPaste); var plugin = this; instance.addHook('beforeKeyDown', onBeforeKeyDown); function onCut() { if (!instance.isListening()) { return; } instance.selection.empty(); } function onPaste(str) { if (!instance.isListening() || !instance.selection.isSelected()) { return; } var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input , inputArray = SheetClip.parse(input) , selected = instance.getSelected() , coords = instance.getCornerCoords([{row: selected[0], col: selected[1]}, {row: selected[2], col: selected[3]}]) , areaStart = coords.TL , areaEnd = { row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row), col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col) }; instance.PluginHooks.once('afterChange', function (changes, source) { if (changes && changes.length) { this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col); } }); instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode); }; function onBeforeKeyDown (event) { if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) { //when CTRL is pressed, prepare selectable text in textarea //http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript plugin.setCopyableText(); event.stopImmediatePropagation(); return; } var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) { setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin)); } } this.destroy = function () { this.copyPasteInstance.removeCallback(onCut); this.copyPasteInstance.removeCallback(onPaste); this.copyPasteInstance.destroy(); instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this)); this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance); this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance); /** * Prepares copyable text in the invisible textarea */ this.setCopyableText = function () { var selection = instance.getSelected(); var settings = instance.getSettings(); var copyRowsLimit = settings.copyRowsLimit; var copyColsLimit = settings.copyColsLimit; var startRow = Math.min(selection[0], selection[2]); var startCol = Math.min(selection[1], selection[3]); var endRow = Math.max(selection[0], selection[2]); var endCol = Math.max(selection[1], selection[3]); var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1); var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1); instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol)); if (endRow !== finalEndRow || endCol !== finalEndCol) { instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit); } }; } function init() { var instance = this; var pluginEnabled = instance.getSettings().copyPaste !== false; if(pluginEnabled && !instance.copyPaste){ instance.copyPaste = new CopyPastePlugin(instance); } else if (!pluginEnabled && instance.copyPaste) { instance.copyPaste.destroy(); delete instance.copyPaste; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable, CopyPaste, SheetClip); (function (Handsontable) { 'use strict'; Handsontable.Search = function Search(instance) { this.query = function (queryStr, callback, queryMethod) { var rowCount = instance.countRows(); var colCount = instance.countCols(); var queryResult = []; if (!callback) { callback = Handsontable.Search.global.getDefaultCallback(); } if (!queryMethod) { queryMethod = Handsontable.Search.global.getDefaultQueryMethod(); } for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) { for (var colIndex = 0; colIndex < colCount; colIndex++) { var cellData = instance.getDataAtCell(rowIndex, colIndex); var cellProperties = instance.getCellMeta(rowIndex, colIndex); var cellCallback = cellProperties.search.callback || callback; var cellQueryMethod = cellProperties.search.queryMethod || queryMethod; var testResult = cellQueryMethod(queryStr, cellData); if (testResult) { var singleResult = { row: rowIndex, col: colIndex, data: cellData }; queryResult.push(singleResult); } if (cellCallback) { cellCallback(instance, rowIndex, colIndex, cellData, testResult); } } } return queryResult; }; }; Handsontable.Search.DEFAULT_CALLBACK = function (instance, row, col, data, testResult) { instance.getCellMeta(row, col).isSearchResult = testResult; }; Handsontable.Search.DEFAULT_QUERY_METHOD = function (query, value) { if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length == 0){ return false; } return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1; }; Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult'; Handsontable.Search.global = (function () { var defaultCallback = Handsontable.Search.DEFAULT_CALLBACK; var defaultQueryMethod = Handsontable.Search.DEFAULT_QUERY_METHOD; var defaultSearchResultClass = Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS; return { getDefaultCallback: function () { return defaultCallback; }, setDefaultCallback: function (newDefaultCallback) { defaultCallback = newDefaultCallback; }, getDefaultQueryMethod: function () { return defaultQueryMethod; }, setDefaultQueryMethod: function (newDefaultQueryMethod) { defaultQueryMethod = newDefaultQueryMethod; }, getDefaultSearchResultClass: function () { return defaultSearchResultClass; }, setDefaultSearchResultClass: function (newSearchResultClass) { defaultSearchResultClass = newSearchResultClass; } } })(); Handsontable.SearchCellDecorator = function (instance, TD, row, col, prop, value, cellProperties) { var searchResultClass = (typeof cellProperties.search == 'object' && cellProperties.search.searchResultClass) || Handsontable.Search.global.getDefaultSearchResultClass(); if(cellProperties.isSearchResult){ Handsontable.Dom.addClass(TD, searchResultClass); } else { Handsontable.Dom.removeClass(TD, searchResultClass); } }; var originalDecorator = Handsontable.renderers.cellDecorator; Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) { originalDecorator.apply(this, arguments); Handsontable.SearchCellDecorator.apply(this, arguments); }; function init() { var instance = this; var pluginEnabled = !!instance.getSettings().search; if (pluginEnabled) { instance.search = new Handsontable.Search(instance); } else { delete instance.search; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable); /** * Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable * and (optionally) implements behavior needed for native horizontal and vertical scrolling */ function WalkontableOverlay() { this.maxOuts = 10; //max outs in one direction (before and after table) } /* Possible optimizations: [x] don't rerender if scroll delta is smaller than the fragment outside of the viewport [ ] move .style.top change before .draw() [ ] put .draw() in requestAnimationFrame [ ] don't rerender rows that remain visible after the scroll */ WalkontableOverlay.prototype.init = function () { this.TABLE = this.instance.wtTable.TABLE; this.fixed = this.instance.wtTable.hider; this.fixedContainer = this.instance.wtTable.holder; this.fixed.style.position = 'absolute'; this.fixed.style.left = '0'; this.scrollHandler = this.getScrollableElement(this.TABLE); this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here }; WalkontableOverlay.prototype.makeClone = function (direction) { var clone = document.createElement('DIV'); clone.className = 'ht_clone_' + direction + ' handsontable'; clone.style.position = 'fixed'; clone.style.overflow = 'hidden'; var table2 = document.createElement('TABLE'); table2.className = this.instance.wtTable.TABLE.className; clone.appendChild(table2); this.instance.wtTable.holder.parentNode.appendChild(clone); return new Walkontable({ cloneSource: this.instance, cloneOverlay: this, table: table2 }); }; WalkontableOverlay.prototype.getScrollableElement = function (TABLE) { var el = TABLE.parentNode; while (el && el.style) { if (el.style.overflow !== 'visible' && el.style.overflow !== '') { return el; } if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') { return el; } el = el.parentNode; } return window; }; WalkontableOverlay.prototype.prepare = function () { }; WalkontableOverlay.prototype.onScroll = function (forcePosition) { this.windowScrollPosition = this.getScrollPosition(); this.readSettings(); //read window scroll position if (forcePosition) { this.windowScrollPosition = forcePosition; } this.resetFixedPosition(); //may be redundant }; WalkontableOverlay.prototype.availableSize = function () { var availableSize; if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) { availableSize = this.instance.wtDom.outerHeight(this.TABLE); } else { availableSize = this.windowSize; } } else { availableSize = this.windowSize - (this.tableParentOffset); } return availableSize; }; WalkontableOverlay.prototype.refresh = function (selectionsOnly) { var last = this.getLastCell(); this.measureBefore = this.sumCellSizes(0, this.offset); if (last === -1) { //last -1 means that viewport is scrolled behind the table this.measureAfter = 0; } else { this.measureAfter = this.sumCellSizes(last, this.total - last); } this.applyToDOM(); this.clone && this.clone.draw(selectionsOnly); }; WalkontableOverlay.prototype.destroy = function () { this.$scrollHandler.off('.' + this.instance.guid); $(window).off('.' + this.instance.guid); $(document).off('.' + this.instance.guid); }; function WalkontableBorder(instance, settings) { var style; //reference to instance this.instance = instance; this.settings = settings; this.wtDom = this.instance.wtDom; this.main = document.createElement("div"); style = this.main.style; style.position = 'absolute'; style.top = 0; style.left = 0; // style.visibility = 'hidden'; for (var i = 0; i < 5; i++) { var DIV = document.createElement('DIV'); DIV.className = 'wtBorder ' + (settings.className || ''); style = DIV.style; style.backgroundColor = settings.border.color; style.height = settings.border.width + 'px'; style.width = settings.border.width + 'px'; this.main.appendChild(DIV); } this.top = this.main.childNodes[0]; this.left = this.main.childNodes[1]; this.bottom = this.main.childNodes[2]; this.right = this.main.childNodes[3]; /*$(this.top).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.left).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.bottom).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.right).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); });*/ this.topStyle = this.top.style; this.leftStyle = this.left.style; this.bottomStyle = this.bottom.style; this.rightStyle = this.right.style; this.corner = this.main.childNodes[4]; this.corner.className += ' corner'; this.cornerStyle = this.corner.style; this.cornerStyle.width = '5px'; this.cornerStyle.height = '5px'; this.cornerStyle.border = '2px solid #FFF'; this.disappear(); if (!instance.wtTable.bordersHolder) { instance.wtTable.bordersHolder = document.createElement('div'); instance.wtTable.bordersHolder.className = 'htBorders'; instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder); } instance.wtTable.bordersHolder.appendChild(this.main); var down = false; var $body = $(document.body); $body.on('mousedown.walkontable.' + instance.guid, function () { down = true; }); $body.on('mouseup.walkontable.' + instance.guid, function () { down = false }); $(this.main.childNodes).on('mouseenter', function (event) { if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) { return; } event.preventDefault(); event.stopImmediatePropagation(); var bounds = this.getBoundingClientRect(); var $this = $(this); $this.hide(); var isOutside = function (event) { if (event.clientY < Math.floor(bounds.top)) { return true; } if (event.clientY > Math.ceil(bounds.top + bounds.height)) { return true; } if (event.clientX < Math.floor(bounds.left)) { return true; } if (event.clientX > Math.ceil(bounds.left + bounds.width)) { return true; } }; $body.on('mousemove.border.' + instance.guid, function (event) { if (isOutside(event)) { $body.off('mousemove.border.' + instance.guid); $this.show(); } }); }); } /** * Show border around one or many cells * @param {Array} corners */ WalkontableBorder.prototype.appear = function (corners) { var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width; if (this.disabled) { return; } var instance = this.instance , fromRow , fromColumn , toRow , toColumn , hideTop = false , hideLeft = false , hideBottom = false , hideRight = false , i , ilen , s; if (!instance.wtTable.isRowInViewport(corners[0])) { hideTop = true; } if (!instance.wtTable.isRowInViewport(corners[2])) { hideBottom = true; } ilen = instance.wtTable.rowStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { fromRow = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { toRow = s; break; } } if (hideTop && hideBottom) { hideLeft = true; hideRight = true; } else { if (!instance.wtTable.isColumnInViewport(corners[1])) { hideLeft = true; } if (!instance.wtTable.isColumnInViewport(corners[3])) { hideRight = true; } ilen = instance.wtTable.columnStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { fromColumn = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { toColumn = s; break; } } } if (fromRow !== void 0 && fromColumn !== void 0) { isMultiple = (fromRow !== toRow || fromColumn !== toColumn); fromTD = instance.wtTable.getCell([fromRow, fromColumn]); toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD; fromOffset = this.wtDom.offset(fromTD); toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset; containerOffset = this.wtDom.offset(instance.wtTable.TABLE); minTop = fromOffset.top; height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop; minLeft = fromOffset.left; width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft; top = minTop - containerOffset.top - 1; left = minLeft - containerOffset.left - 1; var style = this.wtDom.getComputedStyle(fromTD); if (parseInt(style['borderTopWidth'], 10) > 0) { top += 1; height = height > 0 ? height - 1 : 0; } if (parseInt(style['borderLeftWidth'], 10) > 0) { left += 1; width = width > 0 ? width - 1 : 0; } } else { this.disappear(); return; } if (hideTop) { this.topStyle.display = 'none'; } else { this.topStyle.top = top + 'px'; this.topStyle.left = left + 'px'; this.topStyle.width = width + 'px'; this.topStyle.display = 'block'; } if (hideLeft) { this.leftStyle.display = 'none'; } else { this.leftStyle.top = top + 'px'; this.leftStyle.left = left + 'px'; this.leftStyle.height = height + 'px'; this.leftStyle.display = 'block'; } var delta = Math.floor(this.settings.border.width / 2); if (hideBottom) { this.bottomStyle.display = 'none'; } else { this.bottomStyle.top = top + height - delta + 'px'; this.bottomStyle.left = left + 'px'; this.bottomStyle.width = width + 'px'; this.bottomStyle.display = 'block'; } if (hideRight) { this.rightStyle.display = 'none'; } else { this.rightStyle.top = top + 'px'; this.rightStyle.left = left + width - delta + 'px'; this.rightStyle.height = height + 1 + 'px'; this.rightStyle.display = 'block'; } if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) { this.cornerStyle.display = 'none'; } else { this.cornerStyle.top = top + height - 4 + 'px'; this.cornerStyle.left = left + width - 4 + 'px'; this.cornerStyle.display = 'block'; } }; /** * Hide border */ WalkontableBorder.prototype.disappear = function () { this.topStyle.display = 'none'; this.leftStyle.display = 'none'; this.bottomStyle.display = 'none'; this.rightStyle.display = 'none'; this.cornerStyle.display = 'none'; }; WalkontableBorder.prototype.hasSetting = function (setting) { if (typeof setting === 'function') { return setting(); } return !!setting; }; /** * WalkontableCellFilter * @constructor */ function WalkontableCellFilter() { this.offset = 0; this.total = 0; this.fixedCount = 0; } WalkontableCellFilter.prototype.source = function (n) { return n; }; WalkontableCellFilter.prototype.offsetted = function (n) { return n + this.offset; }; WalkontableCellFilter.prototype.unOffsetted = function (n) { return n - this.offset; }; WalkontableCellFilter.prototype.fixed = function (n) { if (n < this.fixedCount) { return n - this.offset; } else { return n; } }; WalkontableCellFilter.prototype.unFixed = function (n) { if (n < this.fixedCount) { return n + this.offset; } else { return n; } }; WalkontableCellFilter.prototype.visibleToSource = function (n) { return this.source(this.offsetted(this.fixed(n))); }; WalkontableCellFilter.prototype.sourceToVisible = function (n) { return this.source(this.unOffsetted(this.unFixed(n))); }; /** * WalkontableCellStrategy * @constructor */ function WalkontableCellStrategy(instance) { this.instance = instance; } WalkontableCellStrategy.prototype.getSize = function (index) { return this.cellSizes[index]; }; WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) { return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn; }; WalkontableCellStrategy.prototype.countVisible = function () { return this.cellCount; }; WalkontableCellStrategy.prototype.isLastIncomplete = function () { if(this.instance.getSetting('nativeScrollbars')){ var nativeScrollbar = this.instance.cloneFrom ? this.instance.cloneFrom.wtScrollbars.vertical : this.instance.wtScrollbars.vertical; return this.remainingSize > nativeScrollbar.sumCellSizes(nativeScrollbar.offset, nativeScrollbar.offset + nativeScrollbar.curOuts + 1); } else { return this.remainingSize > 0; } }; /** * WalkontableClassNameList * @constructor */ function WalkontableClassNameCache() { this.cache = []; } WalkontableClassNameCache.prototype.add = function (r, c, cls) { if (!this.cache[r]) { this.cache[r] = []; } if (!this.cache[r][c]) { this.cache[r][c] = []; } this.cache[r][c][cls] = true; }; WalkontableClassNameCache.prototype.test = function (r, c, cls) { return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]); }; /** * WalkontableColumnFilter * @constructor */ function WalkontableColumnFilter() { this.countTH = 0; } WalkontableColumnFilter.prototype = new WalkontableCellFilter(); WalkontableColumnFilter.prototype.readSettings = function (instance) { this.offset = instance.wtSettings.settings.offsetColumn; this.total = instance.getSetting('totalColumns'); this.fixedCount = instance.getSetting('fixedColumnsLeft'); this.countTH = instance.getSetting('rowHeaders').length; }; WalkontableColumnFilter.prototype.offsettedTH = function (n) { return n - this.countTH; }; WalkontableColumnFilter.prototype.unOffsettedTH = function (n) { return n + this.countTH; }; WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) { return this.visibleToSource(this.offsettedTH(n)); }; WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) { return this.unOffsettedTH(this.sourceToVisible(n)); }; /** * WalkontableColumnStrategy * @param containerSizeFn * @param sizeAtIndex * @param strategy - all, last, none * @constructor */ function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) { var size , i = 0; WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.cellSizesSum = 0; this.cellSizes = []; this.cellStretch = []; this.cellCount = 0; this.remainingSize = 0; this.strategy = strategy; //step 1 - determine cells that fit containerSize and cache their widths while (true) { size = sizeAtIndex(i); if (size === void 0) { break; //total columns exceeded } if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) { break; //total width exceeded } this.cellSizes.push(size); this.cellSizesSum += size; this.cellCount++; i++; } var containerSize = this.getContainerSize(this.cellSizesSum); this.remainingSize = this.cellSizesSum - containerSize; //negative value means the last cell is fully visible and there is some space left for stretching //positive value means the last cell is not fully visible } WalkontableColumnStrategy.prototype = new WalkontableCellStrategy(); WalkontableColumnStrategy.prototype.getSize = function (index) { return this.cellSizes[index] + (this.cellStretch[index] || 0); }; WalkontableColumnStrategy.prototype.stretch = function () { //step 2 - apply stretching strategy var containerSize = this.getContainerSize(this.cellSizesSum) , i = 0; this.remainingSize = this.cellSizesSum - containerSize; this.cellStretch.length = 0; //clear previous stretch if (this.strategy === 'all') { if (this.remainingSize < 0) { var ratio = containerSize / this.cellSizesSum; var newSize; while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop newSize = Math.floor(ratio * this.cellSizes[i]); this.remainingSize += newSize - this.cellSizes[i]; this.cellStretch[i] = newSize - this.cellSizes[i]; i++; } this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } else if (this.strategy === 'last') { if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test) this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } }; function Walkontable(settings) { var that = this, originalHeaders = []; this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events //bootstrap from settings this.wtDom = new WalkontableDom(); if (settings.cloneSource) { this.cloneSource = settings.cloneSource; this.cloneOverlay = settings.cloneOverlay; this.wtSettings = settings.cloneSource.wtSettings; this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = settings.cloneSource.wtViewport; } else { this.wtSettings = new WalkontableSettings(this, settings); this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = new WalkontableViewport(this); this.wtScrollbars = new WalkontableScrollbars(this); this.wtWheel = new WalkontableWheel(this); this.wtEvent = new WalkontableEvent(this); } //find original headers if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) { for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) { originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML); } if (!this.getSetting('columnHeaders').length) { this.update('columnHeaders', [function (column, TH) { that.wtDom.fastInnerText(TH, originalHeaders[column]); }]); } } //initialize selections this.selections = {}; var selectionsSettings = this.getSetting('selections'); if (selectionsSettings) { for (var i in selectionsSettings) { if (selectionsSettings.hasOwnProperty(i)) { this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]); } } } this.drawn = false; this.drawInterrupted = false; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table /*if (window.Handsontable) { Handsontable.PluginHooks.add('beforeChange', function () { if (that.rowHeightCache) { that.rowHeightCache.length = 0; } }); }*/ } Walkontable.prototype.draw = function (selectionsOnly) { this.drawInterrupted = false; if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) { this.drawInterrupted = true; //draw interrupted because TABLE is not visible return; } this.getSetting('beforeDraw', !selectionsOnly); selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn; if (this.drawn) { //fix offsets that might have changed this.scrollVertical(0); this.scrollHorizontal(0); } this.lastOffsetRow = this.getSetting('offsetRow'); this.lastOffsetColumn = this.getSetting('offsetColumn'); this.wtTable.draw(selectionsOnly); if (!this.cloneSource) { this.getSetting('onDraw', !selectionsOnly); } return this; }; Walkontable.prototype.update = function (settings, value) { return this.wtSettings.update(settings, value); }; Walkontable.prototype.scrollVertical = function (delta) { var result = this.wtScroll.scrollVertical(delta); this.getSetting('onScrollVertically'); return result; }; Walkontable.prototype.scrollHorizontal = function (delta) { var result = this.wtScroll.scrollHorizontal(delta); this.getSetting('onScrollHorizontally'); return result; }; Walkontable.prototype.scrollViewport = function (coords) { this.wtScroll.scrollViewport(coords); return this; }; Walkontable.prototype.getViewport = function () { return [ this.wtTable.rowFilter.visibleToSource(0), this.wtTable.columnFilter.visibleToSource(0), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn() ]; }; Walkontable.prototype.getSetting = function (key, param1, param2, param3) { return this.wtSettings.getSetting(key, param1, param2, param3); }; Walkontable.prototype.hasSetting = function (key) { return this.wtSettings.has(key); }; Walkontable.prototype.destroy = function () { $(document.body).off('.' + this.guid); this.wtScrollbars.destroy(); clearTimeout(this.wheelTimeout); this.wtEvent && this.wtEvent.destroy(); }; /** * A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays. * Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly * @param instance * @constructor */ function WalkontableDebugOverlay(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('debug'); this.clone.wtTable.holder.style.opacity = 0.4; this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000'; var that = this; var lastTimeout; var lastX = 0; var lastY = 0; var overlayContainer = that.clone.wtTable.holder.parentNode; $(document.body).on('mousemove.' + this.instance.guid, function (event) { if (!that.instance.wtTable.holder.parentNode) { return; //removed from DOM } if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) { return; //ignore minor mouse movement } lastX = event.clientX; lastY = event.clientY; WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible'); clearTimeout(lastTimeout); lastTimeout = setTimeout(function () { WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible'); }, 1000); }); } WalkontableDebugOverlay.prototype = new WalkontableOverlay(); WalkontableDebugOverlay.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box = this.instance.wtTable.holder.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; }; WalkontableDebugOverlay.prototype.prepare = function () { }; WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) { this.clone && this.clone.draw(selectionsOnly); }; WalkontableDebugOverlay.prototype.getScrollPosition = function () { }; WalkontableDebugOverlay.prototype.getLastCell = function () { }; WalkontableDebugOverlay.prototype.applyToDOM = function () { }; WalkontableDebugOverlay.prototype.scrollTo = function () { }; WalkontableDebugOverlay.prototype.readWindowSize = function () { }; WalkontableDebugOverlay.prototype.readSettings = function () { }; function WalkontableDom() { } //goes up the DOM tree (including given element) until it finds an element that matches the nodeName WalkontableDom.prototype.closest = function (elem, nodeNames, until) { while (elem != null && elem !== until) { if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) { return elem; } elem = elem.parentNode; } return null; }; //goes up the DOM tree and checks if element is child of another element WalkontableDom.prototype.isChildOf = function (child, parent) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Counts index of element within its parent * WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable * Otherwise would need to check for nodeType or use previousElementSibling * @see http://jsperf.com/sibling-index/10 * @param {Element} elem * @return {Number} */ WalkontableDom.prototype.index = function (elem) { var i = 0; while (elem = elem.previousSibling) { ++i } return i; }; if (document.documentElement.classList) { // HTML5 classList API WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.classList.contains(cls); }; WalkontableDom.prototype.addClass = function (ele, cls) { ele.classList.add(cls); }; WalkontableDom.prototype.removeClass = function (ele, cls) { ele.classList.remove(cls); }; } else { //http://snipplr.com/view/3561/addclass-removeclass-hasclass/ WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }; WalkontableDom.prototype.addClass = function (ele, cls) { if (!this.hasClass(ele, cls)) ele.className += " " + cls; }; WalkontableDom.prototype.removeClass = function (ele, cls) { if (this.hasClass(ele, cls)) { //is this really needed? var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js } }; } /*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ WalkontableDom.prototype.addEvent = (function () { var that = this; if (document.addEventListener) { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.addEventListener(type, cb, false); } else if (elem && elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } else { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.attachEvent('on' + type, function () { //normalize //http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization var e = window['event']; e.target = e.srcElement; //e.offsetX = e.layerX; //e.offsetY = e.layerY; e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement; if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug return cb.call(elem, e) }); } else if (elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } })(); WalkontableDom.prototype.triggerEvent = function (element, eventName, target) { var event; if (document.createEvent) { event = document.createEvent("MouseEvents"); event.initEvent(eventName, true, true); } else { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; event.target = target; if (document.createEvent) { target.dispatchEvent(event); } else { target.fireEvent("on" + event.eventType, event); } };*/ WalkontableDom.prototype.removeTextNodes = function (elem, parent) { if (elem.nodeType === 3) { parent.removeChild(elem); //bye text nodes! } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) { var childs = elem.childNodes; for (var i = childs.length - 1; i >= 0; i--) { this.removeTextNodes(childs[i], elem); } } }; /** * Remove childs function * WARNING - this doesn't unload events and data attached by jQuery * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method * @param element * @returns {void} */ // WalkontableDom.prototype.empty = function (element) { var child; while (child = element.lastChild) { element.removeChild(child); } }; WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/; /** * Insert content into element trying avoid innerHTML method. * @return {void} */ WalkontableDom.prototype.fastInnerHTML = function (element, content) { if (this.HTML_CHARACTERS.test(content)) { element.innerHTML = content; } else { this.fastInnerText(element, content); } }; /** * Insert text content into element * @return {void} */ if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.textContent = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } else { //IE8 WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.data = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } /** * Returns true/false depending if element has offset parent * @param elem * @returns {boolean} */ /*if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.hasOffsetParent = function (elem) { return !!elem.offsetParent; } } else { WalkontableDom.prototype.hasOffsetParent = function (elem) { try { if (!elem.offsetParent) { return false; } } catch (e) { return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here } return true; } }*/ /** * Returns true if element is attached to the DOM and visible, false otherwise * @param elem * @returns {boolean} */ WalkontableDom.prototype.isVisible = function (elem) { //fast method according to benchmarks, but requires layout so slow in our case /* if (!WalkontableDom.prototype.hasOffsetParent(elem)) { return false; //fixes problem with UI Bootstrap <tabs> directive } // if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here if (elem.offsetWidth > 0) { return true; } */ //slow method var next = elem; while (next !== document.documentElement) { //until <html> reached if (next === null) { //parent detached from DOM return false; } else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE if (next.host) { //this is Web Components Shadow DOM //see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation //according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled return WalkontableDom.prototype.isVisible(next.host.impl); } else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled return WalkontableDom.prototype.isVisible(next.host); } else { throw new Error("Lost in Web Components world"); } } else { return false; //this is a node detached from document in IE8 } } else if (next.style.display === 'none') { return false; } next = next.parentNode; } return true; }; /** * Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster * @param {HTMLElement} elem * @return {Object} */ WalkontableDom.prototype.offset = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE offset (see also WalkontableDom.prototype.outerHeight) //http://jsperf.com/offset-vs-getboundingclientrect/8 var box = elem.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0), left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0) }; } var offsetLeft = elem.offsetLeft , offsetTop = elem.offsetTop , lastElem = elem; while (elem = elem.offsetParent) { if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0 break; } offsetLeft += elem.offsetLeft; offsetTop += elem.offsetTop; lastElem = elem; } if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6 //if(lastElem !== document.body) { //faster but does gives false positive in Firefox offsetLeft += window.pageXOffset || document.documentElement.scrollLeft; offsetTop += window.pageYOffset || document.documentElement.scrollTop; } return { left: offsetLeft, top: offsetTop }; }; WalkontableDom.prototype.getComputedStyle = function (elem) { return elem.currentStyle || document.defaultView.getComputedStyle(elem); }; WalkontableDom.prototype.outerWidth = function (elem) { return elem.offsetWidth; }; WalkontableDom.prototype.outerHeight = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight //jQuery (1.10.1) still has this unsolved //may be better to just switch to getBoundingClientRect //http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/ //http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html //http://bugs.jquery.com/ticket/2196 //http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140 return elem.offsetHeight + elem.firstChild.offsetHeight; } else { return elem.offsetHeight; } }; (function () { var hasCaptionProblem; function detectCaptionProblem() { var TABLE = document.createElement('TABLE'); TABLE.style.borderSpacing = 0; TABLE.style.borderWidth = 0; TABLE.style.padding = 0; var TBODY = document.createElement('TBODY'); TABLE.appendChild(TBODY); TBODY.appendChild(document.createElement('TR')); TBODY.firstChild.appendChild(document.createElement('TD')); TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>'; var CAPTION = document.createElement('CAPTION'); CAPTION.innerHTML = 'c<br>c<br>c<br>c'; CAPTION.style.padding = 0; CAPTION.style.margin = 0; TABLE.insertBefore(CAPTION, TBODY); document.body.appendChild(TABLE); hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean document.body.removeChild(TABLE); } WalkontableDom.prototype.hasCaptionProblem = function () { if (hasCaptionProblem === void 0) { detectCaptionProblem(); } return hasCaptionProblem; }; /** * Returns caret position in text input * @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea * @return {Number} */ WalkontableDom.prototype.getCaretPosition = function (el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { //IE8 el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }; /** * Sets caret position in text input * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ * @param {Element} el * @param {Number} pos * @param {Number} endPos */ WalkontableDom.prototype.setCaretPosition = function (el, pos, endPos) { if (endPos === void 0) { endPos = pos; } if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, endPos); } else if (el.createTextRange) { //IE8 var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', endPos); range.moveStart('character', pos); range.select(); } }; var cachedScrollbarWidth; //http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes function walkontableCalculateScrollbarWidth() { var inner = document.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); (document.body || document.documentElement).appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) w2 = outer.clientWidth; (document.body || document.documentElement).removeChild(outer); return (w1 - w2); } /** * Returns the computed width of the native browser scroll bar * @return {Number} width */ WalkontableDom.prototype.getScrollbarWidth = function () { if (cachedScrollbarWidth === void 0) { cachedScrollbarWidth = walkontableCalculateScrollbarWidth(); } return cachedScrollbarWidth; } })(); function WalkontableEvent(instance) { var that = this; //reference to instance this.instance = instance; this.wtDom = this.instance.wtDom; var dblClickOrigin = [null, null]; var dblClickTimeout = [null, null]; var onMouseDown = function (event) { var cell = that.parentCell(event.target); if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerMouseDown', event, event.target); } else if (cell.TD && cell.TD.nodeName === 'TD') { if (that.instance.hasSetting('onCellMouseDown')) { that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD); } } if (event.button !== 2) { //if not right mouse button if (cell.TD && cell.TD.nodeName === 'TD') { dblClickOrigin[0] = cell.TD; clearTimeout(dblClickTimeout[0]); dblClickTimeout[0] = setTimeout(function () { dblClickOrigin[0] = null; }, 1000); } } }; var lastMouseOver; var onMouseOver = function (event) { if (that.instance.hasSetting('onCellMouseOver')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOver = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD); } } } }; /* var lastMouseOut; var onMouseOut = function (event) { if (that.instance.hasSetting('onCellMouseOut')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOut = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD); } } } };*/ var onMouseUp = function (event) { if (event.button !== 2) { //if not right mouse button var cell = that.parentCell(event.target); if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) { if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD); } else if (cell.TD) { that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD); } dblClickOrigin[0] = null; dblClickOrigin[1] = null; } else if (cell.TD === dblClickOrigin[0]) { dblClickOrigin[1] = cell.TD; clearTimeout(dblClickTimeout[1]); dblClickTimeout[1] = setTimeout(function () { dblClickOrigin[1] = null; }, 500); } } }; $(this.instance.wtTable.holder).on('mousedown', onMouseDown); $(this.instance.wtTable.TABLE).on('mouseover', onMouseOver); // $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut); $(this.instance.wtTable.holder).on('mouseup', onMouseUp); } WalkontableEvent.prototype.parentCell = function (elem) { var cell = {}; var TABLE = this.instance.wtTable.TABLE; var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE); if (TD && this.wtDom.isChildOf(TD, TABLE)) { cell.coords = this.instance.wtTable.getCoords(TD); cell.TD = TD; } else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current')) { cell.coords = this.instance.selections.current.selected[0]; cell.TD = this.instance.wtTable.getCell(cell.coords); } return cell; }; WalkontableEvent.prototype.destroy = function () { clearTimeout(this.dblClickTimeout0); clearTimeout(this.dblClickTimeout1); }; function walkontableRangesIntersect() { var from = arguments[0]; var to = arguments[1]; for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) { if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) { return true; } } return false; } /** * Generates a random hex string. Used as namespace for Walkontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ function walkontableRandomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4(); } /** * http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html */ window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (/* function */ callback, /* DOMElement */ element) { return window.setTimeout(callback, 1000 / 60); }; })(); window.cancelRequestAnimFrame = (function () { return window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || clearTimeout })(); //http://snipplr.com/view/13523/ //modified for speed //http://jsperf.com/getcomputedstyle-vs-style-vs-css/8 if (!window.getComputedStyle) { (function () { var elem; var styleObj = { getPropertyValue: function getPropertyValue(prop) { if (prop == 'float') prop = 'styleFloat'; return elem.currentStyle[prop.toUpperCase()] || null; } }; window.getComputedStyle = function (el) { elem = el; return styleObj; } })(); } /** * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim */ if (!String.prototype.trim) { var trimRegex = /^\s+|\s+$/g; String.prototype.trim = function () { return this.replace(trimRegex, ''); }; } /** * WalkontableRowFilter * @constructor */ function WalkontableRowFilter() { } WalkontableRowFilter.prototype = new WalkontableCellFilter(); WalkontableRowFilter.prototype.readSettings = function (instance) { if (instance.cloneOverlay instanceof WalkontableDebugOverlay) { this.offset = 0; } else { this.offset = instance.wtSettings.settings.offsetRow; } this.total = instance.getSetting('totalRows'); this.fixedCount = instance.getSetting('fixedRowsTop'); }; /** * WalkontableRowStrategy * @param containerSizeFn * @param sizeAtIndex * @constructor */ function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) { WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.sizeAtIndex = sizeAtIndex; this.cellSizesSum = 0; this.cellSizes = []; this.cellCount = 0; this.remainingSize = -Infinity; } WalkontableRowStrategy.prototype = new WalkontableCellStrategy(); WalkontableRowStrategy.prototype.add = function (i, TD, reverse) { if (!this.isLastIncomplete() && this.remainingSize != 0) { var size = this.sizeAtIndex(i, TD); if (size === void 0) { return false; //total rows exceeded } var containerSize = this.getContainerSize(this.cellSizesSum + size); if (reverse) { this.cellSizes.unshift(size); } else { this.cellSizes.push(size); } this.cellSizesSum += size; this.cellCount++; this.remainingSize = this.cellSizesSum - containerSize; if (reverse && this.isLastIncomplete()) { //something is outside of the screen, maybe even some full rows? return false; } return true; } return false; }; WalkontableRowStrategy.prototype.remove = function () { var size = this.cellSizes.pop(); this.cellSizesSum -= size; this.cellCount--; this.remainingSize -= size; }; WalkontableRowStrategy.prototype.removeOutstanding = function () { while (this.cellCount > 0 && this.cellSizes[this.cellCount - 1] < this.remainingSize) { //this row is completely off screen! this.remove(); } }; function WalkontableScroll(instance) { this.instance = instance; } WalkontableScroll.prototype.scrollVertical = function (delta) { if (!this.instance.drawn) { throw new Error('scrollVertical can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetRow') , fixedCount = instance.getSetting('fixedRowsTop') , total = instance.getSetting('totalRows') , maxSize = instance.wtViewport.getViewportHeight(); if (total > 0) { newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) { if (row - offset < fixedCount && row - offset >= 0) { return instance.getSetting('rowHeight', row - offset); } else { return instance.getSetting('rowHeight', row); } }, function (isReverse) { instance.wtTable.verticalRenderReverse = isReverse; }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.vertical.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollHorizontal = function (delta) { if (!this.instance.drawn) { throw new Error('scrollHorizontal can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetColumn') , fixedCount = instance.getSetting('fixedColumnsLeft') , total = instance.getSetting('totalColumns') , maxSize = instance.wtViewport.getViewportWidth(); if (total > 0) { newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) { if (col - offset < fixedCount && col - offset >= 0) { return instance.getSetting('columnWidth', col - offset); } else { return instance.getSetting('columnWidth', col); } }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.horizontal.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) { var newOffset = offset + delta; if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; setReverseRenderFn(true); } if (newOffset < 0) { newOffset = 0; } return newOffset; }; WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) { var newOffset = offset + delta , sum = 0 , col; if (newOffset > fixedCount) { if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; } col = newOffset; while (sum < maxSize && col < total) { sum += cellSizeFn(col); col++; } if (sum < maxSize) { while (newOffset > 0) { //if sum still less than available width, we cannot scroll that far (must move offset to the left) sum += cellSizeFn(newOffset - 1); if (sum < maxSize) { newOffset--; } else { break; } } } } else if (newOffset < 0) { newOffset = 0; } return newOffset; }; /** * Scrolls viewport to a cell by minimum number of cells */ WalkontableScroll.prototype.scrollViewport = function (coords) { if (!this.instance.drawn) { return; } var offsetRow = this.instance.getSetting('offsetRow') , offsetColumn = this.instance.getSetting('offsetColumn') , lastVisibleRow = this.instance.wtTable.getLastVisibleRow() , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , fixedRowsTop = this.instance.getSetting('fixedRowsTop') , fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); if (this.instance.getSetting('nativeScrollbars')) { var TD = this.instance.wtTable.getCell(coords); if (typeof TD === 'object') { var offset = WalkontableDom.prototype.offset(TD); var outerWidth = WalkontableDom.prototype.outerWidth(TD); var outerHeight = WalkontableDom.prototype.outerHeight(TD); var scrollX = this.instance.wtScrollbars.horizontal.getScrollPosition(); var scrollY = this.instance.wtScrollbars.vertical.getScrollPosition(); var clientWidth = WalkontableDom.prototype.outerWidth(this.instance.wtScrollbars.horizontal.scrollHandler); var clientHeight = WalkontableDom.prototype.outerHeight(this.instance.wtScrollbars.vertical.scrollHandler); if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { offset.left = offset.left - WalkontableDom.prototype.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left; } if (this.instance.wtScrollbars.vertical.scrollHandler !== window) { offset.top = offset.top - WalkontableDom.prototype.offset(this.instance.wtScrollbars.vertical.scrollHandler).top; } clientWidth -= 20; clientHeight -= 20; if (outerWidth < clientWidth) { if (offset.left < scrollX) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left); } else if (offset.left + outerWidth > scrollX + clientWidth) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left - clientWidth + outerWidth); } } if (outerHeight < clientHeight) { if (offset.top < scrollY) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top); } else if (offset.top + outerHeight > scrollY + clientHeight) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top - clientHeight + outerHeight); } } return; } } if (coords[0] < 0 || coords[0] > totalRows - 1) { throw new Error('row ' + coords[0] + ' does not exist'); } else if (coords[1] < 0 || coords[1] > totalColumns - 1) { throw new Error('column ' + coords[1] + ' does not exist'); } if (coords[0] > lastVisibleRow) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] - fixedRowsTop < offsetRow) { this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); } else { this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed } if (this.instance.wtTable.isColumnBeforeViewport(coords[1])) { //scroll left this.instance.wtScrollbars.horizontal.scrollTo(coords[1] - fixedColumnsLeft); } else if (this.instance.wtTable.isColumnAfterViewport(coords[1]) || (this.instance.wtTable.getLastVisibleColumn() === coords[1] && !this.instance.wtTable.isLastColumnFullyVisible())) { //scroll right var sum = 0; for (var i = 0; i < fixedColumnsLeft; i++) { sum += this.instance.getSetting('columnWidth', i); } var scrollTo = coords[1]; sum += this.instance.getSetting('columnWidth', scrollTo); var available = this.instance.wtViewport.getViewportWidth(); if (sum < available) { var next = this.instance.getSetting('columnWidth', scrollTo - 1); while (sum + next <= available && scrollTo >= fixedColumnsLeft) { scrollTo--; sum += next; next = this.instance.getSetting('columnWidth', scrollTo - 1); } } this.instance.wtScrollbars.horizontal.scrollTo(scrollTo - fixedColumnsLeft); } /*else { //no scroll }*/ return this.instance; }; function WalkontableScrollbar() { } WalkontableScrollbar.prototype.init = function () { var that = this; //reference to instance this.$table = $(this.instance.wtTable.TABLE); //create elements this.slider = document.createElement('DIV'); this.sliderStyle = this.slider.style; this.sliderStyle.position = 'absolute'; this.sliderStyle.top = '0'; this.sliderStyle.left = '0'; this.sliderStyle.display = 'none'; this.slider.className = 'dragdealer ' + this.type; this.handle = document.createElement('DIV'); this.handleStyle = this.handle.style; this.handle.className = 'handle'; this.slider.appendChild(this.handle); this.container = this.instance.wtTable.holder; this.container.appendChild(this.slider); var firstRun = true; this.dragTimeout = null; var dragDelta; var dragRender = function () { that.onScroll(dragDelta); }; this.dragdealer = new Dragdealer(this.slider, { vertical: (this.type === 'vertical'), horizontal: (this.type === 'horizontal'), slide: false, speed: 100, animationCallback: function (x, y) { if (firstRun) { firstRun = false; return; } that.skipRefresh = true; dragDelta = that.type === 'vertical' ? y : x; if (that.dragTimeout === null) { that.dragTimeout = setInterval(dragRender, 100); dragRender(); } }, callback: function (x, y) { that.skipRefresh = false; clearInterval(that.dragTimeout); that.dragTimeout = null; dragDelta = that.type === 'vertical' ? y : x; that.onScroll(dragDelta); } }); this.skipRefresh = false; }; WalkontableScrollbar.prototype.onScroll = function (delta) { if (this.instance.drawn) { this.readSettings(); if (this.total > this.visibleCount) { var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize); if (delta === 1) { if (this.type === 'vertical') { this.instance.scrollVertical(Infinity).draw(); } else { this.instance.scrollHorizontal(Infinity).draw(); } } else if (newOffset !== this.offset) { //is new offset different than old offset if (this.type === 'vertical') { this.instance.scrollVertical(newOffset - this.offset).draw(); } else { this.instance.scrollHorizontal(newOffset - this.offset).draw(); } } else { this.refresh(); } } } }; /** * Returns what part of the scroller should the handle take * @param viewportCount {Number} number of visible rows or columns * @param totalCount {Number} total number of rows or columns * @return {Number} 0..1 */ WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return 1 / totalCount; }; WalkontableScrollbar.prototype.prepare = function () { if (this.skipRefresh) { return; } var ratio = this.getHandleSizeRatio(this.visibleCount, this.total); if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') { //isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0 this.visible = false; } else { this.visible = true; } }; WalkontableScrollbar.prototype.refresh = function () { if (this.skipRefresh) { return; } else if (!this.visible) { this.sliderStyle.display = 'none'; return; } var ratio , sliderSize , handleSize , handlePosition , visibleCount = this.visibleCount , tableWidth = this.instance.wtViewport.getWorkspaceWidth() , tableHeight = this.instance.wtViewport.getWorkspaceHeight(); if (tableWidth === Infinity) { tableWidth = this.instance.wtViewport.getWorkspaceActualWidth(); } if (tableHeight === Infinity) { tableHeight = this.instance.wtViewport.getWorkspaceActualHeight(); } if (this.type === 'vertical') { if (this.instance.wtTable.rowStrategy.isLastIncomplete()) { visibleCount--; } sliderSize = tableHeight - 2; //2 is sliders border-width this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px'; this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width this.sliderStyle.height = Math.max(sliderSize, 0) + 'px'; } else { //horizontal sliderSize = tableWidth - 2; //2 is sliders border-width this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px'; this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width this.sliderStyle.width = Math.max(sliderSize, 0) + 'px'; } ratio = this.getHandleSizeRatio(visibleCount, this.total); handleSize = Math.round(sliderSize * ratio); if (handleSize < 10) { handleSize = 15; } handlePosition = Math.floor(sliderSize * (this.offset / this.total)); if (handleSize + handlePosition > sliderSize) { handlePosition = sliderSize - handleSize; } if (this.type === 'vertical') { this.handleStyle.height = handleSize + 'px'; this.handleStyle.top = handlePosition + 'px'; } else { //horizontal this.handleStyle.width = handleSize + 'px'; this.handleStyle.left = handlePosition + 'px'; } this.sliderStyle.display = 'block'; }; WalkontableScrollbar.prototype.destroy = function () { clearInterval(this.dragdealer.interval); }; /// var WalkontableVerticalScrollbar = function (instance) { this.instance = instance; this.type = 'vertical'; this.init(); }; WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar(); WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetRow', cell); }; WalkontableVerticalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollV'); this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); this.visibleCount = this.instance.wtTable.rowStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.top, 10); this.sliderSize = parseInt(this.sliderStyle.height, 10); this.fixedCount = this.instance.getSetting('fixedRowsTop'); }; /// var WalkontableHorizontalScrollbar = function (instance) { this.instance = instance; this.type = 'horizontal'; this.init(); }; WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar(); WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetColumn', cell); }; WalkontableHorizontalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollH'); this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); this.visibleCount = this.instance.wtTable.columnStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.left, 10); this.sliderSize = parseInt(this.sliderStyle.width, 10); this.fixedCount = this.instance.getSetting('fixedColumnsLeft'); }; WalkontableHorizontalScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return viewportCount / totalCount; }; function WalkontableCornerScrollbarNative(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('corner'); } WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay(); WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } elem.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; WalkontableCornerScrollbarNative.prototype.prepare = function () { }; WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () { }; WalkontableCornerScrollbarNative.prototype.getLastCell = function () { }; WalkontableCornerScrollbarNative.prototype.applyToDOM = function () { }; WalkontableCornerScrollbarNative.prototype.scrollTo = function () { }; WalkontableCornerScrollbarNative.prototype.readWindowSize = function () { }; WalkontableCornerScrollbarNative.prototype.readSettings = function () { }; function WalkontableHorizontalScrollbarNative(instance) { this.instance = instance; this.type = 'horizontal'; this.cellSize = 50; this.init(); this.clone = this.makeClone('left'); } WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var overlayContainer = this.clone.wtTable.holder.parentNode; if (this.instance.wtScrollbars.vertical.scrollHandler === window) { var box = this.instance.wtTable.hider.getBoundingClientRect(); overlayContainer.style.top = Math.ceil(box.top, 10) + 'px'; overlayContainer.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 'px'; } else { this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px'; overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px' } overlayContainer.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow }; WalkontableHorizontalScrollbarNative.prototype.prepare = function () { }; WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollX; } else { return this.scrollHandler.scrollLeft; } }; WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollLeft = pos; }; WalkontableHorizontalScrollbarNative.prototype.onScroll = function () { WalkontableOverlay.prototype.onScroll.apply(this, arguments); this.instance.getSetting('onScrollHorizontally'); }; WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () { return this.instance.wtTable.getLastVisibleColumn(); }; //applyToDOM (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () { this.fixedContainer.style.paddingLeft = this.measureBefore + 'px'; this.fixedContainer.style.paddingRight = this.measureAfter + 'px'; }; WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) { this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize); }; //readWindowSize (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientWidth; this.tableParentOffset = this.instance.wtTable.holderOffset.left; } else { this.windowSize = WalkontableDom.prototype.outerWidth(this.scrollHandler); this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); }; function WalkontableVerticalScrollbarNative(instance) { this.instance = instance; this.type = 'vertical'; this.cellSize = 23; this.init(); this.clone = this.makeClone('top'); } WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } } else { box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } if (this.instance.wtScrollbars.horizontal.scrollHandler === window) { elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px'; } else { elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px'; } elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { var elem = this.clone.wtTable.holder.parentNode; elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px'; } }; WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollY; } else { return this.scrollHandler.scrollTop; } }; WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollTop = pos; }; WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) { WalkontableOverlay.prototype.onScroll.apply(this, arguments); var scrollDelta; var newOffset = 0; if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) { scrollDelta = this.windowScrollPosition - this.tableParentOffset; partialOffset = 0; if (scrollDelta > 0) { var sum = 0; var last; for (var i = 0; i < this.total; i++) { last = this.instance.getSetting('rowHeight', i); sum += last; if (sum > scrollDelta) { break; } } if (this.offset > 0) { partialOffset = (sum - scrollDelta); } newOffset = i; newOffset = Math.min(newOffset, this.total); } } this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset; newOffset -= this.curOuts; this.instance.update('offsetRow', newOffset); this.readSettings(); //read new offset this.instance.draw(); this.instance.getSetting('onScrollVertically'); }; WalkontableVerticalScrollbarNative.prototype.getLastCell = function () { return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1; }; var partialOffset = 0; WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) { var sum = 0; while (from < length) { sum += this.instance.getSetting('rowHeight', from); from++; } return sum; }; //applyToDOM (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () { var headerSize = this.instance.wtViewport.getColumnHeaderHeight(); this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow this.fixed.style.top = this.measureBefore + 'px'; this.fixed.style.bottom = ''; }; WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) { var newY = this.tableParentOffset + cell * this.cellSize; this.$scrollHandler.scrollTop(newY); this.onScroll(newY); }; //readWindowSize (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientHeight; this.tableParentOffset = this.instance.wtTable.holderOffset.top; } else { //this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler); this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); }; function WalkontableScrollbars(instance) { this.instance = instance; if (instance.getSetting('nativeScrollbars')) { instance.update('scrollbarWidth', instance.wtDom.getScrollbarWidth()); instance.update('scrollbarHeight', instance.wtDom.getScrollbarWidth()); this.vertical = new WalkontableVerticalScrollbarNative(instance); this.horizontal = new WalkontableHorizontalScrollbarNative(instance); this.corner = new WalkontableCornerScrollbarNative(instance); if (instance.getSetting('debug')) { this.debug = new WalkontableDebugOverlay(instance); } this.registerListeners(); } else { this.vertical = new WalkontableVerticalScrollbar(instance); this.horizontal = new WalkontableHorizontalScrollbar(instance); } } WalkontableScrollbars.prototype.registerListeners = function () { var that = this; var oldVerticalScrollPosition , oldHorizontalScrollPosition , oldBoxTop , oldBoxLeft , oldBoxWidth , oldBoxHeight; function refreshAll() { if (!that.instance.wtTable.holder.parentNode) { //Walkontable was detached from DOM, but this handler was not removed that.destroy(); return; } that.vertical.windowScrollPosition = that.vertical.getScrollPosition(); that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition(); that.box = that.instance.wtTable.hider.getBoundingClientRect(); if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) { //that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table oldBoxWidth = that.box.width; oldBoxHeight = that.box.height; that.instance.draw(); } if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) { that.vertical.onScroll(); that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles that.vertical.react(); that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles oldVerticalScrollPosition = that.vertical.windowScrollPosition; oldHorizontalScrollPosition = that.horizontal.windowScrollPosition; oldBoxTop = that.box.top; oldBoxLeft = that.box.left; } } var $window = $(window); this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) { this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); } if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) { $window.on('scroll.' + this.instance.guid, refreshAll); } $window.on('load.' + this.instance.guid, refreshAll); $window.on('resize.' + this.instance.guid, refreshAll); $(document).on('ready.' + this.instance.guid, refreshAll); setInterval(refreshAll, 100); //Marcin - only idea I have to reposition scrollbars on CSS change of the container (container was moved using some styles after page was loaded) }; WalkontableScrollbars.prototype.destroy = function () { this.vertical && this.vertical.destroy(); this.horizontal && this.horizontal.destroy(); }; WalkontableScrollbars.prototype.refresh = function (selectionsOnly) { this.horizontal && this.horizontal.readSettings(); this.vertical && this.vertical.readSettings(); this.horizontal && this.horizontal.prepare(); this.vertical && this.vertical.prepare(); this.horizontal && this.horizontal.refresh(selectionsOnly); this.vertical && this.vertical.refresh(selectionsOnly); this.corner && this.corner.refresh(selectionsOnly); this.debug && this.debug.refresh(selectionsOnly); }; function WalkontableSelection(instance, settings) { this.instance = instance; this.settings = settings; this.selected = []; if (settings.border) { this.border = new WalkontableBorder(instance, settings); } } WalkontableSelection.prototype.add = function (coords) { this.selected.push(coords); }; WalkontableSelection.prototype.clear = function () { this.selected.length = 0; //http://jsperf.com/clear-arrayxxx }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @returns {Object} */ WalkontableSelection.prototype.getCorners = function () { var minRow , minColumn , maxRow , maxColumn , i , ilen = this.selected.length; if (ilen > 0) { minRow = maxRow = this.selected[0][0]; minColumn = maxColumn = this.selected[0][1]; if (ilen > 1) { for (i = 1; i < ilen; i++) { if (this.selected[i][0] < minRow) { minRow = this.selected[i][0]; } else if (this.selected[i][0] > maxRow) { maxRow = this.selected[i][0]; } if (this.selected[i][1] < minColumn) { minColumn = this.selected[i][1]; } else if (this.selected[i][1] > maxColumn) { maxColumn = this.selected[i][1]; } } } } return [minRow, minColumn, maxRow, maxColumn]; }; WalkontableSelection.prototype.draw = function () { var corners, r, c, source_r, source_c; var visibleRows = this.instance.wtTable.rowStrategy.countVisible() , visibleColumns = this.instance.wtTable.columnStrategy.countVisible(); if (this.selected.length) { corners = this.getCorners(); for (r = 0; r < visibleRows; r++) { for (c = 0; c < visibleColumns; c++) { source_r = this.instance.wtTable.rowFilter.visibleToSource(r); source_c = this.instance.wtTable.columnFilter.visibleToSource(c); if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) { //selected cell this.instance.wtTable.currentCellCache.add(r, c, this.settings.className); } else if (source_r >= corners[0] && source_r <= corners[2]) { //selection is in this row this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName); } else if (source_c >= corners[1] && source_c <= corners[3]) { //selection is in this column this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName); } } } this.border && this.border.appear(corners); //warning! border.appear modifies corners! } else { this.border && this.border.disappear(); } }; function WalkontableSettings(instance, settings) { var that = this; this.instance = instance; //default settings. void 0 means it is required, null means it can be empty this.defaults = { table: void 0, debug: false, //shows WalkontableDebugOverlay //presentation mode scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar) scrollV: 'auto', //values: see above nativeScrollbars: false, //values: false (dragdealer), true (native) stretchH: 'hybrid', //values: hybrid, all, last, none currentRowClassName: null, currentColumnClassName: null, //data source data: void 0, offsetRow: 0, offsetColumn: 0, fixedColumnsLeft: 0, fixedRowsTop: 0, rowHeaders: function () { return [] }, //this must be array of functions: [function (row, TH) {}] columnHeaders: function () { return [] }, //this must be array of functions: [function (column, TH) {}] totalRows: void 0, totalColumns: void 0, width: null, height: null, cellRenderer: function (row, column, TD) { var cellData = that.getSetting('data', row, column); that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData); }, columnWidth: 50, selections: null, hideBorderOnMouseDownOver: false, //callbacks onCellMouseDown: null, onCellMouseOver: null, // onCellMouseOut: null, onCellDblClick: null, onCellCornerMouseDown: null, onCellCornerDblClick: null, beforeDraw: null, onDraw: null, onScrollVertically: null, onScrollHorizontally: null, //constants scrollbarWidth: 10, scrollbarHeight: 10 }; //reference to settings this.settings = {}; for (var i in this.defaults) { if (this.defaults.hasOwnProperty(i)) { if (settings[i] !== void 0) { this.settings[i] = settings[i]; } else if (this.defaults[i] === void 0) { throw new Error('A required setting "' + i + '" was not provided'); } else { this.settings[i] = this.defaults[i]; } } } } /** * generic methods */ WalkontableSettings.prototype.update = function (settings, value) { if (value === void 0) { //settings is object for (var i in settings) { if (settings.hasOwnProperty(i)) { this.settings[i] = settings[i]; } } } else { //if value is defined then settings is the key this.settings[settings] = value; } return this.instance; }; WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) { if (this[key]) { return this[key](param1, param2, param3); } else { return this._getSetting(key, param1, param2, param3); } }; WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) { if (typeof this.settings[key] === 'function') { return this.settings[key](param1, param2, param3); } else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') { return this.settings[key][param1]; } else { return this.settings[key]; } }; WalkontableSettings.prototype.has = function (key) { return !!this.settings[key] }; /** * specific methods */ WalkontableSettings.prototype.rowHeight = function (row, TD) { if (!this.instance.rowHeightCache) { this.instance.rowHeightCache = []; //hack. This cache is being invalidated in WOT core.js } if (this.instance.rowHeightCache[row] === void 0) { var size = 23; //guess if (TD) { size = this.instance.wtDom.outerHeight(TD); //measure this.instance.rowHeightCache[row] = size; //cache only something we measured } return size; } else { return this.instance.rowHeightCache[row]; } }; function WalkontableTable(instance, table) { //reference to instance this.instance = instance; this.TABLE = table; this.wtDom = this.instance.wtDom; this.wtDom.removeTextNodes(this.TABLE); //wtSpreader var parent = this.TABLE.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var spreader = document.createElement('DIV'); spreader.className = 'wtSpreader'; if (parent) { parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } spreader.appendChild(this.TABLE); } this.spreader = this.TABLE.parentNode; //wtHider parent = this.spreader.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var hider = document.createElement('DIV'); hider.className = 'wtHider'; if (parent) { parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } hider.appendChild(this.spreader); } this.hider = this.spreader.parentNode; this.hiderStyle = this.hider.style; this.hiderStyle.position = 'relative'; //wtHolder parent = this.hider.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var holder = document.createElement('DIV'); holder.style.position = 'relative'; holder.className = 'wtHolder'; if (parent) { parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } holder.appendChild(this.hider); } this.holder = this.hider.parentNode; //bootstrap from settings this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0]; if (!this.TBODY) { this.TBODY = document.createElement('TBODY'); this.TABLE.appendChild(this.TBODY); } this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0]; if (!this.THEAD) { this.THEAD = document.createElement('THEAD'); this.TABLE.insertBefore(this.THEAD, this.TBODY); } this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0]; if (!this.COLGROUP) { this.COLGROUP = document.createElement('COLGROUP'); this.TABLE.insertBefore(this.COLGROUP, this.THEAD); } if (this.instance.getSetting('columnHeaders').length) { if (!this.THEAD.childNodes.length) { var TR = document.createElement('TR'); this.THEAD.appendChild(TR); } } this.colgroupChildrenLength = this.COLGROUP.childNodes.length; this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0; this.tbodyChildrenLength = this.TBODY.childNodes.length; this.oldCellCache = new WalkontableClassNameCache(); this.currentCellCache = new WalkontableClassNameCache(); this.rowFilter = new WalkontableRowFilter(); this.columnFilter = new WalkontableColumnFilter(); this.verticalRenderReverse = false; } WalkontableTable.prototype.refreshHiderDimensions = function () { var height = this.instance.wtViewport.getWorkspaceHeight(); var width = this.instance.wtViewport.getWorkspaceWidth(); var spreaderStyle = this.spreader.style; if ((height !== Infinity || width !== Infinity) && !this.instance.getSetting('nativeScrollbars')) { if (height === Infinity) { height = this.instance.wtViewport.getWorkspaceActualHeight(); } if (width === Infinity) { width = this.instance.wtViewport.getWorkspaceActualWidth(); } this.hiderStyle.overflow = 'hidden'; spreaderStyle.position = 'absolute'; spreaderStyle.top = '0'; spreaderStyle.left = '0'; if (!this.instance.getSetting('nativeScrollbars')) { spreaderStyle.height = '4000px'; spreaderStyle.width = '4000px'; } if (height < 0) { //this happens with WalkontableOverlay and causes "Invalid argument" error in IE8 height = 0; } this.hiderStyle.height = height + 'px'; this.hiderStyle.width = width + 'px'; } else { spreaderStyle.position = 'relative'; spreaderStyle.width = 'auto'; spreaderStyle.height = 'auto'; } }; WalkontableTable.prototype.refreshStretching = function () { if (this.instance.cloneSource) { return; } var instance = this.instance , stretchH = instance.getSetting('stretchH') , totalRows = instance.getSetting('totalRows') , totalColumns = instance.getSetting('totalColumns') , offsetColumn = instance.getSetting('offsetColumn'); var containerWidthFn = function (cacheWidth) { var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth); if (viewportWidth < cacheWidth && that.instance.getSetting('nativeScrollbars')) { return Infinity; //disable stretching when viewport is bigger than sum of the cell widths } return viewportWidth; }; var that = this; var columnWidthFn = function (i) { var source_c = that.columnFilter.visibleToSource(i); if (source_c < totalColumns) { return instance.getSetting('columnWidth', source_c); } }; if (stretchH === 'hybrid') { if (offsetColumn > 0) { stretchH = 'last'; } else { stretchH = 'none'; } } var containerHeightFn = function (cacheHeight) { if (that.instance.getSetting('nativeScrollbars')) { if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay) { return Infinity; } else { return 2 * that.instance.wtViewport.getViewportHeight(cacheHeight); } } return that.instance.wtViewport.getViewportHeight(cacheHeight); }; var rowHeightFn = function (i, TD) { if (that.instance.getSetting('nativeScrollbars')) { return 20; } var source_r = that.rowFilter.visibleToSource(i); if (source_r < totalRows) { if (that.verticalRenderReverse && i === 0) { return that.instance.getSetting('rowHeight', source_r, TD) - 1; } else { return that.instance.getSetting('rowHeight', source_r, TD); } } }; this.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH); this.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn); }; WalkontableTable.prototype.adjustAvailableNodes = function () { var displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , columnHeaders = this.instance.getSetting('columnHeaders') , TR , TD , c; //adjust COLGROUP while (this.colgroupChildrenLength < displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } //adjust COLGROUP while (this.colgroupChildrenLength < displayTds + displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } while (this.colgroupChildrenLength > displayTds + displayThs) { this.COLGROUP.removeChild(this.COLGROUP.lastChild); this.colgroupChildrenLength--; } //adjust THEAD TR = this.THEAD.firstChild; if (columnHeaders.length) { if (!TR) { TR = document.createElement('TR'); this.THEAD.appendChild(TR); } this.theadChildrenLength = TR.childNodes.length; while (this.theadChildrenLength < displayTds + displayThs) { TR.appendChild(document.createElement('TH')); this.theadChildrenLength++; } while (this.theadChildrenLength > displayTds + displayThs) { TR.removeChild(TR.lastChild); this.theadChildrenLength--; } } else if (TR) { this.wtDom.empty(TR); } //draw COLGROUP for (c = 0; c < this.colgroupChildrenLength; c++) { if (c < displayThs) { this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader'); } else { this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader'); } } //draw THEAD if (columnHeaders.length) { TR = this.THEAD.firstChild; if (displayThs) { TD = TR.firstChild; //actually it is TH but let's reuse single variable for (c = 0; c < displayThs; c++) { rowHeaders[c](-displayThs + c, TD); TD = TD.nextSibling; } } } for (c = 0; c < displayTds; c++) { if (columnHeaders.length) { columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]); } } }; WalkontableTable.prototype.adjustColumns = function (TR, desiredCount) { var count = TR.childNodes.length; while (count < desiredCount) { var TD = document.createElement('TD'); TR.appendChild(TD); count++; } while (count > desiredCount) { TR.removeChild(TR.lastChild); count--; } }; WalkontableTable.prototype.draw = function (selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { this.verticalRenderReverse = false; //this is only supported in dragdealer mode, not in native } this.rowFilter.readSettings(this.instance); this.columnFilter.readSettings(this.instance); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { this.tableOffset = this.instance.cloneSource.wtTable.tableOffset; } else { this.holderOffset = this.wtDom.offset(this.holder); this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtScrollbars.vertical.readWindowSize(); this.instance.wtScrollbars.horizontal.readWindowSize(); this.instance.wtViewport.resetSettings(); } } else { this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtViewport.resetSettings(); } this._doDraw(); } else { this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true); } this.refreshPositions(selectionsOnly); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (!this.instance.cloneSource) { this.instance.wtScrollbars.vertical.resetFixedPosition(); this.instance.wtScrollbars.horizontal.resetFixedPosition(); this.instance.wtScrollbars.corner.resetFixedPosition(); this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition(); } } } this.instance.drawn = true; return this; }; WalkontableTable.prototype._doDraw = function () { var r = 0 , source_r , c , source_c , offsetRow = this.instance.getSetting('offsetRow') , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , TR , TD , TH , adjusted = false , workspaceWidth , mustBeInViewport , res; if (this.verticalRenderReverse) { mustBeInViewport = offsetRow; } var noPartial = false; if (this.verticalRenderReverse) { if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) { noPartial = true; } else { this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse this.rowFilter.readSettings(this.instance); } } if (this.instance.cloneSource) { this.columnStrategy = this.instance.cloneSource.wtTable.columnStrategy; this.rowStrategy = this.instance.cloneSource.wtTable.rowStrategy; } //draw TBODY if (totalColumns > 0) { source_r = this.rowFilter.visibleToSource(r); var fixedRowsTop = this.instance.getSetting('fixedRowsTop'); var cloneLimit; if (this.instance.cloneSource) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) { cloneLimit = fixedRowsTop; } else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) { cloneLimit = this.rowStrategy.countVisible(); } //else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows } this.adjustAvailableNodes(); adjusted = true; if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } if (!this.instance.cloneSource) { workspaceWidth = this.instance.wtViewport.getWorkspaceWidth(); this.columnStrategy.stretch(); } for (c = 0; c < displayTds; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } while (source_r < totalRows && source_r >= 0) { if (r > 1000) { throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.'); } if (cloneLimit !== void 0 && r === cloneLimit) { break; //we have as much rows as needed for this clone } if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) { TR = document.createElement('TR'); for (c = 0; c < displayThs; c++) { TR.appendChild(document.createElement('TH')); } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild); } else { this.TBODY.appendChild(TR); } this.tbodyChildrenLength++; } else if (r === 0) { TR = this.TBODY.firstChild; } else { TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //TH TH = TR.firstChild; for (c = 0; c < displayThs; c++) { //If the number of row headers increased we need to replace TD with TH if (TH.nodeName == 'TD') { TD = TH; TH = document.createElement('TH'); TR.insertBefore(TH, TD); TR.removeChild(TD); } rowHeaders[c](source_r, TH); //actually TH TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } this.adjustColumns(TR, displayTds + displayThs); for (c = 0; c < displayTds; c++) { source_c = this.columnFilter.visibleToSource(c); if (c === 0) { TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)]; } else { TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //If the number of headers has been reduced, we need to replace excess TH with TD if (TD.nodeName == 'TH') { TH = TD; TD = document.createElement('TD'); TR.insertBefore(TD, TH); TR.removeChild(TH); } TD.className = ''; TD.removeAttribute('style'); this.instance.getSetting('cellRenderer', source_r, source_c, TD); } offsetRow = this.instance.getSetting('offsetRow'); //refresh the value //after last column is rendered, check if last cell is fully displayed if (this.verticalRenderReverse && noPartial) { if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) { this.TBODY.removeChild(TR); this.instance.update('offsetRow', offsetRow + 1); this.tbodyChildrenLength--; this.rowFilter.readSettings(this.instance); break; } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { this.rowStrategy.removeOutstanding(); } } } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { if (!this.instance.getSetting('nativeScrollbars')) { this.rowStrategy.removeOutstanding(); } } if (this.rowStrategy.isLastIncomplete()) { if (this.verticalRenderReverse && !this.isRowInViewport(mustBeInViewport)) { //we failed because one of the cells was by far too large. Recover by rendering from top this.verticalRenderReverse = false; this.instance.update('offsetRow', mustBeInViewport); this.draw(); return; } break; } } if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { TR.style.height = this.instance.getSetting('rowHeight', source_r) + 'px'; //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height } else { this.instance.getSetting('rowHeight', source_r, TD); //this trick saves rowHeight in rowHeightCache. It is then read in WalkontableVerticalScrollbarNative.prototype.sumCellSizes and reset in Walkontable constructor } } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { if (offsetRow === 0) { break; } this.instance.update('offsetRow', offsetRow - 1); this.rowFilter.readSettings(this.instance); } else { r++; } source_r = this.rowFilter.visibleToSource(r); } } if (!adjusted) { this.adjustAvailableNodes(); } if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) { r = this.rowStrategy.countVisible(); while (this.tbodyChildrenLength > r) { this.TBODY.removeChild(this.TBODY.lastChild); this.tbodyChildrenLength--; } } this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(false); if (!this.instance.cloneSource) { if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) { //workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching this.columnStrategy.stretch(); for (c = 0; c < this.columnStrategy.cellCount; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } } } this.verticalRenderReverse = false; }; WalkontableTable.prototype.refreshPositions = function (selectionsOnly) { this.refreshHiderDimensions(); this.refreshSelections(selectionsOnly); }; WalkontableTable.prototype.refreshSelections = function (selectionsOnly) { var vr , r , vc , c , s , slen , classNames = [] , visibleRows = this.rowStrategy.countVisible() , visibleColumns = this.columnStrategy.countVisible(); this.oldCellCache = this.currentCellCache; this.currentCellCache = new WalkontableClassNameCache(); if (this.instance.selections) { for (r in this.instance.selections) { if (this.instance.selections.hasOwnProperty(r)) { this.instance.selections[r].draw(); if (this.instance.selections[r].settings.className) { classNames.push(this.instance.selections[r].settings.className); } if (this.instance.selections[r].settings.highlightRowClassName) { classNames.push(this.instance.selections[r].settings.highlightRowClassName); } if (this.instance.selections[r].settings.highlightColumnClassName) { classNames.push(this.instance.selections[r].settings.highlightColumnClassName); } } } } slen = classNames.length; for (vr = 0; vr < visibleRows; vr++) { for (vc = 0; vc < visibleColumns; vc++) { r = this.rowFilter.visibleToSource(vr); c = this.columnFilter.visibleToSource(vc); for (s = 0; s < slen; s++) { if (this.currentCellCache.test(vr, vc, classNames[s])) { this.wtDom.addClass(this.getCell([r, c]), classNames[s]); } else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) { this.wtDom.removeClass(this.getCell([r, c]), classNames[s]); } } } } }; /** * getCell * @param {Array} coords * @return {Object} HTMLElement on success or {Number} one of the exit codes on error: * -1 row before viewport * -2 row after viewport * -3 column before viewport * -4 column after viewport * */ WalkontableTable.prototype.getCell = function (coords) { if (this.isRowBeforeViewport(coords[0])) { return -1; //row before viewport } else if (this.isRowAfterViewport(coords[0])) { return -2; //row after viewport } else { if (this.isColumnBeforeViewport(coords[1])) { return -3; //column before viewport } else if (this.isColumnAfterViewport(coords[1])) { return -4; //column after viewport } else { return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])]; } } }; WalkontableTable.prototype.getCoords = function (TD) { return [ this.rowFilter.visibleToSource(this.wtDom.index(TD.parentNode)), this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex) ]; }; //returns -1 if no row is visible WalkontableTable.prototype.getLastVisibleRow = function () { return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1); }; //returns -1 if no column is visible WalkontableTable.prototype.getLastVisibleColumn = function () { return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1); }; WalkontableTable.prototype.isRowBeforeViewport = function (r) { return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount); }; WalkontableTable.prototype.isRowAfterViewport = function (r) { return (r > this.getLastVisibleRow()); }; WalkontableTable.prototype.isColumnBeforeViewport = function (c) { return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount); }; WalkontableTable.prototype.isColumnAfterViewport = function (c) { return (c > this.getLastVisibleColumn()); }; WalkontableTable.prototype.isRowInViewport = function (r) { return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r)); }; WalkontableTable.prototype.isColumnInViewport = function (c) { return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c)); }; WalkontableTable.prototype.isLastRowFullyVisible = function () { return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete()); }; WalkontableTable.prototype.isLastColumnFullyVisible = function () { return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete()); }; function WalkontableViewport(instance) { this.instance = instance; this.resetSettings(); if (this.instance.getSetting('nativeScrollbars')) { var that = this; $(window).on('resize', function () { that.clientHeight = that.getWorkspaceHeight(); }); } } /*WalkontableViewport.prototype.isInSightVertical = function () { //is table outside viewport bottom edge if (tableTop > windowHeight + scrollTop) { return -1; } //is table outside viewport top edge else if (scrollTop > tableTop + tableFakeHeight) { return -2; } //table is in viewport but how much exactly? else { } };*/ //used by scrollbar WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) { if (this.instance.getSetting('nativeScrollbars')) { return this.instance.wtScrollbars.vertical.windowSize; } var height = this.instance.getSetting('height'); if (height === Infinity || height === void 0 || height === null || height < 1) { if (this.instance.wtScrollbars.vertical instanceof WalkontableOverlay) { height = this.instance.wtScrollbars.vertical.availableSize(); } else { height = Infinity; } } if (height !== Infinity) { if (proposedHeight >= height) { height -= this.instance.getSetting('scrollbarHeight'); } else if (this.instance.wtScrollbars.horizontal.visible) { height -= this.instance.getSetting('scrollbarHeight'); } } return height; }; WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) { var width = this.instance.getSetting('width'); if (width === Infinity || width === void 0 || width === null || width < 1) { if (this.instance.wtScrollbars.horizontal instanceof WalkontableOverlay) { width = this.instance.wtScrollbars.horizontal.availableSize(); } else { width = Infinity; } } if (width !== Infinity) { if (proposedWidth >= width) { width -= this.instance.getSetting('scrollbarWidth'); } else if (this.instance.wtScrollbars.vertical.visible) { width -= this.instance.getSetting('scrollbarWidth'); } } return width; }; WalkontableViewport.prototype.getWorkspaceActualHeight = function () { return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE); }; WalkontableViewport.prototype.getWorkspaceActualWidth = function () { return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth; }; WalkontableViewport.prototype.getColumnHeaderHeight = function () { if (isNaN(this.columnHeaderHeight)) { var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY) , tableOffset = this.instance.wtTable.tableOffset; this.columnHeaderHeight = cellOffset.top - tableOffset.top; } return this.columnHeaderHeight; }; WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) { var containerHeight = this.getWorkspaceHeight(proposedHeight); if (containerHeight === Infinity) { return containerHeight; } var columnHeaderHeight = this.getColumnHeaderHeight(); if (columnHeaderHeight > 0) { return containerHeight - columnHeaderHeight; } else { return containerHeight; } }; WalkontableViewport.prototype.getRowHeaderWidth = function () { if (this.instance.cloneSource) { return this.instance.cloneSource.wtViewport.getRowHeaderWidth(); } if (isNaN(this.rowHeaderWidth)) { var rowHeaders = this.instance.getSetting('rowHeaders'); if (rowHeaders.length) { var TH = this.instance.wtTable.TABLE.querySelector('TH'); this.rowHeaderWidth = 0; for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) { if (TH) { this.rowHeaderWidth += this.instance.wtDom.outerWidth(TH); TH = TH.nextSibling; } else { this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix } } } else { this.rowHeaderWidth = 0; } } return this.rowHeaderWidth; }; WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) { var containerWidth = this.getWorkspaceWidth(proposedWidth); if (containerWidth === Infinity) { return containerWidth; } var rowHeaderWidth = this.getRowHeaderWidth(); if (rowHeaderWidth > 0) { return containerWidth - rowHeaderWidth; } else { return containerWidth; } }; WalkontableViewport.prototype.resetSettings = function () { this.rowHeaderWidth = NaN; this.columnHeaderHeight = NaN; }; function WalkontableWheel(instance) { if (instance.getSetting('nativeScrollbars')) { return; } //spreader === instance.wtTable.TABLE.parentNode $(instance.wtTable.spreader).on('mousewheel', function (event, delta, deltaX, deltaY) { if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53 deltaY = delta; } if (!deltaX && !deltaY) { //this happens in IE8 test case return; } if (deltaY > 0 && instance.getSetting('offsetRow') === 0) { return; //attempt to scroll up when it's already showing first row } else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) { return; //attempt to scroll down when it's already showing last row } else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) { return; //attempt to scroll left when it's already showing first column } else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) { return; //attempt to scroll right when it's already showing last column } //now we are sure we really want to scroll clearTimeout(instance.wheelTimeout); instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second if (deltaY) { //ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll //see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar instance.scrollVertical(-Math.ceil(deltaY)).draw(); } } else if (deltaX) { if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar instance.scrollHorizontal(Math.ceil(deltaX)).draw(); } } }, 0); event.preventDefault(); }); } /** * Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340 * http://code.ovidiu.ch/dragdealer-js * * Copyright (c) 2010, Ovidiu Chereches * MIT License * http://legal.ovidiu.ch/licenses/MIT */ /* Cursor */ var Cursor = { x: 0, y: 0, init: function() { this.setEvent('mouse'); this.setEvent('touch'); }, setEvent: function(type) { var moveHandler = document['on' + type + 'move'] || function(){}; document['on' + type + 'move'] = function(e) { moveHandler(e); Cursor.refresh(e); } }, refresh: function(e) { if(!e) { e = window.event; } if(e.type == 'mousemove') { this.set(e); } else if(e.touches) { this.set(e.touches[0]); } }, set: function(e) { if(e.pageX || e.pageY) { this.x = e.pageX; this.y = e.pageY; } else if(document.body && (e.clientX || e.clientY)) //need to check whether body exists, because of IE8 issue (#1084) { this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } } }; Cursor.init(); /* Position */ var Position = { get: function(obj) { var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope if(obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while((obj = obj.offsetParent)); } return [curleft, curtop]; } }; /* Dragdealer */ var Dragdealer = function(wrapper, options) { if(typeof(wrapper) == 'string') { wrapper = document.getElementById(wrapper); } if(!wrapper) { return; } var handle = wrapper.getElementsByTagName('div')[0]; if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1) { return; } this.init(wrapper, handle, options || {}); this.setup(); }; Dragdealer.prototype = { init: function(wrapper, handle, options) { this.wrapper = wrapper; this.handle = handle; this.options = options; this.disabled = this.getOption('disabled', false); this.horizontal = this.getOption('horizontal', true); this.vertical = this.getOption('vertical', false); this.slide = this.getOption('slide', true); this.steps = this.getOption('steps', 0); this.snap = this.getOption('snap', false); this.loose = this.getOption('loose', false); this.speed = this.getOption('speed', 10) / 100; this.xPrecision = this.getOption('xPrecision', 0); this.yPrecision = this.getOption('yPrecision', 0); this.callback = options.callback || null; this.animationCallback = options.animationCallback || null; this.bounds = { left: options.left || 0, right: -(options.right || 0), top: options.top || 0, bottom: -(options.bottom || 0), x0: 0, x1: 0, xRange: 0, y0: 0, y1: 0, yRange: 0 }; this.value = { prev: [-1, -1], current: [options.x || 0, options.y || 0], target: [options.x || 0, options.y || 0] }; this.offset = { wrapper: [0, 0], mouse: [0, 0], prev: [-999999, -999999], current: [0, 0], target: [0, 0] }; this.change = [0, 0]; this.activity = false; this.dragging = false; this.tapping = false; }, getOption: function(name, defaultValue) { return this.options[name] !== undefined ? this.options[name] : defaultValue; }, setup: function() { this.setWrapperOffset(); this.setBoundsPadding(); this.setBounds(); this.setSteps(); this.addListeners(); }, setWrapperOffset: function() { this.offset.wrapper = Position.get(this.wrapper); }, setBoundsPadding: function() { if(!this.bounds.left && !this.bounds.right) { this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0]; this.bounds.right = -this.bounds.left; } if(!this.bounds.top && !this.bounds.bottom) { this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1]; this.bounds.bottom = -this.bounds.top; } }, setBounds: function() { this.bounds.x0 = this.bounds.left; this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right; this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth; this.bounds.y0 = this.bounds.top; this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom; this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight; this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth)); this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight)); }, setSteps: function() { if(this.steps > 1) { this.stepRatios = []; for(var i = 0; i <= this.steps - 1; i++) { this.stepRatios[i] = i / (this.steps - 1); } } }, addListeners: function() { var self = this; this.wrapper.onselectstart = function() { return false; } this.handle.onmousedown = this.handle.ontouchstart = function(e) { self.handleDownHandler(e); }; this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e) { self.wrapperDownHandler(e); }; var mouseUpHandler = document.onmouseup || function(){}; document.onmouseup = function(e) { mouseUpHandler(e); self.documentUpHandler(e); }; var touchEndHandler = document.ontouchend || function(){}; document.ontouchend = function(e) { touchEndHandler(e); self.documentUpHandler(e); }; var resizeHandler = window.onresize || function(){}; window.onresize = function(e) { resizeHandler(e); self.documentResizeHandler(e); }; this.wrapper.onmousemove = function(e) { self.activity = true; } this.wrapper.onclick = function(e) { return !self.activity; } this.interval = setInterval(function(){ self.animate() }, 25); self.animate(false, true); }, handleDownHandler: function(e) { this.activity = false; Cursor.refresh(e); this.preventDefaults(e, true); this.startDrag(); }, wrapperDownHandler: function(e) { Cursor.refresh(e); this.preventDefaults(e, true); this.startTap(); }, documentUpHandler: function(e) { this.stopDrag(); this.stopTap(); }, documentResizeHandler: function(e) { this.setWrapperOffset(); this.setBounds(); this.update(); }, enable: function() { this.disabled = false; this.handle.className = this.handle.className.replace(/\s?disabled/g, ''); }, disable: function() { this.disabled = true; this.handle.className += ' disabled'; }, setStep: function(x, y, snap) { this.setValue( this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0, this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0, snap ); }, setValue: function(x, y, snap) { this.setTargetValue([x, y || 0]); if(snap) { this.groupCopy(this.value.current, this.value.target); } }, startTap: function(target) { if(this.disabled) { return; } this.tapping = true; this.setWrapperOffset(); this.setBounds(); if(target === undefined) { target = [ Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2), Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2) ]; } this.setTargetOffset(target); }, stopTap: function() { if(this.disabled || !this.tapping) { return; } this.tapping = false; this.setTargetValue(this.value.current); this.result(); }, startDrag: function() { if(this.disabled) { return; } this.setWrapperOffset(); this.setBounds(); this.offset.mouse = [ Cursor.x - Position.get(this.handle)[0], Cursor.y - Position.get(this.handle)[1] ]; this.dragging = true; }, stopDrag: function() { if(this.disabled || !this.dragging) { return; } this.dragging = false; var target = this.groupClone(this.value.current); if(this.slide) { var ratioChange = this.change; target[0] += ratioChange[0] * 4; target[1] += ratioChange[1] * 4; } this.setTargetValue(target); this.result(); }, feedback: function() { var value = this.value.current; if(this.snap && this.steps > 1) { value = this.getClosestSteps(value); } if(!this.groupCompare(value, this.value.prev)) { if(typeof(this.animationCallback) == 'function') { this.animationCallback(value[0], value[1]); } this.groupCopy(this.value.prev, value); } }, result: function() { if(typeof(this.callback) == 'function') { this.callback(this.value.target[0], this.value.target[1]); } }, animate: function(direct, first) { if(direct && !this.dragging) { return; } if(this.dragging) { var prevTarget = this.groupClone(this.value.target); var offset = [ Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0], Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1] ]; this.setTargetOffset(offset, this.loose); this.change = [ this.value.target[0] - prevTarget[0], this.value.target[1] - prevTarget[1] ]; } if(this.dragging || first) { this.groupCopy(this.value.current, this.value.target); } if(this.dragging || this.glide() || first) { this.update(); this.feedback(); } }, glide: function() { var diff = [ this.value.target[0] - this.value.current[0], this.value.target[1] - this.value.current[1] ]; if(!diff[0] && !diff[1]) { return false; } if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep) { this.value.current[0] += diff[0] * this.speed; this.value.current[1] += diff[1] * this.speed; } else { this.groupCopy(this.value.current, this.value.target); } return true; }, update: function() { if(!this.snap) { this.offset.current = this.getOffsetsByRatios(this.value.current); } else { this.offset.current = this.getOffsetsByRatios( this.getClosestSteps(this.value.current) ); } this.show(); }, show: function() { if(!this.groupCompare(this.offset.current, this.offset.prev)) { if(this.horizontal) { this.handle.style.left = String(this.offset.current[0]) + 'px'; } if(this.vertical) { this.handle.style.top = String(this.offset.current[1]) + 'px'; } this.groupCopy(this.offset.prev, this.offset.current); } }, setTargetValue: function(value, loose) { var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, setTargetOffset: function(offset, loose) { var value = this.getRatiosByOffsets(offset); var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, getLooseValue: function(value) { var proper = this.getProperValue(value); return [ proper[0] + ((value[0] - proper[0]) / 4), proper[1] + ((value[1] - proper[1]) / 4) ]; }, getProperValue: function(value) { var proper = this.groupClone(value); proper[0] = Math.max(proper[0], 0); proper[1] = Math.max(proper[1], 0); proper[0] = Math.min(proper[0], 1); proper[1] = Math.min(proper[1], 1); if((!this.dragging && !this.tapping) || this.snap) { if(this.steps > 1) { proper = this.getClosestSteps(proper); } } return proper; }, getRatiosByOffsets: function(group) { return [ this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0), this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getRatioByOffset: function(offset, range, padding) { return range ? (offset - padding) / range : 0; }, getOffsetsByRatios: function(group) { return [ this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0), this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getOffsetByRatio: function(ratio, range, padding) { return Math.round(ratio * range) + padding; }, getClosestSteps: function(group) { return [ this.getClosestStep(group[0]), this.getClosestStep(group[1]) ]; }, getClosestStep: function(value) { var k = 0; var min = 1; for(var i = 0; i <= this.steps - 1; i++) { if(Math.abs(this.stepRatios[i] - value) < min) { min = Math.abs(this.stepRatios[i] - value); k = i; } } return this.stepRatios[k]; }, groupCompare: function(a, b) { return a[0] == b[0] && a[1] == b[1]; }, groupCopy: function(a, b) { a[0] = b[0]; a[1] = b[1]; }, groupClone: function(a) { return [a[0], a[1]]; }, preventDefaults: function(e, selection) { if(!e) { e = window.event; } if(e.preventDefault) { e.preventDefault(); } e.returnValue = false; if(selection && document.selection) { document.selection.empty(); } }, cancelEvent: function(e) { if(!e) { e = window.event; } if(e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } }; /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.1.3 * * Requires: 1.2.2+ */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })); })(jQuery, window, Handsontable); // numeral.js // version : 1.4.7 // author : Adam Draper // license : MIT // http://adamwdraper.github.com/Numeral-js/ (function () { /************************************ Constants ************************************/ var numeral, VERSION = '1.4.7', // internal storage for language config files languages = {}, currentLanguage = 'en', zeroFormat = null, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports); /************************************ Constructors ************************************/ // Numeral prototype object function Numeral (number) { this._n = number; } /** * Implementation of toFixed() that treats floats more like decimals * * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present * problems for accounting- and finance-related software. */ function toFixed (value, precision, optionals) { var power = Math.pow(10, precision), output; // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (Math.round(value * power) / power).toFixed(precision); if (optionals) { var optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } /************************************ Formatting ************************************/ // determine what type of formatting we need to do function formatNumeral (n, format) { var output; // figure out what kind of format we are dealing with if (format.indexOf('$') > -1) { // currency!!!!! output = formatCurrency(n, format); } else if (format.indexOf('%') > -1) { // percentage output = formatPercentage(n, format); } else if (format.indexOf(':') > -1) { // time output = formatTime(n, format); } else { // plain ol' numbers or bytes output = formatNumber(n, format); } // return string return output; } // revert to number function unformatNumeral (n, string) { if (string.indexOf(':') > -1) { n._n = unformatTime(string); } else { if (string === zeroFormat) { n._n = 0; } else { var stringOriginal = string; if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false; for (var power = 0; power <= prefixes.length; power++) { bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._n = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, '')); // round if we are talking about bytes n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n; } } return n._n; } function formatCurrency (n, format) { var prependSymbol = (format.indexOf('$') <= 1) ? true : false; // remove $ for the moment var space = ''; // check for space before or after currency if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } // format the number var output = formatNumeral(n, format); // position the symbol if (prependSymbol) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); output.splice(1, 0, languages[currentLanguage].currency.symbol + space); output = output.join(''); } else { output = languages[currentLanguage].currency.symbol + space + output; } } else { if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + languages[currentLanguage].currency.symbol); output = output.join(''); } else { output = output + space + languages[currentLanguage].currency.symbol; } } return output; } function formatPercentage (n, format) { var space = ''; // check for space before % if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } n._n = n._n * 100; var output = formatNumeral(n, format); if (output.indexOf(')') > -1 ) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime (n, format) { var hours = Math.floor(n._n/60/60), minutes = Math.floor((n._n - (hours * 60 * 60))/60), seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime (string) { var timeArray = string.split(':'), seconds = 0; // turn hours and minutes into seconds and add them all up if (timeArray.length === 3) { // hours seconds = seconds + (Number(timeArray[0]) * 60 * 60); // minutes seconds = seconds + (Number(timeArray[1]) * 60); // seconds seconds = seconds + Number(timeArray[2]); } else if (timeArray.lenght === 2) { // minutes seconds = seconds + (Number(timeArray[0]) * 60); // seconds seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber (n, format) { var negP = false, optDec = false, abbr = '', bytes = '', ord = '', abs = Math.abs(n._n); // check if number is zero and a custom zero format has been set if (n._n === 0 && zeroFormat !== null) { return zeroFormat; } else { // see if we should use parentheses for negative number if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } // see if abbreviation is wanted if (format.indexOf('a') > -1) { // check for space before abbreviation if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12)) { // trillion abbr = abbr + languages[currentLanguage].abbreviations.trillion; n._n = n._n / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) { // billion abbr = abbr + languages[currentLanguage].abbreviations.billion; n._n = n._n / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) { // million abbr = abbr + languages[currentLanguage].abbreviations.million; n._n = n._n / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) { // thousand abbr = abbr + languages[currentLanguage].abbreviations.thousand; n._n = n._n / Math.pow(10, 3); } } // see if we are formatting bytes if (format.indexOf('b') > -1) { // check for space before if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max; for (var power = 0; power <= prefixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power+1); if (n._n >= min && n._n < max) { bytes = bytes + prefixes[power]; if (min > 0) { n._n = n._n / min; } break; } } } // see if ordinal is wanted if (format.indexOf('o') > -1) { // check for space before if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(n._n); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } var w = n._n.toString().split('.')[0], precision = format.split('.')[1], thousands = format.indexOf(','), d = '', neg = false; if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length); } else { d = toFixed(n._n, precision.length); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d) === 0) { d = ''; } } else { w = toFixed(n._n, null); } // format number if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } /************************************ Top Level Functions ************************************/ numeral = function (input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (!Number(input)) { input = 0; } return new Numeral(Number(input)); }; // version number numeral.version = VERSION; // compare numeral object numeral.isNumeral = function (obj) { return obj instanceof Numeral; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. numeral.language = function (key, values) { if (!key) { return currentLanguage; } if (key && !values) { currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; numeral.language('en', { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; }, currency: { symbol: '$' } }); numeral.zeroFormat = function (format) { if (typeof(format) === 'string') { zeroFormat = format; } else { zeroFormat = null; } }; /************************************ Helpers ************************************/ function loadLanguage(key, values) { languages[key] = values; } /************************************ Numeral Prototype ************************************/ numeral.fn = Numeral.prototype = { clone : function () { return numeral(this); }, format : function (inputString) { return formatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, unformat : function (inputString) { return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, value : function () { return this._n; }, valueOf : function () { return this._n; }, set : function (value) { this._n = Number(value); return this; }, add : function (value) { this._n = this._n + Number(value); return this; }, subtract : function (value) { this._n = this._n - Number(value); return this; }, multiply : function (value) { this._n = this._n * Number(value); return this; }, divide : function (value) { this._n = this._n / Number(value); return this; }, difference : function (value) { var difference = this._n - Number(value); if (difference < 0) { difference = -difference; } return difference; } }; /************************************ Exposing Numeral ************************************/ // CommonJS module is defined if (hasModule) { module.exports = numeral; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `numeral` as a global object via a string identifier, // for Closure Compiler 'advanced' mode this['numeral'] = numeral; } /*global define:false */ if (typeof define === 'function' && define.amd) { define([], function () { return numeral; }); } }).call(this);
src/cms/preview-templates/IndexPagePreview.js
njosieb/ecocentrixco
import PropTypes from 'prop-types' import React from 'react' import { IndexPageTemplate } from '../../templates/index-page' const IndexPagePreview = ({ entry }) => ( <IndexPageTemplate headerImage={entry.getIn(['data', 'headerImage'])} headerText={entry.getIn(['data', 'headerText'])} headerSubtext={entry.getIn(['data', 'headerSubtext'])} servicesList={entry.getIn(['data', 'servicesList'])} statsList={entry.getIn(['data', 'statsList'])} certifications={entry.getIn(['data', 'certifications'])} /> ) IndexPagePreview.propTypes = { entry: PropTypes.shape({ getIn: PropTypes.func }) } export default IndexPagePreview
node_modules/react-icons/md/bluetooth-audio.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdBluetoothAudio = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m21.5 27.2l-3.1-3.2v6.3z m-3.1-17.5v6.3l3.1-3.2z m7.8 3.1l-7.2 7.2 7.2 7.2-9.6 9.4h-1.6v-12.6l-7.7 7.6-2.3-2.3 9.3-9.3-9.3-9.3 2.3-2.3 7.7 7.6v-12.6h1.6z m6.4-1.6q2.4 3.9 2.4 8.6t-2.6 8.9l-1.9-2q1.6-3.3 1.6-6.7t-1.6-6.7z m-8.8 8.8l3.8-3.8q0.8 1.9 0.8 3.8 0 2-0.8 3.9z"/></g> </Icon> ) export default MdBluetoothAudio
ajax/libs/ember-data.js/1.0.0-beta.5/ember-data.prod.js
hanssens/cdnjs
/*! * @overview Ember Data * @copyright Copyright 2011-2014 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 1.0.0-beta.5 */ (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod, deps, callback, reified , exports; mod = registry[name]; if (!mod) { throw new Error("Module '" + name + "' not found."); } deps = mod.deps; callback = mod.callback; reified = []; exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.5' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.5' }); if ('undefined' !== typeof window) { window.DS = DS; } if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; // Simple dispatcher to support overriding the aliased // method in subclasses. function aliasMethod(methodName) { return function() { return this[methodName].apply(this, arguments); }; } /** In Ember Data a Serializer is used to serialize and deserialize records when they are transfered in and out of an external source. This process involves normalizing property names, transforming attribute values and serializeing relationships. For maximum performance Ember Data recomends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ DS.JSONSerializer = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` propery to store the id of the record. The external source may not always follow this convention. In these cases it is usesful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.applyTransforms(type, hash); return hash; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all you attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var attrs = get(this, 'attrs'); var value = get(record, key), type = attribute.type; if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); json[key] = value; }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; if (isNone(belongsTo)) { json[key] = belongsTo; } else { json[key] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[key] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "_type"] = belongsTo.constructor.typeKey; } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method deletegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindAll: aliasMethod('extractArray'), /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindQuery: aliasMethod('extractArray'), /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindMany: aliasMethod('extractArray'), /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindHasMany: aliasMethod('extractArray'), /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractCreateRecord: aliasMethod('extractSave'), /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractUpdateRecord: aliasMethod('extractSave'), /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractDeleteRecord: aliasMethod('extractSave'), /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFind: aliasMethod('extractSingle'), /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFindBelongsTo: aliasMethod('extractSingle'), /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSave: aliasMethod('extractSingle'), /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractArray: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ /** `keyForRelationship` can be used to define a custom key when serializeing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); return transform; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ DS.DebugAdapter = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== DS.Model && DS.Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0, columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = [], keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this, keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); })(); (function() { /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), optionsArray: attr('raw') }); ``` @class Transform @namespace DS */ DS.Transform = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @return The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: Ember.required() }); })(); (function() { /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ DS.BooleanTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); })(); (function() { /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ DS.DateTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } }); })(); (function() { var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ DS.NumberTransform = DS.Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); })(); (function() { var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ DS.StringTransform = DS.Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); })(); (function() { })(); (function() { /** @module ember-data */ var set = Ember.set; /* This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store || DS.Store); application.register('serializer:_default', DS.JSONSerializer); application.register('serializer:_rest', DS.RESTSerializer); application.register('adapter:_rest', DS.RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "transforms", before: "store", initialize: function(container, application) { application.register('transform:boolean', DS.BooleanTransform); application.register('transform:date', DS.DateTransform); application.register('transform:number', DS.NumberTransform); application.register('transform:string', DS.StringTransform); } }); Application.initializer({ name: "dataAdapter", before: "store", initialize: function(container, application) { application.register('dataAdapter:main', DS.DebugAdapter); } }); Application.initializer({ name: "injectStore", before: "store", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); application.inject('serializer', 'store', 'store:main'); application.inject('dataAdapter', 'store', 'store:main'); } }); }); })(); (function() { /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); store.fetchAll(type, this); }, /** Adds a record to the `RecordArray`. @method addRecord @private @param {DS.Model} record */ addRecord: function(record) { get(this, 'content').addObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all(App.Message); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return DS.PromiseArray.create({ promise: promise }); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ DS.FilteredRecordArray = DS.RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ updateFilter: Ember.observer(function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'), type = get(this, 'type'), records = store.pushMany(type, data), meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: meta }); // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The property name of the relationship @property {String} name @private */ name: null, /** The record to which this relationship belongs. @property {DS.Model} owner @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method fetch @private */ fetch: function() { var records = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'), resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type')); var unloadedRecords = records.filterProperty('isEmpty', true); store.fetchMany(unloadedRecords, owner, resolver); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); this._changesToSync.clear(); } }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); })(); (function() { /** @module ember-data */ })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var resolve = Ember.RSVP.resolve; var copy = Ember.copy; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript var person = store.find('person', 123); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript var person = store.find(App.Person, 123); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. @class Store @namespace DS @extends Ember.Object */ DS.Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = DS.RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '_rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @returns DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:_rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @returns {DS.Model} record */ createRecord: function(type, properties) { type = this.modelFor(type); properties = copy(properties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @returns {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deletedRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find(App.Person, { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @return {Promise} promise */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Promise} promise */ findById: function(type, id) { type = this.modelFor(type); var record = this.recordForId(type, id); var promise = this.fetchRecord(record) || resolve(record, "DS: Store#findById " + type + " with id: " + id); return promiseObject(promise); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @returns {Promise} promise */ findByIds: function(type, ids) { var store = this; var promiseLabel = "DS: Store#findByIds " + type; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @returns {Promise} promise */ fetchRecord: function(record) { if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } if (!get(record, 'isEmpty')) { return null; } var type = record.constructor, id = get(record, 'id'); var adapter = this.adapterFor(type); var promise = _find(adapter, this, type, id); record.loadingData(promise); return promise; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null. ```js var post = store.getById('post', 1); ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @param {DS.Model} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterFor(type), id = get(record, 'id'); return _find(adapter, this, type, id); }, /** This method takes a list of records, groups the records by type, converts the records into IDs, and then invokes the adapter's `findMany` method. The records are grouped by type to invoke `findMany` on adapters for each unique type in records. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes. @method fetchMany @private @param {Array} records @param {DS.Model} owner @param {Resolver} resolver */ fetchMany: function(records, owner, resolver) { if (!records.length) { return; } // Group By Type var recordsByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(records, function(record) { recordsByTypeMap.get(record.constructor).push(record); }); forEach(recordsByTypeMap, function(type, records) { var ids = records.mapProperty('id'), adapter = this.adapterFor(type); resolver.resolve(_findMany(adapter, this, type, ids, owner)); }, this); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {Boolean} */ hasRecordForId: function(type, id) { id = coerceId(id); type = this.modelFor(type); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {DS.Model} record */ recordForId: function(type, id) { type = this.modelFor(type); id = coerceId(id); var record = this.typeMapFor(type).idToRecord[id]; if (!record) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(owner, records, type, resolver) { type = this.modelFor(type); records = Ember.A(records); var unloadedRecords = records.filterProperty('isEmpty', true), manyArray = this.recordArrayManager.createManyArray(type, records); forEach(unloadedRecords, function(record) { record.loadingData(); }); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); this.fetchMany(unloadedRecords, owner, resolver); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); Ember.run.once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); resolver.resolve(_findHasMany(adapter, this, owner, link, relationship)); return records; }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @param {Resolver} resolver */ findBelongsTo: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); resolver.resolve(_findBelongsTo(adapter, this, owner, link, relationship)); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(type, query) { type = this.modelFor(type); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type), promiseLabel = "DS: Store#findQuery " + type, resolver = Ember.RSVP.defer(promiseLabel); resolver.resolve(_findQuery(adapter, this, type, query, array)); return promiseArray(resolver.promise); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { type = this.modelFor(type); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @returns {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var local_posts = store.all(App.Post); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll(App.Post); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), records = typeMap.records, record; while(record = records.pop()) { record.unloadRecord(); } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter(App.Post, {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPosts.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; // allow an optional server query if (arguments.length === 3) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); var array = this.recordArrayManager .createFilteredRecordArray(type, filter); promise = promise || resolve(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded(App.Post, 1); // false store.find(App.Post, 1).then(function() { store.recordIsLoaded(App.Post, 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1], adapter = this.adapterFor(record.constructor), operation; if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'), id = coerceId(data.id); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: {}, records: [], metadata: {} }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id), record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @returns {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { var normalizedKey = this.container.normalize('model:' + key); factory = this.container.lookupFactory(normalizedKey); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = normalizedKey.split(':', 2)[1]; } else { // A factory already supplied. factory = key; } factory.store = this; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @returns {DS.Model} the record that was created or updated. */ push: function(type, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. type = this.modelFor(type); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. The data will be automatically deserialized using the serializer for the `type` param. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload('post', pushData); ``` @method pushPayload @param {String} type @param {Object} payload @return {DS.Model} the record that was created or updated. */ pushPayload: function (type, payload) { var serializer; if (!payload) { payload = type; serializer = defaultSerializer(this.container); } else { serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, update: function(type, data) { return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(type, metadata) { type = this.modelFor(type); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @returns {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type), idToRecord = typeMap.idToRecord; // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor, typeMap = this.typeMapFor(type), id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId, parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId, parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @returns DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind, value = data[key]; if (value == null) { return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); addUnsavedRecords(record, key, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (isNone(id) || id instanceof DS.Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // If there are any unsaved records that are in a hasMany they won't be // in the payload, so add them back in manually. function addUnsavedRecords(record, key, data) { if(record) { data.pushObjects(record.get(key).filterBy('isNew')); } } // Delegation to the adapter and promise management /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ DS.PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise) { return DS.PromiseObject.create({ promise: promise }); } function promiseArray(promise) { return DS.PromiseArray.create({ promise: promise }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:_default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:_default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer, defaultSerializer = adapter.defaultSerializer, container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _find(adapter, store, type, id) { var promise = adapter.find(store, type, id), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#find of " + type + " with id: " + id).then(function(payload) { payload = serializer.extract(store, type, payload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); record.notFound(); throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, owner) { var promise = adapter.findMany(store, type, ids, owner), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findMany of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findMany'); store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findHasMany'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findAll of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findAll'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findQuery of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findQuery'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor, promise = adapter[operation](store, type, record), serializer = serializerForAdapter(adapter, type); return promise.then(function(payload) { if (payload) { payload = serializer.extract(store, type, payload, get(record, 'id'), operation); } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof DS.InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, "DS: Extract and notify about " + operation + " completion of " + record); } })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What we mean is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ var hasDefinedProperties = function(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didSetProperty = function(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); }; // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store askes // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes, isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); } } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); DS.RootState = RootState; })(); (function() { var get = Ember.get, isEmpty = Ember.isEmpty; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ DS.Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute @method errorsFor @param {String} attribute @returns {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return Ember.makeArray(messages).map(function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. @method has @param {String} attribute @returns {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, merge = Ember.merge, once = Ember.run.once; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ DS.Model = Ember.Object.extend(Ember.Evented, { /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store askes the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord(App.Model); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.set('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord(App.Model); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDeleted'); // false record.deleteRecord(); record.get('isDeleted'); // true ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord(App.Model); record.get('isNew'); // true store.find('model', 1).then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when no client-side validations have failed and the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord(App.Model); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend. This may also result in the record having its `isValid` property become false if the adapter reported that server-side validations failed. Example ```javascript record.get('isError'); // false record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord(App.Model); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, transaction: null, /** @property currentState @private @type {Object} */ currentState: null, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys coresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {Object} */ errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @returns {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = DS.JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).property(), _data: null, init: function() { set(this, 'currentState', DS.RootState.empty); var errors = DS.Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); set(this, 'errors', errors); this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = name.split(".", 1), currentState = get(this, 'currentState'), state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = name.split("."); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.get('model').deleteRecord(); }, confirm: function() { this.get('model').save(); }, undo: function() { this.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; this.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[relationship.name]; if (hasMany) { hasMany.clear(); } } }, this); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { get(this, 'store').dataWasUpdated(this.constructor, this); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'), newData = get(this, '_attributes'), diffData = {}, prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { Ember.run.once(this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** @method updateHasMany @private @param {String} name @param {Array} records */ updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, /** @method updateBelongsTo @private @param {String} name @param {DS.Model} record */ updateBelongsTo: function(name, record) { this._data[name] = record; }, /** If the model `isDirty` this function will which discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record and persist any changes to the record to an extenal source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return DS.PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Ember.RSVP.Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags"); return DS.PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { this._deferredTriggers.push(arguments); once(this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l=this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers = []; } }); DS.Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: DS.Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ DS.Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { meta.name = name; map.set(name, meta); } }); return map; }), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a tring contrining the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); DS.Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue(); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](DS.Transform.html). `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value) { if (arguments.length > 1) { var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key]; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); this._attributes[key] = value; return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ /** An AttributeChange object is created whenever a record's attribute changes value. It is used to track changes to a record between transaction commits. @class AttributeChange @namespace DS @private @constructor */ var AttributeChange = DS.AttributeChange = function(options) { this.record = options.record; this.store = options.store; this.name = options.name; this.value = options.value; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { if (this.value !== this.oldValue) { this.record.send('becomeDirty'); this.record.updateRecordArraysLater(); } // TODO: Use this object in the commit process this.destroy(); }, /** If the AttributeChange is destroyed (either by being rolled back or being committed), remove it from the list of pending changes on the record. @method destroy */ destroy: function() { delete this.record._changesToSync[this.name]; } }; })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @construtor */ DS.RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @construtor */ DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; /** @class RelationshipChangeRemove @namespace DS @private @construtor */ DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && childRecord) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); // the object is a value, and not a promise function isValue(object) { return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); } DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.addObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.addObject(secondRecord); } }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.removeObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.removeObject(secondRecord); } }); } } this.coalesce(); }; })(); (function() { /** @module ember-data */ })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), promiseLabel = "DS: Async belongsTo " + this + " : " + key; if (arguments.length === 2) { return value === undefined ? null : DS.PromiseObject.create({ promise: Ember.RSVP.resolve(value, promiseLabel) }); } var link = data.links && data.links[key], belongsTo = data[key]; if(!isNone(belongsTo)) { var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo, promiseLabel); return DS.PromiseObject.create({ promise: promise}); } else if (link) { var resolver = Ember.RSVP.defer("DS: Async belongsTo (link) " + this + " : " + key); store.findBelongsTo(this, link, meta, resolver); return DS.PromiseObject.create({ promise: resolver.promise }); } else { return null; } }).property('data').meta(meta); } /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.belongsTo = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.fetchRecord(belongsTo); return belongsTo; }).property('data').meta(meta); }; /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ DS.Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); change.sync(); } } delete this._changesToSync[key]; }) }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; function asyncHasMany(type, options, meta) { return Ember.computed(function(key, value) { var relationship = this._relationships[key], promiseLabel = "DS: Async hasMany " + this + " : " + key; if (!relationship) { var resolver = Ember.RSVP.defer(promiseLabel); relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; var rel; if (link) { rel = store.findHasMany(this, link, meta, resolver); } else { rel = store.findMany(this, data[key], meta.type, resolver); } // cache the promise so we can use it // when we come back and don't need to rebuild // the relationship. set(rel, 'promise', resolver.promise); return rel; }); } var promise = relationship.get('promise').then(function() { return relationship; }, null, "DS: Async hasMany records received"); return DS.PromiseArray.create({ promise: promise }); }).property('data').meta(meta); } function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'), store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } function hasRelationship(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; if (options.async) { return asyncHasMany(type, options, meta); } return Ember.computed(function(key, value) { return buildRelationship(this, key, options, function(store, data) { var records = data[key]; return store.findMany(this, data[key], meta.type); }); }).property('data').meta(meta); } /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.hasMany = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } return hasRelationship(type, options); }; })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ DS.Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = this.store.modelFor(meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || this.store.modelFor(type); } if (!types.contains(type)) { types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (!type && meta.kind === 'hasMany') { type = Ember.String.singularize(name); } else if (!type) { type = name; } if (typeof type === 'string') { meta.type = this.store.modelFor(type); } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ DS.RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; }, recordDidChange: function(record) { this.changedRecords.push(record); once(this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords = []; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, _recordWasChanged: function (record) { var type = record.constructor, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { recordArrays.add(array); array.addRecord(record); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = DS.ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = DS.RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter) { var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { return DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store }); }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` @class InvalidError @namespace DS */ DS.InvalidError = function(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } }; DS.InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: ```javascript App.MyAdapter = DS.Adapter.extend({ // ...your code here }); ``` To tell your store which adapter to use, set its `adapter` property: ```javascript App.store = DS.Store.create({ adapter: App.MyAdapter.create() }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ DS.Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority then a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** Find multiple records at once. By default, it loops over the provided ids and calls `find` on each. May be overwritten to improve performance and reduce the number of server requests. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findMany: function(store, type, ids) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, {ids: ids}).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var promises = map.call(ids, function(id) { return this.find(store, type, id); }, this); return Ember.RSVP.all(promises); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, fmt = Ember.String.fmt, indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ DS.FixtureAdapter = DS.Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.deleteLoadedFixture(type, fixture); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(callback.call(context)); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; function coerceId(id) { return id == null ? null : id+''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to defined across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ DS.RESTSerializer = DS.JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implemention makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } return this._super(type, hash, prop); }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ normalizePayload: function(type, payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {subclass of DS.Model} type @param {Object} hash @returns {Object} the normalized payload */ normalizePayload: function(type, payload) { return payload; }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = attrs[key]; if (payloadKey && payloadKey.key) { payloadKey = payloadKey.key; } if (typeof payloadKey === 'string') { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id, requestType) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String} id @param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType @returns {Object} the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId, requestType) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop), isPrimary = typeName === primaryTypeName; // legacy support for singular resources if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) { primaryRecord = this.normalize(primaryType, payload[prop], prop); continue; } var type = store.modelFor(typeName); /*jshint loopfunc:true*/ forEach.call(payload[prop], function(hash) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord, isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload, id, requestType) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; } payload = { comments: comments, posts: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType @returns {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryArray; for (var prop in payload) { var typeKey = prop, forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type), isPrimary = (!forcedSecondary && (typeName === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, payload) { payload = this.normalizePayload(null, payload); for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return this.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** You can use this method to normalize the JSON root keys returned into the model type expected by your store. For example, your server may return underscored root keys rather than the expected camelcased versions. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); } }); ``` @method typeForRoot @param {String} root @returns {String} the model's typeKey */ typeForRoot: function(root) { return Ember.String.singularize(root); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends camelized root keys. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "Type"] = belongsTo.constructor.typeKey; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```js DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ DS.RESTAdapter = DS.Adapter.extend({ defaultSerializer: '_rest', /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```javascript DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the querystring. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @returns {Promise} promise */ find: function(store, type, id) { return this.ajax(this.buildURL(type.typeKey, id), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @returns {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @returns {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as IDs. For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @returns {Promise} promise */ findMany: function(store, type, ids) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findHasMany: function(store, record, url) { var host = get(this, 'host'), id = get(record, 'id'), type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @returns {String} url */ buildURL: function(type, id) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } if (id) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'), namespace = get(this, 'namespace'), url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js DS.RESTAdapter.reopen({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }; }); ``` @method pathForType @param {String} type @returns {String} path **/ pathForType: function(type) { return Ember.String.pluralize(type); }, /** Takes an ajax response, and returns a relavant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @return {Object} jqXHR */ ajaxError: function(jqXHR) { if (jqXHR) { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE ect. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = adapter.ajaxOptions(url, type, hash); hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }, "DS: RestAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE ect. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, hash) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } if (this.headers !== undefined) { var headers = this.headers; hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); })(); (function() { /** @module ember-data */ })(); (function() { DS.Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); })(); (function() { /** @module ember-data */ })(); (function() { /** Ember Data @module ember-data @main ember-data */ })(); (function() { Ember.String.pluralize = function(word) { return Ember.Inflector.inflector.pluralize(word); }; Ember.String.singularize = function(word) { return Ember.Inflector.inflector.singularize(word); }; })(); (function() { var BLANK_REGEX = /^\s*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow') //=> 'kine' inflector.singularize('kine') //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice') // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice') // => 'advice' inflector.pluralize('formula') // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula') // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || {}; ruleSet.irregularPairs = ruleSet.irregularPairs || {}; var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: {}, irregularInverse: {}, uncountable: {} }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); } Inflector.prototype = { /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, isBlank, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); if (isBlank) { return word; } lowercase = word.toLowerCase(); isUncountable = this.rules.uncountable[lowercase]; if (isUncountable) { return word; } isIrregular = irregular && irregular[lowercase]; if (isIrregular) { return isIrregular; } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; Ember.Inflector = Inflector; })(); (function() { Ember.Inflector.defaultRules = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; })(); (function() { if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return Ember.String.pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return Ember.String.singularize(this); }; } })(); (function() { Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules); })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; DS.ActiveModelSerializer = DS.RESTSerializer.extend({ // SERIALIZE /** Converts camelcased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @returns String */ keyForAttribute: function(attr) { return Ember.String.decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @returns String */ keyForRelationship: function(key, kind) { key = Ember.String.decamelize(key); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return Ember.String.singularize(key) + "_ids"; } else { return key; } }, /** Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute(key); json[key + "_type"] = Ember.String.capitalize(belongsTo.constructor.typeKey); }, // EXTRACT /** Extracts the model typeKey from underscored root objects. @method typeForRoot @param {String} root @returns String the model's typeKey */ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); }, /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} hash */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = Ember.String.camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, payload; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); })(); (function() { var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; /** The EmbeddedRecordsMixin allows you to add embedded record support to your serializers. To set up embedded records, you include the mixin into the serializer and then define your embedded relations. ```js App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` Currently only `{embedded: 'always'}` records are supported. @class EmbeddedRecordsMixin @namespace DS */ DS.EmbeddedRecordsMixin = Ember.Mixin.create({ /** Serialize has-may relationship when it is configured as embedded objects. @method serializeHasMany */ serializeHasMany: function(record, json, relationship) { var key = relationship.key, attrs = get(this, 'attrs'), embed = attrs && attrs[key] && attrs[key].embedded === 'always'; if (embed) { json[this.keyForAttribute(key)] = get(record, key).map(function(relation) { var data = relation.serialize(), primaryKey = get(this, 'primaryKey'); data[primaryKey] = get(relation, primaryKey); return data; }, this); } }, /** Extract embedded objects out of the payload for a single object and add them as sideloaded objects instead. @method extractSingle */ extractSingle: function(store, primaryType, payload, recordId, requestType) { var root = this.keyForAttribute(primaryType.typeKey), partial = payload[root]; updatePayloadWithEmbedded(store, this, primaryType, partial, payload); return this._super(store, primaryType, payload, recordId, requestType); }, /** Extract embedded objects out of a standard payload and add them as sideloaded objects instead. @method extractArray */ extractArray: function(store, type, payload) { var root = this.keyForAttribute(type.typeKey), partials = payload[Ember.String.pluralize(root)]; forEach(partials, function(partial) { updatePayloadWithEmbedded(store, this, type, partial, payload); }, this); return this._super(store, type, payload); } }); function updatePayloadWithEmbedded(store, serializer, type, partial, payload) { var attrs = get(serializer, 'attrs'); if (!attrs) { return; } type.eachRelationship(function(key, relationship) { var expandedKey, embeddedTypeKey, attribute, ids, config = attrs[key], serializer = store.serializerFor(relationship.type.typeKey), primaryKey = get(serializer, "primaryKey"); if (relationship.kind !== "hasMany") { return; } if (config && (config.embedded === 'always' || config.embedded === 'load')) { // underscore forces the embedded records to be side loaded. // it is needed when main type === relationship.type embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey); expandedKey = this.keyForRelationship(key, relationship.kind); attribute = this.keyForAttribute(key); ids = []; if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; forEach(partial[attribute], function(data) { var embeddedType = store.modelFor(relationship.type.typeKey); updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload); ids.push(data[primaryKey]); payload[embeddedTypeKey].push(data); }); partial[expandedKey] = ids; delete partial[attribute]; } }, serializer); } })(); (function() { /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelcasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.Adapter **/ DS.ActiveModelAdapter = DS.RESTAdapter.extend({ defaultSerializer: '_ams', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @returns String */ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param jqXHR @returns error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"], errors = {}; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); return new DS.InvalidError(errors); } else { return error; } } }); })(); (function() { })(); (function() { Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "activeModelAdapter", initialize: function(container, application) { application.register('serializer:_ams', DS.ActiveModelSerializer); application.register('adapter:_ams', DS.ActiveModelAdapter); } }); }); })(); (function() { })(); })(); if (typeof location !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) { Ember.Logger.warn("You are running a production build of Ember on localhost and won't receive detailed error messages. "+ "If you want full error messages please use the non-minified build provided on the Ember website."); }
src/svg-icons/communication/stay-current-portrait.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentPortrait = (props) => ( <SvgIcon {...props}> <path d="M17 1.01L7 1c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/> </SvgIcon> ); CommunicationStayCurrentPortrait = pure(CommunicationStayCurrentPortrait); CommunicationStayCurrentPortrait.displayName = 'CommunicationStayCurrentPortrait'; CommunicationStayCurrentPortrait.muiName = 'SvgIcon'; export default CommunicationStayCurrentPortrait;
WebNceeMVC/packages/jQuery.1.10.2/Content/Scripts/jquery-1.10.2.js
JulienMinato/WxNcee
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * NUGET: END LICENSE TEXT */ /*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
src/constant.js
asfor/Speech-draft
import React from 'react' const imagePath = './images/' export const backgroundColor = ['blue', 'red', 'green', 'yellow'] export const homepageTitle = 'Programming Language' export const wavesClassName = 'waves' const iconNames = ['java', 'c++', 'js', 'php', 'python', 'swift'] export const startPages = [( <div> <p> We all knows a lot of languages in the past, such as English, French, Japanese and ...Hokkienese. But today, we&apos;re going to talk about another language - programming language. </p> <ul id='icons'> {iconNames.map((name, index) => { return <li key={index}><img src={imagePath + name + '.jpg'} /></li> })} </ul> </div> ),( <div className='start-2'> <p> The language we use in common is called natural language. As we all know, the function of natural language is to transfer information between people. </p> <div> <img src={imagePath + 'start_2_1' + '.png'} /> </div> </div> ),( <div className='start-3'> <p> By contrast, the communication between people and machines is by programming language. </p> </div> )] export const categoryPages = [( <div> <p> Same as natural language, programming languages are also divided into many types, according to the design of thinking to divide, it can be divided into two kinds: imperative and functional. </p> </div> ),( <div> <p> These two kinds of thinking are derived from math, and they are the prototype of Turing Machine and λ calculus. </p> </div> ),( <div> <p> The difference between them is that imperative focus on description of &quot;how to do&quot;, and the functional focus on description of &quot;what to do&quot;. </p> </div> ),( <div> <p> From the other point of view, they are like oil painting and traditional Chinese painting, a focus on &quot;shape&quot;, a focus on &quot;meaning&quot;. </p> </div> )] export const developmentPages = [( <div> <p> In the competition and development of the last century, because of cost and technology, imperative completely defeated the functional, and thus derived from the &quot;Object-Oriented&quot;, a thought that helps us to describe the world, Everyone is familiar with the Java and C++ belongs to it. </p> </div> ),( <div> <p> Although the command style ruled for a long time, but with the development of times, its own defects are slowly exposed out, the functional again slowly back to the people&apos;s sight. </p> </div> ),( <div> <p> But this time, they are not the opposition, people began to try to combine them, to play out their advantages. Such as Python and JavaScript is like this. </p> </div> )] export const endPages = [( <div> <p> To this day, they have been infiltrating each other, and continue to develop, maybe this is the history of the development of things. </p> </div> ),( <div> <h1>Thanks!</h1> </div> )]
react-router-tutorial/lessons/03-navigating-with-link/index.js
zerotung/practices-and-notes
import React from 'react' import { render } from 'react-dom' import { Router, Route, hashHistory } from 'react-router' import App from './modules/App' import About from './modules/About' import Repos from './modules/Repos' render(( <Router history={hashHistory}> <Route path="/" component={App}/> <Route path="/repos" component={Repos}/> <Route path="/about" component={About}/> </Router> ), document.getElementById('app'))
docs/src/examples/elements/List/Variations/ListExampleHorizontal.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Image, List } from 'semantic-ui-react' const ListExampleHorizontal = () => ( <List horizontal> <List.Item> <Image avatar src='/images/avatar/small/tom.jpg' /> <List.Content> <List.Header>Tom</List.Header> Top Contributor </List.Content> </List.Item> <List.Item> <Image avatar src='/images/avatar/small/christian.jpg' /> <List.Content> <List.Header>Christian Rocha</List.Header> Admin </List.Content> </List.Item> <List.Item> <Image avatar src='/images/avatar/small/matt.jpg' /> <List.Content> <List.Header>Matt</List.Header> Top Rated User </List.Content> </List.Item> </List> ) export default ListExampleHorizontal
src/client/vr/writeScenetoDOM.js
ragingsquirrel3/vrdb
import React, { Component } from 'react'; import { render } from 'react-dom'; class AFrameScene extends Component { render() { return <a-entity dangerouslySetInnerHTML={{ __html: this.props.html }} />; } } export default function writeSceneToDOM (_html) { render(<AFrameScene html={_html} />, document.getElementById('dynamicTarget')); }
packages/material-ui-icons/src/SubscriptionsRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M19 8H5c-.55 0-1-.45-1-1s.45-1 1-1h14c.55 0 1 .45 1 1s-.45 1-1 1zm-2-6H7c-.55 0-1 .45-1 1s.45 1 1 1h10c.55 0 1-.45 1-1s-.45-1-1-1zm5 10v8c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2v-8c0-1.1.9-2 2-2h16c1.1 0 2 .9 2 2zm-6.81 3.56L10 12.73v6.53l5.19-2.82c.35-.19.35-.69 0-.88z" /> , 'SubscriptionsRounded');
src/js/index.js
elliotaplant/celestial-dance
import 'aframe'; import 'aframe-extras'; import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import SpaceScene from './components/SpaceScene'; import Sidebar from './components/Sidebar'; ReactDOM.render(<Sidebar/>, document.querySelector('.sidebar-container')); ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container')); const scene = document.getElementsByTagName('a-scene')[0]; const xButton = document.getElementById('close-sidebar'); const hamburgerIcon = document.getElementById('drawer-toggle-label'); function hideDrawer() { document.getElementById('drawer-toggle').checked = false; } function hideBurger() { hamburgerIcon.style.visibility = 'hidden'; } function showBurger() { hamburgerIcon.style.visibility = 'visible'; } function getPairCode(fullText) { var pairCode = ''; var betweenQuotes = false; for (var i = 0; i < fullText.length; i++) { if (fullText.charCodeAt(i) === 8221) { betweenQuotes = false; } if (betweenQuotes) { pairCode += fullText[i]; } if (fullText.charCodeAt(i) === 8220) { betweenQuotes = true; } } return pairCode; } function findPairCode() { var overlay = document.getElementsByClassName('overlay'); if (overlay.length) { var pairCode = getPairCode(overlay[0].textContent); document.getElementById('pair-code').textContent = 'Pair Code: "' + pairCode + '"'; } else { setTimeout(findPairCode, 20); } } window.onload = findPairCode; scene.onmousedown = hideDrawer; scene.addEventListener('enter-vr', hideBurger, false); scene.addEventListener('exit-vr', showBurger, false); xButton.onmousedown = hideDrawer; xButton.onmouseover = () => { xButton.src = 'assets/x-icon-white.png' }; xButton.onmouseout = () => { xButton.src = 'assets/x-icon-grey.png' };
src/components/Navigation.js
flq/remorse
import React from 'react'; import { NavLink } from 'react-router-dom'; import './Navigation.css'; import GlobalCommands from "./GlobalCommands"; export default function Navigation() { return ( <nav> <NavLink to="/typing">Type text</NavLink> <NavLink to="/test-writing-morse">Test your writing skills</NavLink> <NavLink to="/test-reading-morse">Test your reading skills</NavLink> <NavLink to="/training-data">See your training data</NavLink> <GlobalCommands /> </nav> ); }
apps/test-suite/components/PlatformTouchable.js
exponent/exponent
import React from 'react'; import { TouchableHighlight } from 'react-native'; export default function PlatformTouchable(props) { return <TouchableHighlight underlayColor="lightgray" {...props} />; }
packages/material-ui-icons/lib/esm/TrackChangesTwoTone.js
mbrookes/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "m19.07 4.93-1.41 1.41C19.1 7.79 20 9.79 20 12c0 4.42-3.58 8-8 8s-8-3.58-8-8c0-4.08 3.05-7.44 7-7.93v2.02C8.16 6.57 6 9.03 6 12c0 3.31 2.69 6 6 6s6-2.69 6-6c0-1.66-.67-3.16-1.76-4.24l-1.41 1.41C15.55 9.9 16 10.9 16 12c0 2.21-1.79 4-4 4s-4-1.79-4-4c0-1.86 1.28-3.41 3-3.86v2.14c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V2h-1C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10c0-2.76-1.12-5.26-2.93-7.07z" }), 'TrackChangesTwoTone');
chrome/extension/newtab.js
aaggarwa88/AlwaysOn
import React from 'react' import Root from '../../app/containers/Root'; class AlwaysOn extends React.Component { constructor () { super() } render () { return <div> <Root /> </div> } } window.addEventListener('load', () => { React.render(<AlwaysOn />, document.querySelector('#reactApp')); });
assets/javascripts/kitten/components/layout/scrollable-container/stories.js
KissKissBankBank/kitten
import React from 'react' import { ScrollableContainer } from './index' import { COLORS } from 'kitten' import { DocsPage } from 'storybook/docs-page' export default { title: 'Layout/ScrollableContainer', component: ScrollableContainer, parameters: { docs: { page: () => ( <DocsPage filepath={__filename} importString="ScrollableContainer" /> ), }, }, args: { shadowColor: COLORS.background1, }, argTypes: { shadowColor: { name: 'shadowColor', control: { type: 'color', }, }, }, } export const Default = args => ( <ScrollableContainer {...args} style={{ backgroundColor: COLORS.line1 }}> <div style={{ height: '100px', lineHeight: '100px' }}> {'🚗 '.repeat(100)} </div> </ScrollableContainer> )
src/index.js
faalsh/react-materialize-demo
import React from 'react' import { render } from 'react-dom' import { Router, Route, browserHistory, IndexRoute } from 'react-router' import {Provider} from 'react-redux' import store from './store' import Layout from './containers/Layout/Layout.jsx' import Matches from './containers/Matches/Matches.jsx' import Repos from './containers/Repos/Repos.jsx' import Repo from './components/Repo/Repo.jsx' import {fetchSeasons} from './actions/leagueActions'; import Home from './containers/Home/Home.jsx' import './index.css' // import 'materialize-loader' import './favicon.ico' render(( <Provider store={store} > <Router history={browserHistory}> <Route path="/" component={Layout}> <IndexRoute component={Home}/> <Route path="/repos" component={Repos}> <Route path="/repos/:userName/:repoName" component={Repo}/> </Route> <Route path="/matches" component={Matches}> </Route> </Route> </Router> </Provider> ), document.getElementById('app'))
src/svg-icons/editor/insert-drive-file.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertDriveFile = (props) => ( <SvgIcon {...props}> <path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z"/> </SvgIcon> ); EditorInsertDriveFile = pure(EditorInsertDriveFile); EditorInsertDriveFile.displayName = 'EditorInsertDriveFile'; EditorInsertDriveFile.muiName = 'SvgIcon'; export default EditorInsertDriveFile;
app/react-icons/fa/barcode.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaBarcode extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m1.4 34.3h-1.4v-31.4h1.4v31.4z m1.4 0h-0.7v-31.4h0.7v31.4z m2.1 0h-0.7v-31.4h0.7v31.4z m3.5 0h-0.7v-31.4h0.7v31.4z m3.5 0h-1.4v-31.4h1.4v31.4z m2.8 0h-0.7v-31.4h0.7v31.4z m1.4 0h-0.7v-31.4h0.7v31.4z m1.4 0h-0.6v-31.4h0.6v31.4z m3.6 0h-1.5v-31.4h1.4v31.4z m3.5 0h-1.5v-31.4h1.5v31.4z m2.8 0h-1.4v-31.4h1.4v31.4z m2.8 0h-1.4v-31.4h1.4v31.4z m2.1 0h-1.4v-31.4h1.4v31.4z m4.2 0h-2.1v-31.4h2.1v31.4z m1.4 0h-0.7v-31.4h0.7v31.4z m2.1 0h-1.4v-31.4h1.4v31.4z"/></g> </IconBase> ); } }
test/specs/elements/Input/Input-test.js
koenvg/Semantic-UI-React
import cx from 'classnames' import _ from 'lodash' import React from 'react' import Input, { htmlInputPropNames } from 'src/elements/Input/Input' import { SUI } from 'src/lib' import * as common from 'test/specs/commonTests' import { sandbox } from 'test/utils' describe('Input', () => { common.isConformant(Input, { eventTargets: { // keyboard onKeyDown: 'input', onKeyPress: 'input', onKeyUp: 'input', // focus onFocus: 'input', onBlur: 'input', // form onChange: 'input', onInput: 'input', // mouse onClick: 'input', onContextMenu: 'input', onDrag: 'input', onDragEnd: 'input', onDragEnter: 'input', onDragExit: 'input', onDragLeave: 'input', onDragOver: 'input', onDragStart: 'input', onDrop: 'input', onMouseDown: 'input', onMouseEnter: 'input', onMouseLeave: 'input', onMouseMove: 'input', onMouseOut: 'input', onMouseOver: 'input', onMouseUp: 'input', // selection onSelect: 'input', // touch onTouchCancel: 'input', onTouchEnd: 'input', onTouchMove: 'input', onTouchStart: 'input', }, }) common.hasUIClassName(Input) common.rendersChildren(Input) common.implementsLabelProp(Input, { shorthandDefaultProps: elProps => ({ className: cx({ label: !_.includes(elProps.className, 'label'), }), }), }) common.implementsButtonProp(Input, { propKey: 'action', shorthandDefaultProps: elProps => ({ className: cx({ button: !_.includes(elProps.className, 'button'), }), }), }) common.implementsCreateMethod(Input) common.implementsHTMLInputProp(Input, { alwaysPresent: true, shorthandDefaultProps: { type: 'text' }, }) common.propKeyAndValueToClassName(Input, 'actionPosition', ['left'], { className: 'action' }) common.propKeyAndValueToClassName(Input, 'iconPosition', ['left'], { className: 'icon' }) common.propKeyAndValueToClassName(Input, 'labelPosition', ['left', 'right', 'left corner', 'right corner'], { className: 'labeled', }) common.propKeyOnlyToClassName(Input, 'action') common.propKeyOnlyToClassName(Input, 'disabled') common.propKeyOnlyToClassName(Input, 'error') common.propKeyOnlyToClassName(Input, 'fluid') common.propKeyOnlyToClassName(Input, 'focus') common.propKeyOnlyToClassName(Input, 'inverted') common.propKeyOnlyToClassName(Input, 'label', { className: 'labeled' }) common.propKeyOnlyToClassName(Input, 'loading') common.propKeyOnlyToClassName(Input, 'transparent') common.propKeyOnlyToClassName(Input, 'icon') common.propValueOnlyToClassName(Input, 'size', SUI.SIZES) it('renders with conditional children', () => { shallow( <Input> {true && <span></span>} {false && <div></div>} </Input> ) .should.contain(<span></span>) .should.not.contain(<div></div>) }) it('renders a text <input> by default', () => { shallow(<Input />) .find('input') .should.have.prop('type', 'text') }) describe('input props', () => { htmlInputPropNames.forEach(propName => { it(`passes \`${propName}\` to the <input>`, () => { const propValue = propName === 'onChange' ? () => null : 'foo' const wrapper = shallow(<Input {...{ [propName]: propValue }} />) // account for overloading the onChange prop const expectedValue = propName === 'onChange' ? wrapper.instance().handleChange : propValue wrapper .find('input') .should.have.prop(propName, expectedValue) }) it(`passes \`${propName}\` to the <input> when using children`, () => { const propValue = propName === 'onChange' ? () => null : 'foo' const wrapper = shallow( <Input {...{ [propName]: propValue }}> <input /> </Input> ) // account for overloading the onChange prop const expectedValue = propName === 'onChange' ? wrapper.instance().handleChange : propValue wrapper .find('input') .should.have.prop(propName, expectedValue) }) }) }) describe('onChange', () => { it('is called with (e, data) on change', () => { const spy = sandbox.spy() const e = { target: { value: 'name' } } const props = { 'data-foo': 'bar', onChange: spy } const wrapper = shallow(<Input {...props} />) wrapper.find('input').simulate('change', e) spy.should.have.been.calledOnce() spy.should.have.been.calledWithMatch(e, { ...props, value: e.target.value }) }) it('is called with (e, data) on change when using children', () => { const spy = sandbox.spy() const e = { target: { value: 'name' } } const props = { 'data-foo': 'bar', onChange: spy } const wrapper = shallow( <Input {...props}> <input /> </Input> ) wrapper.find('input').simulate('change', e) spy.should.have.been.calledOnce() spy.should.have.been.calledWithMatch(e, { ...props, value: e.target.value }) }) }) describe('tabIndex', () => { it('is not set by default', () => { shallow(<Input />) .find('input') .should.not.have.prop('tabIndex') }) it('defaults to -1 when disabled', () => { shallow(<Input disabled />) .find('input') .should.have.prop('tabIndex', -1) }) it('can be set explicitly', () => { shallow(<Input tabIndex={123} />) .find('input') .should.have.prop('tabIndex', 123) }) it('can be set explicitly when disabled', () => { shallow(<Input tabIndex={123} disabled />) .find('input') .should.have.prop('tabIndex', 123) }) }) })
src/js/ui/components/errorMessageFooter.js
hiddentao/heartnotes
import _ from 'lodash'; import React from 'react'; import AttentionIcon from './attentionIcon'; import Footer from './footer'; import { connectRedux } from '../helpers/decorators'; class Component extends React.Component { render() { let { diaryMgr } = this.props.data.diary; let footerItems = []; if (diaryMgr.auth.isCloudType && !diaryMgr.auth.subscriptionActive) { footerItems.push( <p key="sub"> Subscription expired! Your diary entries will not be backed up or synced. </p> ); } let { backgroundTasks } = this.props.data.app; _.each(backgroundTasks, (task) => { if (task.error) { footerItems.push( <p key={task.id}>{task.desc}: {task.msg}</p> ) } }); if (footerItems.length) { return ( <Footer className="error-messages"> {footerItems} </Footer> ); } else { return null; } } } module.exports = connectRedux()(Component);
src/create-account/EmailVerificationForm.js
qingweibinary/binary-next-gen
import React, { Component } from 'react'; import M from '../_common/M'; import Button from '../_common/Button'; import ErrorMsg from '../_common/ErrorMsg'; import InputGroup from '../_common/InputGroup'; import * as LiveData from '../_data/LiveData'; export default class EmailVerificationForm extends Component { static propTypes = { actions: React.PropTypes.object.isRequired, error: React.PropTypes.object, email: React.PropTypes.string.isRequired, password: React.PropTypes.string.isRequired, residence: React.PropTypes.string.isRequired, verificationCode: React.PropTypes.string.isRequired, }; static contextTypes = { router: React.PropTypes.object.isRequired, }; async onVerificationCodeEntered(event) { const { actions } = this.props; try { await actions.createAccountFieldUpdate('verificationCode', event.target.value); await actions.createAccountFieldUpdate('error', null); } catch (err) { actions.createAccountFieldUpdate('error', err); } } async onVerify() { const { actions, password, residence, verificationCode } = this.props; const { router } = this.context; actions.createAccountFieldUpdate('progress', true); try { await LiveData.api.createVirtualAccount({ client_password: password, residence, verification_code: verificationCode, }); router.push('/signin'); } catch (err) { actions.createAccountFailed(err); } finally { actions.createAccountFieldUpdate('progress', false); } } async goBack() { const { actions } = this.props; await actions.createAccountFieldUpdate('error', null); actions.createAccountFieldUpdate('step', 0); } render() { const { error } = this.props; return ( <div> <h3> <M m="Please enter your email verification code" /> </h3> <InputGroup type="text" placeholder="Verification Code" onChange={::this.onVerificationCodeEntered} /> <ErrorMsg shown={!!error} text={(error && error.message) || '-'} /> <Button text="Go back" onClick={::this.goBack} className="btn-secondary" /> &nbsp; <Button text="Verify" onClick={::this.onVerify} /> </div> ); } }
dist/1.11.0/jquery-dimensions-event-alias-offset-wrap.js
eric-seekas/jquery-builder
/*! * jQuery JavaScript Library v1.11.0 -dimensions,-event-alias,-offset,-wrap * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-09-24T05:30Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var version = "1.11.0 -dimensions,-event-alias,-offset,-wrap", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // 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, // 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(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return 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 ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // 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 ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( 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] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; 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; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // 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 ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // 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: trim && !trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : 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 { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return 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 len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // 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 new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return 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 = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // 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 ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, Expr, getText, isXML, compile, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ 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 hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select t=''><option selected=''></option></select>"; // Support: IE8, Opera 10-12 // Nothing should be selected when empty strings follow ^= or $= or *= if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( 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 ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[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 (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { 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; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ 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 ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (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; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); 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; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { 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 // Intentionally let the error be thrown if parseHTML is not present 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 typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ 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; } }); jQuery.fn.extend({ 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; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // 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 ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // 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( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var 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[ tuple[ 0 ] + "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 = 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 ? 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(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // 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"); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // 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(); } } 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 ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; jQuery(function() { // We need to execute this one support test ASAP because we need to know // if body.style.zoom needs to be set. var container, div, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup container = document.createElement( "div" ); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; div = document.createElement( "div" ); body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== 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.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1"; if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) { // 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 = null; }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; 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; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, 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 pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( 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 ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.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; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = document.createElement("div"), input = document.createElement("input"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.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() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. fragment = div = input = null; })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( 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 = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === 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.defaultPrevented === undefined && ( // Support: IE < 9 src.returnValue === false || // Support: Android < 4.0 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 ( !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 ( !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 ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); 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, // 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: 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; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== 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 ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !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 ( 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.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.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( 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 ( (!support.noCloneEvent || !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 ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !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 ( !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 = 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 !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return 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 ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = 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" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); 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() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function 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'/>" )).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; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var a, shrinkWrapBlocksVal, div = document.createElement( "div" ), divReset = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" + "display:block;padding:0;margin:0;border:0"; // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; a.style.cssText = "float:left;opacity:.5"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Null elements to avoid leaks in IE. a = div = null; support.shrinkWrapBlocks = function() { var body, container, div, containerStyles; if ( shrinkWrapBlocksVal == null ) { body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px"; container = document.createElement( "div" ); div = document.createElement( "div" ); body.appendChild( container ).appendChild( div ); // Will be changed later if needed. shrinkWrapBlocksVal = false; if ( typeof div.style.zoom !== strundefined ) { // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.cssText = divReset + ";width:1px;padding:1px;zoom:1"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); // Null elements to avoid leaks in IE. body = container = div = null; } return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; 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; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // 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; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var a, reliableHiddenOffsetsVal, boxSizingVal, boxSizingReliableVal, pixelPositionVal, reliableMarginRightVal, div = document.createElement( "div" ), containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px", divReset = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" + "display:block;padding:0;margin:0;border:0"; // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; a.style.cssText = "float:left;opacity:.5"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Null elements to avoid leaks in IE. a = div = null; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal != null ) { return reliableHiddenOffsetsVal; } var container, tds, isSupported, div = document.createElement( "div" ), body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; container = document.createElement( "div" ); container.style.cssText = containerStyles; 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 reliableHiddenOffsetsVal = isSupported && ( tds[ 0 ].offsetHeight === 0 ); body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; return reliableHiddenOffsetsVal; }, boxSizing: function() { if ( boxSizingVal == null ) { computeStyleTests(); } return boxSizingVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, reliableMarginRight: function() { var body, container, div, marginDiv; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( reliableMarginRightVal == null && window.getComputedStyle ) { body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); // 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"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); body.removeChild( container ); } return reliableMarginRightVal; } }); function computeStyleTests() { var container, div, body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:absolute;display:block;padding:1px;border:1px;width:4px;" + "margin-top:1%;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { boxSizingVal = div.offsetWidth === 4; }); // Will be changed later if needed. boxSizingReliableVal = true; pixelPositionVal = false; reliableMarginRightVal = true; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; } body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.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; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // 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]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, 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 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", 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; } 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 = 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 && ( 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"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": 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 null and NaN values aren't set. See: #7116 if ( value == null || value !== 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 ( !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 ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; 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; } }); 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, support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !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; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, 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" ] ); } } ); // 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; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // 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; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, dDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); dDisplay = defaultDisplay( elem.nodeName ); if ( display === "none" ) { display = dDisplay; } if ( display === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || dDisplay === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function 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; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } 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 ); } } }); 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.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); 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 ); }; }); // 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.timers = []; 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 ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; 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 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.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 ); }; }); }; (function() { var a, input, select, opt, div = document.createElement("div" ); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // 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: IE8 only // 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"; // Null elements to avoid leaks in IE. a = input = select = opt = div = null; })(); var rreturn = /\r/g; jQuery.fn.extend({ 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; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : jQuery.text( elem ); } }, 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 ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !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; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !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 + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return 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 ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, 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( 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 + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, 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( 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 + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === 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; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.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; }; var // Document location ajaxLocParts, ajaxLocation, 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+)|)|)/, /* 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( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 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; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( 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 += ( 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_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // 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._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; 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 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 ); } } // 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, "+" ); }; 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 || !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(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#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 && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.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 { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( 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 ) {} } // 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 + "_" + ( 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 += ( 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"; } }); // 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 jQuery.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 && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ 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; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
server/sonar-web/src/main/js/components/controls/ListFooter.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import classNames from 'classnames'; import React from 'react'; import { translate, translateWithParameters } from '../../helpers/l10n'; import { formatMeasure } from '../../helpers/measures'; export default class ListFooter extends React.Component { static propTypes = { count: React.PropTypes.number.isRequired, total: React.PropTypes.number.isRequired, loadMore: React.PropTypes.func, ready: React.PropTypes.bool }; static defaultProps = { ready: true }; componentWillMount () { this.handleLoadMore = this.handleLoadMore.bind(this); } canLoadMore () { return typeof this.props.loadMore === 'function'; } handleLoadMore (e) { e.preventDefault(); e.target.blur(); this.props.loadMore(); } render () { const hasMore = this.props.total > this.props.count; const loadMoreLink = ( <a className="spacer-left" href="#" onClick={this.handleLoadMore}> {translate('show_more')} </a> ); const className = classNames('spacer-top note text-center', { 'new-loading': !this.props.ready }); return ( <footer className={className}> {translateWithParameters( 'x_of_y_shown', formatMeasure(this.props.count, 'INT'), formatMeasure(this.props.total, 'INT') )} {this.canLoadMore() && hasMore ? loadMoreLink : null} </footer> ); } }
default/public/javascript/jquery/jquery+kumbiaphp.min.js
ennerperez/sgas
/*! jQuery v1.9.0 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license */(function(e,t){"use strict";function n(e){var t=e.length,n=st.type(e);return st.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}function r(e){var t=Tt[e]={};return st.each(e.match(lt)||[],function(e,n){t[n]=!0}),t}function i(e,n,r,i){if(st.acceptData(e)){var o,a,s=st.expando,u="string"==typeof n,l=e.nodeType,c=l?st.cache:e,f=l?e[s]:e[s]&&s;if(f&&c[f]&&(i||c[f].data)||!u||r!==t)return f||(l?e[s]=f=K.pop()||st.guid++:f=s),c[f]||(c[f]={},l||(c[f].toJSON=st.noop)),("object"==typeof n||"function"==typeof n)&&(i?c[f]=st.extend(c[f],n):c[f].data=st.extend(c[f].data,n)),o=c[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[st.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[st.camelCase(n)])):a=o,a}}function o(e,t,n){if(st.acceptData(e)){var r,i,o,a=e.nodeType,u=a?st.cache:e,l=a?e[st.expando]:st.expando;if(u[l]){if(t&&(r=n?u[l]:u[l].data)){st.isArray(t)?t=t.concat(st.map(t,st.camelCase)):t in r?t=[t]:(t=st.camelCase(t),t=t in r?[t]:t.split(" "));for(i=0,o=t.length;o>i;i++)delete r[t[i]];if(!(n?s:st.isEmptyObject)(r))return}(n||(delete u[l].data,s(u[l])))&&(a?st.cleanData([e],!0):st.support.deleteExpando||u!=u.window?delete u[l]:u[l]=null)}}}function a(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(Nt,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:wt.test(r)?st.parseJSON(r):r}catch(o){}st.data(e,n,r)}else r=t}return r}function s(e){var t;for(t in e)if(("data"!==t||!st.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function u(){return!0}function l(){return!1}function c(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function f(e,t,n){if(t=t||0,st.isFunction(t))return st.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return st.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=st.grep(e,function(e){return 1===e.nodeType});if(Wt.test(t))return st.filter(t,r,!n);t=st.filter(t,r)}return st.grep(e,function(e){return st.inArray(e,t)>=0===n})}function p(e){var t=zt.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function d(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function h(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function g(e){var t=nn.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function m(e,t){for(var n,r=0;null!=(n=e[r]);r++)st._data(n,"globalEval",!t||st._data(t[r],"globalEval"))}function y(e,t){if(1===t.nodeType&&st.hasData(e)){var n,r,i,o=st._data(e),a=st._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)st.event.add(t,n,s[n][r])}a.data&&(a.data=st.extend({},a.data))}}function v(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!st.support.noCloneEvent&&t[st.expando]){r=st._data(t);for(i in r.events)st.removeEvent(t,i,r.handle);t.removeAttribute(st.expando)}"script"===n&&t.text!==e.text?(h(t).text=e.text,g(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),st.support.html5Clone&&e.innerHTML&&!st.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Zt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function b(e,n){var r,i,o=0,a=e.getElementsByTagName!==t?e.getElementsByTagName(n||"*"):e.querySelectorAll!==t?e.querySelectorAll(n||"*"):t;if(!a)for(a=[],r=e.childNodes||e;null!=(i=r[o]);o++)!n||st.nodeName(i,n)?a.push(i):st.merge(a,b(i,n));return n===t||n&&st.nodeName(e,n)?st.merge([e],a):a}function x(e){Zt.test(e.type)&&(e.defaultChecked=e.checked)}function T(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Nn.length;i--;)if(t=Nn[i]+n,t in e)return t;return r}function w(e,t){return e=t||e,"none"===st.css(e,"display")||!st.contains(e.ownerDocument,e)}function N(e,t){for(var n,r=[],i=0,o=e.length;o>i;i++)n=e[i],n.style&&(r[i]=st._data(n,"olddisplay"),t?(r[i]||"none"!==n.style.display||(n.style.display=""),""===n.style.display&&w(n)&&(r[i]=st._data(n,"olddisplay",S(n.nodeName)))):r[i]||w(n)||st._data(n,"olddisplay",st.css(n,"display")));for(i=0;o>i;i++)n=e[i],n.style&&(t&&"none"!==n.style.display&&""!==n.style.display||(n.style.display=t?r[i]||"":"none"));return e}function C(e,t,n){var r=mn.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function k(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=st.css(e,n+wn[o],!0,i)),r?("content"===n&&(a-=st.css(e,"padding"+wn[o],!0,i)),"margin"!==n&&(a-=st.css(e,"border"+wn[o]+"Width",!0,i))):(a+=st.css(e,"padding"+wn[o],!0,i),"padding"!==n&&(a+=st.css(e,"border"+wn[o]+"Width",!0,i)));return a}function E(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=ln(e),a=st.support.boxSizing&&"border-box"===st.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=un(e,t,o),(0>i||null==i)&&(i=e.style[t]),yn.test(i))return i;r=a&&(st.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+k(e,t,n||(a?"border":"content"),r,o)+"px"}function S(e){var t=V,n=bn[e];return n||(n=A(e,t),"none"!==n&&n||(cn=(cn||st("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(cn[0].contentWindow||cn[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=A(e,t),cn.detach()),bn[e]=n),n}function A(e,t){var n=st(t.createElement(e)).appendTo(t.body),r=st.css(n[0],"display");return n.remove(),r}function j(e,t,n,r){var i;if(st.isArray(t))st.each(t,function(t,i){n||kn.test(e)?r(e,i):j(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==st.type(t))r(e,t);else for(i in t)j(e+"["+i+"]",t[i],n,r)}function D(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(lt)||[];if(st.isFunction(n))for(;r=o[i++];)"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function L(e,n,r,i){function o(u){var l;return a[u]=!0,st.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||s||a[c]?s?!(l=c):t:(n.dataTypes.unshift(c),o(c),!1)}),l}var a={},s=e===$n;return o(n.dataTypes[0])||!a["*"]&&o("*")}function H(e,n){var r,i,o=st.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((o[r]?e:i||(i={}))[r]=n[r]);return i&&st.extend(!0,e,i),e}function M(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(o in c)o in r&&(n[c[o]]=r[o]);for(;"*"===l[0];)l.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("Content-Type"));if(i)for(o in u)if(u[o]&&u[o].test(i)){l.unshift(o);break}if(l[0]in r)a=l[0];else{for(o in r){if(!l[0]||e.converters[o+" "+l[0]]){a=o;break}s||(s=o)}a=a||s}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function q(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=u[++s];)if("*"!==i){if("*"!==l&&l!==i){if(n=a[l+" "+i]||a["* "+i],!n)for(r in a)if(o=r.split(" "),o[1]===i&&(n=a[l+" "+o[0]]||a["* "+o[0]])){n===!0?n=a[r]:a[r]!==!0&&(i=o[0],u.splice(s--,0,i));break}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(c){return{state:"parsererror",error:n?c:"No conversion from "+l+" to "+i}}}l=i}return{state:"success",data:t}}function _(){try{return new e.XMLHttpRequest}catch(t){}}function F(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function O(){return setTimeout(function(){Qn=t}),Qn=st.now()}function B(e,t){st.each(t,function(t,n){for(var r=(rr[t]||[]).concat(rr["*"]),i=0,o=r.length;o>i;i++)if(r[i].call(e,t,n))return})}function P(e,t,n){var r,i,o=0,a=nr.length,s=st.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=Qn||O(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:st.extend({},t),opts:st.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Qn||O(),duration:n.duration,tweens:[],createTween:function(t,n){var r=st.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(R(c,l.opts.specialEasing);a>o;o++)if(r=nr[o].call(l,e,c,l.opts))return r;return B(l,c),st.isFunction(l.opts.start)&&l.opts.start.call(e,l),st.fx.timer(st.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function R(e,t){var n,r,i,o,a;for(n in e)if(r=st.camelCase(n),i=t[r],o=e[n],st.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=st.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function W(e,t,n){var r,i,o,a,s,u,l,c,f,p=this,d=e.style,h={},g=[],m=e.nodeType&&w(e);n.queue||(c=st._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,f=c.empty.fire,c.empty.fire=function(){c.unqueued||f()}),c.unqueued++,p.always(function(){p.always(function(){c.unqueued--,st.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===st.css(e,"display")&&"none"===st.css(e,"float")&&(st.support.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",st.support.shrinkWrapBlocks||p.done(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(r in t)if(o=t[r],Zn.exec(o)){if(delete t[r],u=u||"toggle"===o,o===(m?"hide":"show"))continue;g.push(r)}if(a=g.length){s=st._data(e,"fxshow")||st._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?st(e).show():p.done(function(){st(e).hide()}),p.done(function(){var t;st._removeData(e,"fxshow");for(t in h)st.style(e,t,h[t])});for(r=0;a>r;r++)i=g[r],l=p.createTween(i,m?s[i]:0),h[i]=s[i]||st.style(e,i),i in s||(s[i]=l.start,m&&(l.end=l.start,l.start="width"===i||"height"===i?1:0))}}function $(e,t,n,r,i){return new $.prototype.init(e,t,n,r,i)}function I(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=wn[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function z(e){return st.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var X,U,V=e.document,Y=e.location,J=e.jQuery,G=e.$,Q={},K=[],Z="1.9.0",et=K.concat,tt=K.push,nt=K.slice,rt=K.indexOf,it=Q.toString,ot=Q.hasOwnProperty,at=Z.trim,st=function(e,t){return new st.fn.init(e,t,X)},ut=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,lt=/\S+/g,ct=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ft=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,pt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,dt=/^[\],:{}\s]*$/,ht=/(?:^|:|,)(?:\s*\[)+/g,gt=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,mt=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,yt=/^-ms-/,vt=/-([\da-z])/gi,bt=function(e,t){return t.toUpperCase()},xt=function(){V.addEventListener?(V.removeEventListener("DOMContentLoaded",xt,!1),st.ready()):"complete"===V.readyState&&(V.detachEvent("onreadystatechange",xt),st.ready())};st.fn=st.prototype={jquery:Z,constructor:st,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:ft.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof st?n[0]:n,st.merge(this,st.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:V,!0)),pt.test(i[1])&&st.isPlainObject(n))for(i in n)st.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=V.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=V,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):st.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),st.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return nt.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=st.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return st.each(this,e,t)},ready:function(e){return st.ready.promise().done(e),this},slice:function(){return this.pushStack(nt.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(st.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:tt,sort:[].sort,splice:[].splice},st.fn.init.prototype=st.fn,st.extend=st.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||st.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(e=arguments[u]))for(n in e)r=s[n],i=e[n],s!==i&&(c&&i&&(st.isPlainObject(i)||(o=st.isArray(i)))?(o?(o=!1,a=r&&st.isArray(r)?r:[]):a=r&&st.isPlainObject(r)?r:{},s[n]=st.extend(c,a,i)):i!==t&&(s[n]=i));return s},st.extend({noConflict:function(t){return e.$===st&&(e.$=G),t&&e.jQuery===st&&(e.jQuery=J),st},isReady:!1,readyWait:1,holdReady:function(e){e?st.readyWait++:st.ready(!0)},ready:function(e){if(e===!0?!--st.readyWait:!st.isReady){if(!V.body)return setTimeout(st.ready);st.isReady=!0,e!==!0&&--st.readyWait>0||(U.resolveWith(V,[st]),st.fn.trigger&&st(V).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===st.type(e)},isArray:Array.isArray||function(e){return"array"===st.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Q[it.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==st.type(e)||e.nodeType||st.isWindow(e))return!1;try{if(e.constructor&&!ot.call(e,"constructor")&&!ot.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||ot.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||V;var r=pt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=st.buildFragment([e],t,i),i&&st(i).remove(),st.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=st.trim(n),n&&dt.test(n.replace(gt,"@").replace(mt,"]").replace(ht,"")))?Function("return "+n)():(st.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||st.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&st.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(yt,"ms-").replace(vt,bt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:at&&!at.call("\ufeff\u00a0")?function(e){return null==e?"":at.call(e)}:function(e){return null==e?"":(e+"").replace(ct,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?st.merge(r,"string"==typeof e?[e]:e):tt.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(rt)return rt.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else for(;n[o]!==t;)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),u=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&(u[u.length]=i);else for(o in e)i=t(e[o],o,r),null!=i&&(u[u.length]=i);return et.apply([],u)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(r=e[n],n=e,e=r),st.isFunction(e)?(i=nt.call(arguments,2),o=function(){return e.apply(n||this,i.concat(nt.call(arguments)))},o.guid=e.guid=e.guid||st.guid++,o):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===st.type(r)){o=!0;for(u in r)st.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,st.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(st(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),st.ready.promise=function(t){if(!U)if(U=st.Deferred(),"complete"===V.readyState)setTimeout(st.ready);else if(V.addEventListener)V.addEventListener("DOMContentLoaded",xt,!1),e.addEventListener("load",st.ready,!1);else{V.attachEvent("onreadystatechange",xt),e.attachEvent("onload",st.ready);var n=!1;try{n=null==e.frameElement&&V.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!st.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}st.ready()}}()}return U.promise(t)},st.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Q["[object "+t+"]"]=t.toLowerCase()}),X=st(V);var Tt={};st.Callbacks=function(e){e="string"==typeof e?Tt[e]||r(e):st.extend({},e);var n,i,o,a,s,u,l=[],c=!e.once&&[],f=function(t){for(n=e.memory&&t,i=!0,u=a||0,a=0,s=l.length,o=!0;l&&s>u;u++)if(l[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}o=!1,l&&(c?c.length&&f(c.shift()):n?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function r(t){st.each(t,function(t,n){var i=st.type(n);"function"===i?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==i&&r(n)})})(arguments),o?s=l.length:n&&(a=t,f(n))}return this},remove:function(){return l&&st.each(arguments,function(e,t){for(var n;(n=st.inArray(t,l,n))>-1;)l.splice(n,1),o&&(s>=n&&s--,u>=n&&u--)}),this},has:function(e){return st.inArray(e,l)>-1},empty:function(){return l=[],this},disable:function(){return l=c=n=t,this},disabled:function(){return!l},lock:function(){return c=t,n||p.disable(),this},locked:function(){return!c},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!l||i&&!c||(o?c.push(t):f(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},st.extend({Deferred:function(e){var t=[["resolve","done",st.Callbacks("once memory"),"resolved"],["reject","fail",st.Callbacks("once memory"),"rejected"],["notify","progress",st.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return st.Deferred(function(n){st.each(t,function(t,o){var a=o[0],s=st.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&st.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?st.extend(e,r):r}},i={};return r.pipe=r.then,st.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=nt.call(arguments),a=o.length,s=1!==a||e&&st.isFunction(e.promise)?a:0,u=1===s?e:st.Deferred(),l=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?nt.call(arguments):i,r===t?u.notifyWith(n,r):--s||u.resolveWith(n,r)}};if(a>1)for(t=Array(a),n=Array(a),r=Array(a);a>i;i++)o[i]&&st.isFunction(o[i].promise)?o[i].promise().done(l(i,r,o)).fail(u.reject).progress(l(i,n,t)):--s;return s||u.resolveWith(r,o),u.promise()}}),st.support=function(){var n,r,i,o,a,s,u,l,c,f,p=V.createElement("div");if(p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=p.getElementsByTagName("*"),i=p.getElementsByTagName("a")[0],!r||!i||!r.length)return{};o=V.createElement("select"),a=o.appendChild(V.createElement("option")),s=p.getElementsByTagName("input")[0],i.style.cssText="top:1px;float:left;opacity:.5",n={getSetAttribute:"t"!==p.className,leadingWhitespace:3===p.firstChild.nodeType,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(i.getAttribute("style")),hrefNormalized:"/a"===i.getAttribute("href"),opacity:/^0.5/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:!!s.value,optSelected:a.selected,enctype:!!V.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==V.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===V.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},s.checked=!0,n.noCloneChecked=s.cloneNode(!0).checked,o.disabled=!0,n.optDisabled=!a.disabled;try{delete p.test}catch(d){n.deleteExpando=!1}s=V.createElement("input"),s.setAttribute("value",""),n.input=""===s.getAttribute("value"),s.value="t",s.setAttribute("type","radio"),n.radioValue="t"===s.value,s.setAttribute("checked","t"),s.setAttribute("name","t"),u=V.createDocumentFragment(),u.appendChild(s),n.appendChecked=s.checked,n.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,p.attachEvent&&(p.attachEvent("onclick",function(){n.noCloneEvent=!1}),p.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})p.setAttribute(l="on"+f,"t"),n[f+"Bubbles"]=l in e||p.attributes[l].expando===!1;return p.style.backgroundClip="content-box",p.cloneNode(!0).style.backgroundClip="",n.clearCloneStyle="content-box"===p.style.backgroundClip,st(function(){var r,i,o,a="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",s=V.getElementsByTagName("body")[0];s&&(r=V.createElement("div"),r.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",s.appendChild(r).appendChild(p),p.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=p.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",c=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",n.reliableHiddenOffsets=c&&0===o[0].offsetHeight,p.innerHTML="",p.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%;",n.boxSizing=4===p.offsetWidth,n.doesNotIncludeMarginInBodyOffset=1!==s.offsetTop,e.getComputedStyle&&(n.pixelPosition="1%"!==(e.getComputedStyle(p,null)||{}).top,n.boxSizingReliable="4px"===(e.getComputedStyle(p,null)||{width:"4px"}).width,i=p.appendChild(V.createElement("div")),i.style.cssText=p.style.cssText=a,i.style.marginRight=i.style.width="0",p.style.width="1px",n.reliableMarginRight=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),p.style.zoom!==t&&(p.innerHTML="",p.style.cssText=a+"width:1px;padding:1px;display:inline;zoom:1",n.inlineBlockNeedsLayout=3===p.offsetWidth,p.style.display="block",p.innerHTML="<div></div>",p.firstChild.style.width="5px",n.shrinkWrapBlocks=3!==p.offsetWidth,s.style.zoom=1),s.removeChild(r),r=p=o=i=null)}),r=o=u=a=i=s=null,n}();var wt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,Nt=/([A-Z])/g;st.extend({cache:{},expando:"jQuery"+(Z+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?st.cache[e[st.expando]]:e[st.expando],!!e&&!s(e)},data:function(e,t,n){return i(e,t,n,!1)},removeData:function(e,t){return o(e,t,!1)},_data:function(e,t,n){return i(e,t,n,!0)},_removeData:function(e,t){return o(e,t,!0)},acceptData:function(e){var t=e.nodeName&&st.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),st.fn.extend({data:function(e,n){var r,i,o=this[0],s=0,u=null;if(e===t){if(this.length&&(u=st.data(o),1===o.nodeType&&!st._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>s;s++)i=r[s].name,i.indexOf("data-")||(i=st.camelCase(i.substring(5)),a(o,i,u[i]));st._data(o,"parsedAttrs",!0)}return u}return"object"==typeof e?this.each(function(){st.data(this,e)}):st.access(this,function(n){return n===t?o?a(o,e,st.data(o,e)):null:(this.each(function(){st.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){st.removeData(this,e)})}}),st.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=st._data(e,n),r&&(!i||st.isArray(r)?i=st._data(e,n,st.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=st.queue(e,t),r=n.length,i=n.shift(),o=st._queueHooks(e,t),a=function(){st.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return st._data(e,n)||st._data(e,n,{empty:st.Callbacks("once memory").add(function(){st._removeData(e,t+"queue"),st._removeData(e,n)})})}}),st.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?st.queue(this[0],e):n===t?this:this.each(function(){var t=st.queue(this,e,n);st._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&st.dequeue(this,e)})},dequeue:function(e){return this.each(function(){st.dequeue(this,e)})},delay:function(e,t){return e=st.fx?st.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=st.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};for("string"!=typeof e&&(n=e,e=t),e=e||"fx";s--;)r=st._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var Ct,kt,Et=/[\t\r\n]/g,St=/\r/g,At=/^(?:input|select|textarea|button|object)$/i,jt=/^(?:a|area)$/i,Dt=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,Lt=/^(?:checked|selected)$/i,Ht=st.support.getSetAttribute,Mt=st.support.input;st.fn.extend({attr:function(e,t){return st.access(this,st.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){st.removeAttr(this,e)})},prop:function(e,t){return st.access(this,st.prop,e,t,arguments.length>1)},removeProp:function(e){return e=st.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(st.isFunction(e))return this.each(function(t){st(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(lt)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Et," "):" ")){for(o=0;i=t[o++];)0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=st.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(st.isFunction(e))return this.each(function(t){st(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(lt)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Et," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");n.className=e?st.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return st.isFunction(e)?this.each(function(n){st(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var i,o=0,a=st(this),s=t,u=e.match(lt)||[];i=u[o++];)s=r?s:!a.hasClass(i),a[s?"addClass":"removeClass"](i);else("undefined"===n||"boolean"===n)&&(this.className&&st._data(this,"__className__",this.className),this.className=this.className||e===!1?"":st._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Et," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=st.isFunction(e),this.each(function(r){var o,a=st(this);1===this.nodeType&&(o=i?e.call(this,r,a.val()):e,null==o?o="":"number"==typeof o?o+="":st.isArray(o)&&(o=st.map(o,function(e){return null==e?"":e+""})),n=st.valHooks[this.type]||st.valHooks[this.nodeName.toLowerCase()],n&&"set"in n&&n.set(this,o,"value")!==t||(this.value=o))});if(o)return n=st.valHooks[o.type]||st.valHooks[o.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(o,"value"))!==t?r:(r=o.value,"string"==typeof r?r.replace(St,""):null==r?"":r)}}}),st.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(st.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&st.nodeName(n.parentNode,"optgroup"))){if(t=st(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=st.makeArray(t);return st(e).find("option").each(function(){this.selected=st.inArray(st(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return e.getAttribute===t?st.prop(e,n,r):(a=1!==s||!st.isXMLDoc(e),a&&(n=n.toLowerCase(),o=st.attrHooks[n]||(Dt.test(n)?kt:Ct)),r===t?o&&a&&"get"in o&&null!==(i=o.get(e,n))?i:(e.getAttribute!==t&&(i=e.getAttribute(n)),null==i?t:i):null!==r?o&&a&&"set"in o&&(i=o.set(e,r,n))!==t?i:(e.setAttribute(n,r+""),r):(st.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(lt);if(o&&1===e.nodeType)for(;n=o[i++];)r=st.propFix[n]||n,Dt.test(n)?!Ht&&Lt.test(n)?e[st.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:st.attr(e,n,""),e.removeAttribute(Ht?n:r)},attrHooks:{type:{set:function(e,t){if(!st.support.radioValue&&"radio"===t&&st.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!st.isXMLDoc(e),a&&(n=st.propFix[n]||n,o=st.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):At.test(e.nodeName)||jt.test(e.nodeName)&&e.href?0:t}}}}),kt={get:function(e,n){var r=st.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?Mt&&Ht?null!=i:Lt.test(n)?e[st.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?st.removeAttr(e,n):Mt&&Ht||!Lt.test(n)?e.setAttribute(!Ht&&st.propFix[n]||n,n):e[st.camelCase("default-"+n)]=e[n]=!0,n}},Mt&&Ht||(st.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return st.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t },set:function(e,n,r){return st.nodeName(e,"input")?(e.defaultValue=n,t):Ct&&Ct.set(e,n,r)}}),Ht||(Ct=st.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},st.attrHooks.contenteditable={get:Ct.get,set:function(e,t,n){Ct.set(e,""===t?!1:t,n)}},st.each(["width","height"],function(e,n){st.attrHooks[n]=st.extend(st.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),st.support.hrefNormalized||(st.each(["href","src","width","height"],function(e,n){st.attrHooks[n]=st.extend(st.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),st.each(["href","src"],function(e,t){st.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),st.support.style||(st.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),st.support.optSelected||(st.propHooks.selected=st.extend(st.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),st.support.enctype||(st.propFix.enctype="encoding"),st.support.checkOn||st.each(["radio","checkbox"],function(){st.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),st.each(["radio","checkbox"],function(){st.valHooks[this]=st.extend(st.valHooks[this],{set:function(e,n){return st.isArray(n)?e.checked=st.inArray(st(e).val(),n)>=0:t}})});var qt=/^(?:input|select|textarea)$/i,_t=/^key/,Ft=/^(?:mouse|contextmenu)|click/,Ot=/^(?:focusinfocus|focusoutblur)$/,Bt=/^([^.]*)(?:\.(.+)|)$/;st.event={global:{},add:function(e,n,r,i,o){var a,s,u,l,c,f,p,d,h,g,m,y=3!==e.nodeType&&8!==e.nodeType&&st._data(e);if(y){for(r.handler&&(a=r,r=a.handler,o=a.selector),r.guid||(r.guid=st.guid++),(l=y.events)||(l=y.events={}),(s=y.handle)||(s=y.handle=function(e){return st===t||e&&st.event.triggered===e.type?t:st.event.dispatch.apply(s.elem,arguments)},s.elem=e),n=(n||"").match(lt)||[""],c=n.length;c--;)u=Bt.exec(n[c])||[],h=m=u[1],g=(u[2]||"").split(".").sort(),p=st.event.special[h]||{},h=(o?p.delegateType:p.bindType)||h,p=st.event.special[h]||{},f=st.extend({type:h,origType:m,data:i,handler:r,guid:r.guid,selector:o,needsContext:o&&st.expr.match.needsContext.test(o),namespace:g.join(".")},a),(d=l[h])||(d=l[h]=[],d.delegateCount=0,p.setup&&p.setup.call(e,i,g,s)!==!1||(e.addEventListener?e.addEventListener(h,s,!1):e.attachEvent&&e.attachEvent("on"+h,s))),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=r.guid)),o?d.splice(d.delegateCount++,0,f):d.push(f),st.event.global[h]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,m=st.hasData(e)&&st._data(e);if(m&&(u=m.events)){for(t=(t||"").match(lt)||[""],l=t.length;l--;)if(s=Bt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){for(f=st.event.special[d]||{},d=(r?f.delegateType:f.bindType)||d,p=u[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;o--;)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&f.teardown.call(e,h,m.handle)!==!1||st.removeEvent(e,d,m.handle),delete u[d])}else for(d in u)st.event.remove(e,d+t[l],n,r,!0);st.isEmptyObject(u)&&(delete m.handle,st._removeData(e,"events"))}},trigger:function(n,r,i,o){var a,s,u,l,c,f,p,d=[i||V],h=n.type||n,g=n.namespace?n.namespace.split("."):[];if(s=u=i=i||V,3!==i.nodeType&&8!==i.nodeType&&!Ot.test(h+st.event.triggered)&&(h.indexOf(".")>=0&&(g=h.split("."),h=g.shift(),g.sort()),c=0>h.indexOf(":")&&"on"+h,n=n[st.expando]?n:new st.Event(h,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=g.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:st.makeArray(r,[n]),p=st.event.special[h]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!st.isWindow(i)){for(l=p.delegateType||h,Ot.test(l+h)||(s=s.parentNode);s;s=s.parentNode)d.push(s),u=s;u===(i.ownerDocument||V)&&d.push(u.defaultView||u.parentWindow||e)}for(a=0;(s=d[a++])&&!n.isPropagationStopped();)n.type=a>1?l:p.bindType||h,f=(st._data(s,"events")||{})[n.type]&&st._data(s,"handle"),f&&f.apply(s,r),f=c&&s[c],f&&st.acceptData(s)&&f.apply&&f.apply(s,r)===!1&&n.preventDefault();if(n.type=h,!(o||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===h&&st.nodeName(i,"a")||!st.acceptData(i)||!c||!i[h]||st.isWindow(i))){u=i[c],u&&(i[c]=null),st.event.triggered=h;try{i[h]()}catch(m){}st.event.triggered=t,u&&(i[c]=u)}return n.result}},dispatch:function(e){e=st.event.fix(e);var n,r,i,o,a,s=[],u=nt.call(arguments),l=(st._data(this,"events")||{})[e.type]||[],c=st.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){for(s=st.event.handlers.call(this,e,l),n=0;(o=s[n++])&&!e.isPropagationStopped();)for(e.currentTarget=o.elem,r=0;(a=o.handlers[r++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(a.namespace))&&(e.handleObj=a,e.data=a.data,i=((st.event.special[a.origType]||{}).handle||a.handler).apply(o.elem,u),i!==t&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(l.disabled!==!0||"click"!==e.type){for(i=[],r=0;u>r;r++)a=n[r],o=a.selector+" ",i[o]===t&&(i[o]=a.needsContext?st(o,this).index(l)>=0:st.find(o,this,null,[l]).length),i[o]&&i.push(a);i.length&&s.push({elem:l,handlers:i})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[st.expando])return e;var t,n,r=e,i=st.event.fixHooks[e.type]||{},o=i.props?this.props.concat(i.props):this.props;for(e=new st.Event(r),t=o.length;t--;)n=o[t],e[n]=r[n];return e.target||(e.target=r.srcElement||V),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,i.filter?i.filter(e,r):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,a=n.button,s=n.fromElement;return null==e.pageX&&null!=n.clientX&&(r=e.target.ownerDocument||V,i=r.documentElement,o=r.body,e.pageX=n.clientX+(i&&i.scrollLeft||o&&o.scrollLeft||0)-(i&&i.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(i&&i.scrollTop||o&&o.scrollTop||0)-(i&&i.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?n.toElement:s),e.which||a===t||(e.which=1&a?1:2&a?3:4&a?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return st.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==V.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===V.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=st.extend(new st.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?st.event.trigger(i,null,t):st.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},st.removeEvent=V.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,n,r){var i="on"+n;e.detachEvent&&(e[i]===t&&(e[i]=null),e.detachEvent(i,r))},st.Event=function(e,n){return this instanceof st.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?u:l):this.type=e,n&&st.extend(this,n),this.timeStamp=e&&e.timeStamp||st.now(),this[st.expando]=!0,t):new st.Event(e,n)},st.Event.prototype={isDefaultPrevented:l,isPropagationStopped:l,isImmediatePropagationStopped:l,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=u,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=u,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u,this.stopPropagation()}},st.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){st.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!st.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),st.support.submitBubbles||(st.event.special.submit={setup:function(){return st.nodeName(this,"form")?!1:(st.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=st.nodeName(n,"input")||st.nodeName(n,"button")?n.form:t;r&&!st._data(r,"submitBubbles")&&(st.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),st._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&st.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return st.nodeName(this,"form")?!1:(st.event.remove(this,"._submit"),t)}}),st.support.changeBubbles||(st.event.special.change={setup:function(){return qt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(st.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),st.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),st.event.simulate("change",this,e,!0)})),!1):(st.event.add(this,"beforeactivate._change",function(e){var t=e.target;qt.test(t.nodeName)&&!st._data(t,"changeBubbles")&&(st.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||st.event.simulate("change",this.parentNode,e,!0)}),st._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return st.event.remove(this,"._change"),!qt.test(this.nodeName)}}),st.support.focusinBubbles||st.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){st.event.simulate(t,e.target,st.event.fix(e),!0)};st.event.special[t]={setup:function(){0===n++&&V.addEventListener(e,r,!0)},teardown:function(){0===--n&&V.removeEventListener(e,r,!0)}}}),st.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(s in e)this.on(s,n,r,e[s],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=l;else if(!i)return this;return 1===o&&(a=i,i=function(e){return st().off(e),a.apply(this,arguments)},i.guid=a.guid||(a.guid=st.guid++)),this.each(function(){st.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,st(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=l),this.each(function(){st.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){st.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?st.event.trigger(e,n,r,!0):t},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),st.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){st.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)},_t.test(t)&&(st.event.fixHooks[t]=st.event.keyHooks),Ft.test(t)&&(st.event.fixHooks[t]=st.event.mouseHooks)}),function(e,t){function n(e){return ht.test(e+"")}function r(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>C.cacheLength&&delete e[t.shift()],e[n]=r}}function i(e){return e[P]=!0,e}function o(e){var t=L.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function a(e,t,n,r){var i,o,a,s,u,l,c,d,h,g;if((t?t.ownerDocument||t:R)!==L&&D(t),t=t||L,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!M&&!r){if(i=gt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&O(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Q.apply(n,K.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&W.getByClassName&&t.getElementsByClassName)return Q.apply(n,K.call(t.getElementsByClassName(a),0)),n}if(W.qsa&&!q.test(e)){if(c=!0,d=P,h=t,g=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(l=f(e),(c=t.getAttribute("id"))?d=c.replace(vt,"\\$&"):t.setAttribute("id",d),d="[id='"+d+"'] ",u=l.length;u--;)l[u]=d+p(l[u]);h=dt.test(e)&&t.parentNode||t,g=l.join(",")}if(g)try{return Q.apply(n,K.call(h.querySelectorAll(g),0)),n}catch(m){}finally{c||t.removeAttribute("id")}}}return x(e.replace(at,"$1"),t,n,r)}function s(e,t){for(var n=e&&t&&e.nextSibling;n;n=n.nextSibling)if(n===t)return-1;return e?1:-1}function u(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function c(e){return i(function(t){return t=+t,i(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function f(e,t){var n,r,i,o,s,u,l,c=X[e+" "];if(c)return t?0:c.slice(0);for(s=e,u=[],l=C.preFilter;s;){(!n||(r=ut.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(i=[])),n=!1,(r=lt.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(at," ")}),s=s.slice(n.length));for(o in C.filter)!(r=pt[o].exec(s))||l[o]&&!(r=l[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?a.error(e):X(e,u).slice(0)}function p(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function d(e,t,n){var r=t.dir,i=n&&"parentNode"===t.dir,o=I++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,u,l,c=$+" "+o;if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i)if(l=t[P]||(t[P]={}),(u=l[r])&&u[0]===c){if((s=u[1])===!0||s===N)return s===!0}else if(u=l[r]=[c],u[1]=e(t,n,a)||N,u[1]===!0)return!0}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function g(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function m(e,t,n,r,o,a){return r&&!r[P]&&(r=m(r)),o&&!o[P]&&(o=m(o,a)),i(function(i,a,s,u){var l,c,f,p=[],d=[],h=a.length,m=i||b(t||"*",s.nodeType?[s]:s,[]),y=!e||!i&&t?m:g(m,p,e,s,u),v=n?o||(i?e:h||r)?[]:a:y;if(n&&n(y,v,s,u),r)for(l=g(v,d),r(l,[],s,u),c=l.length;c--;)(f=l[c])&&(v[d[c]]=!(y[d[c]]=f));if(i){if(o||e){if(o){for(l=[],c=v.length;c--;)(f=v[c])&&l.push(y[c]=f);o(null,v=[],l,u)}for(c=v.length;c--;)(f=v[c])&&(l=o?Z.call(i,f):p[c])>-1&&(i[l]=!(a[l]=f))}}else v=g(v===a?v.splice(h,v.length):v),o?o(null,a,v,u):Q.apply(a,v)})}function y(e){for(var t,n,r,i=e.length,o=C.relative[e[0].type],a=o||C.relative[" "],s=o?1:0,u=d(function(e){return e===t},a,!0),l=d(function(e){return Z.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==j)||((t=n).nodeType?u(e,n,r):l(e,n,r))}];i>s;s++)if(n=C.relative[e[s].type])c=[d(h(c),n)];else{if(n=C.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!C.relative[e[r].type];r++);return m(s>1&&h(c),s>1&&p(e.slice(0,s-1)).replace(at,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&p(e))}c.push(n)}return h(c)}function v(e,t){var n=0,r=t.length>0,o=e.length>0,s=function(i,s,u,l,c){var f,p,d,h=[],m=0,y="0",v=i&&[],b=null!=c,x=j,T=i||o&&C.find.TAG("*",c&&s.parentNode||s),w=$+=null==x?1:Math.E;for(b&&(j=s!==L&&s,N=n);null!=(f=T[y]);y++){if(o&&f){for(p=0;d=e[p];p++)if(d(f,s,u)){l.push(f);break}b&&($=w,N=++n)}r&&((f=!d&&f)&&m--,i&&v.push(f))}if(m+=y,r&&y!==m){for(p=0;d=t[p];p++)d(v,h,s,u);if(i){if(m>0)for(;y--;)v[y]||h[y]||(h[y]=G.call(l));h=g(h)}Q.apply(l,h),b&&!i&&h.length>0&&m+t.length>1&&a.uniqueSort(l)}return b&&($=w,j=x),v};return r?i(s):s}function b(e,t,n){for(var r=0,i=t.length;i>r;r++)a(e,t[r],n);return n}function x(e,t,n,r){var i,o,a,s,u,l=f(e);if(!r&&1===l.length){if(o=l[0]=l[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===t.nodeType&&!M&&C.relative[o[1].type]){if(t=C.find.ID(a.matches[0].replace(xt,Tt),t)[0],!t)return n;e=e.slice(o.shift().value.length)}for(i=pt.needsContext.test(e)?-1:o.length-1;i>=0&&(a=o[i],!C.relative[s=a.type]);i--)if((u=C.find[s])&&(r=u(a.matches[0].replace(xt,Tt),dt.test(o[0].type)&&t.parentNode||t))){if(o.splice(i,1),e=r.length&&p(o),!e)return Q.apply(n,K.call(r,0)),n;break}}return S(e,l)(r,t,M,n,dt.test(e)),n}function T(){}var w,N,C,k,E,S,A,j,D,L,H,M,q,_,F,O,B,P="sizzle"+-new Date,R=e.document,W={},$=0,I=0,z=r(),X=r(),U=r(),V=typeof t,Y=1<<31,J=[],G=J.pop,Q=J.push,K=J.slice,Z=J.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},et="[\\x20\\t\\r\\n\\f]",tt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=tt.replace("w","w#"),rt="([*^$|!~]?=)",it="\\["+et+"*("+tt+")"+et+"*(?:"+rt+et+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+nt+")|)|)"+et+"*\\]",ot=":("+tt+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+it.replace(3,8)+")*)|.*)\\)|)",at=RegExp("^"+et+"+|((?:^|[^\\\\])(?:\\\\.)*)"+et+"+$","g"),ut=RegExp("^"+et+"*,"+et+"*"),lt=RegExp("^"+et+"*([\\x20\\t\\r\\n\\f>+~])"+et+"*"),ct=RegExp(ot),ft=RegExp("^"+nt+"$"),pt={ID:RegExp("^#("+tt+")"),CLASS:RegExp("^\\.("+tt+")"),NAME:RegExp("^\\[name=['\"]?("+tt+")['\"]?\\]"),TAG:RegExp("^("+tt.replace("w","w*")+")"),ATTR:RegExp("^"+it),PSEUDO:RegExp("^"+ot),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+et+"*(even|odd|(([+-]|)(\\d*)n|)"+et+"*(?:([+-]|)"+et+"*(\\d+)|))"+et+"*\\)|)","i"),needsContext:RegExp("^"+et+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+et+"*((?:-\\d)?\\d*)"+et+"*\\)|)(?=[^-]|$)","i")},dt=/[\x20\t\r\n\f]*[+~]/,ht=/\{\s*\[native code\]\s*\}/,gt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,mt=/^(?:input|select|textarea|button)$/i,yt=/^h\d$/i,vt=/'|\\/g,bt=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,xt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,Tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{K.call(H.childNodes,0)[0].nodeType}catch(wt){K=function(e){for(var t,n=[];t=this[e];e++)n.push(t);return n}}E=a.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},D=a.setDocument=function(e){var r=e?e.ownerDocument||e:R;return r!==L&&9===r.nodeType&&r.documentElement?(L=r,H=r.documentElement,M=E(r),W.tagNameNoComments=o(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),W.attributes=o(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),W.getByClassName=o(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),W.getByName=o(function(e){e.id=P+0,e.innerHTML="<a name='"+P+"'></a><div name='"+P+"'></div>",H.insertBefore(e,H.firstChild);var t=r.getElementsByName&&r.getElementsByName(P).length===2+r.getElementsByName(P+0).length;return W.getIdNotName=!r.getElementById(P),H.removeChild(e),t}),C.attrHandle=o(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==V&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},W.getIdNotName?(C.find.ID=function(e,t){if(typeof t.getElementById!==V&&!M){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},C.filter.ID=function(e){var t=e.replace(xt,Tt);return function(e){return e.getAttribute("id")===t}}):(C.find.ID=function(e,n){if(typeof n.getElementById!==V&&!M){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==V&&r.getAttributeNode("id").value===e?[r]:t:[]}},C.filter.ID=function(e){var t=e.replace(xt,Tt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),C.find.TAG=W.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==V?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i];i++)1===n.nodeType&&r.push(n);return r}return o},C.find.NAME=W.getByName&&function(e,n){return typeof n.getElementsByName!==V?n.getElementsByName(name):t},C.find.CLASS=W.getByClassName&&function(e,n){return typeof n.getElementsByClassName===V||M?t:n.getElementsByClassName(e)},_=[],q=[":focus"],(W.qsa=n(r.querySelectorAll))&&(o(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||q.push("\\["+et+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||q.push(":checked")}),o(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&q.push("[*^$]="+et+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),q.push(",.*:")})),(W.matchesSelector=n(F=H.matchesSelector||H.mozMatchesSelector||H.webkitMatchesSelector||H.oMatchesSelector||H.msMatchesSelector))&&o(function(e){W.disconnectedMatch=F.call(e,"div"),F.call(e,"[s!='']:x"),_.push("!=",ot)}),q=RegExp(q.join("|")),_=RegExp(_.join("|")),O=n(H.contains)||H.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},B=H.compareDocumentPosition?function(e,t){var n;return e===t?(A=!0,0):(n=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&n||e.parentNode&&11===e.parentNode.nodeType?e===r||O(R,e)?-1:t===r||O(R,t)?1:0:4&n?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var n,i=0,o=e.parentNode,a=t.parentNode,u=[e],l=[t];if(e===t)return A=!0,0;if(e.sourceIndex&&t.sourceIndex)return(~t.sourceIndex||Y)-(O(R,e)&&~e.sourceIndex||Y);if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:0;if(o===a)return s(e,t);for(n=e;n=n.parentNode;)u.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;u[i]===l[i];)i++;return i?s(u[i],l[i]):u[i]===R?-1:l[i]===R?1:0},A=!1,[0,0].sort(B),W.detectDuplicates=A,L):L},a.matches=function(e,t){return a(e,null,null,t)},a.matchesSelector=function(e,t){if((e.ownerDocument||e)!==L&&D(e),t=t.replace(bt,"='$1']"),!(!W.matchesSelector||M||_&&_.test(t)||q.test(t)))try{var n=F.call(e,t);if(n||W.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return a(t,L,null,[e]).length>0},a.contains=function(e,t){return(e.ownerDocument||e)!==L&&D(e),O(e,t)},a.attr=function(e,t){var n;return(e.ownerDocument||e)!==L&&D(e),M||(t=t.toLowerCase()),(n=C.attrHandle[t])?n(e):M||W.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},a.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},a.uniqueSort=function(e){var t,n=[],r=1,i=0;if(A=!W.detectDuplicates,e.sort(B),A){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));for(;i--;)e.splice(n[i],1)}return e},k=a.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=k(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=k(t);return n},C=a.selectors={cacheLength:50,createPseudo:i,match:pt,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(xt,Tt),e[3]=(e[4]||e[5]||"").replace(xt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||a.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&a.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return pt.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&ct.test(n)&&(t=f(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(xt,Tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=z[e+" "];return t||(t=RegExp("(^|"+et+")"+e+"("+et+"|$)"))&&z(e,function(e){return t.test(e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=a.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.substr(i.length-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){for(;g;){for(f=t;f=f[g];)if(s?f.nodeName.toLowerCase()===y:1===f.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){for(c=m[P]||(m[P]={}),l=c[e]||[],d=l[0]===$&&l[1],p=l[0]===$&&l[2],f=d&&m.childNodes[d];f=++d&&f&&f[g]||(p=d=0)||h.pop();)if(1===f.nodeType&&++p&&f===t){c[e]=[$,d,p];break}}else if(v&&(l=(t[P]||(t[P]={}))[e])&&l[0]===$)p=l[1];else for(;(f=++d&&f&&f[g]||(p=d=0)||h.pop())&&((s?f.nodeName.toLowerCase()!==y:1!==f.nodeType)||!++p||(v&&((f[P]||(f[P]={}))[e]=[$,p]),f!==t)););return p-=i,p===r||0===p%r&&p/r>=0}}},PSEUDO:function(e,t){var n,r=C.pseudos[e]||C.setFilters[e.toLowerCase()]||a.error("unsupported pseudo: "+e);return r[P]?r(t):r.length>1?(n=[e,e,"",t],C.setFilters.hasOwnProperty(e.toLowerCase())?i(function(e,n){for(var i,o=r(e,t),a=o.length;a--;)i=Z.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:i(function(e){var t=[],n=[],r=S(e.replace(at,"$1"));return r[P]?i(function(e,t,n,i){for(var o,a=r(e,null,i,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:i(function(e){return function(t){return a(e,t).length>0}}),contains:i(function(e){return function(t){return(t.textContent||t.innerText||k(t)).indexOf(e)>-1}}),lang:i(function(e){return ft.test(e||"")||a.error("unsupported lang: "+e),e=e.replace(xt,Tt).toLowerCase(),function(t){var n;do if(n=M?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===H},focus:function(e){return e===L.activeElement&&(!L.hasFocus||L.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!C.pseudos.empty(e)},header:function(e){return yt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:c(function(){return[0]}),last:c(function(e,t){return[t-1]}),eq:c(function(e,t,n){return[0>n?n+t:n]}),even:c(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:c(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:c(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:c(function(e,t,n){for(var r=0>n?n+t:n;t>++r;)e.push(r);return e})}};for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[w]=u(w);for(w in{submit:!0,reset:!0})C.pseudos[w]=l(w);S=a.compile=function(e,t){var n,r=[],i=[],o=U[e+" "];if(!o){for(t||(t=f(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=U(e,v(i,r))}return o},C.pseudos.nth=C.pseudos.eq,C.filters=T.prototype=C.pseudos,C.setFilters=new T,D(),a.attr=st.attr,st.find=a,st.expr=a.selectors,st.expr[":"]=st.expr.pseudos,st.unique=a.uniqueSort,st.text=a.getText,st.isXMLDoc=a.isXML,st.contains=a.contains}(e);var Pt=/Until$/,Rt=/^(?:parents|prev(?:Until|All))/,Wt=/^.[^:#\[\.,]*$/,$t=st.expr.match.needsContext,It={children:!0,contents:!0,next:!0,prev:!0};st.fn.extend({find:function(e){var t,n,r;if("string"!=typeof e)return r=this,this.pushStack(st(e).filter(function(){for(t=0;r.length>t;t++)if(st.contains(r[t],this))return!0}));for(n=[],t=0;this.length>t;t++)st.find(e,this[t],n);return n=this.pushStack(st.unique(n)),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=st(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(st.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(f(this,e,!1))},filter:function(e){return this.pushStack(f(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?$t.test(e)?st(e,this.context).index(this[0])>=0:st.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=$t.test(e)||"string"!=typeof e?st(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n.ownerDocument&&n!==t&&11!==n.nodeType;){if(a?a.index(n)>-1:st.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}return this.pushStack(o.length>1?st.unique(o):o)},index:function(e){return e?"string"==typeof e?st.inArray(this[0],st(e)):st.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?st(e,t):st.makeArray(e&&e.nodeType?[e]:e),r=st.merge(this.get(),n);return this.pushStack(st.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),st.fn.andSelf=st.fn.addBack,st.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return st.dir(e,"parentNode")},parentsUntil:function(e,t,n){return st.dir(e,"parentNode",n)},next:function(e){return c(e,"nextSibling")},prev:function(e){return c(e,"previousSibling") },nextAll:function(e){return st.dir(e,"nextSibling")},prevAll:function(e){return st.dir(e,"previousSibling")},nextUntil:function(e,t,n){return st.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return st.dir(e,"previousSibling",n)},siblings:function(e){return st.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return st.sibling(e.firstChild)},contents:function(e){return st.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:st.merge([],e.childNodes)}},function(e,t){st.fn[e]=function(n,r){var i=st.map(this,t,n);return Pt.test(e)||(r=n),r&&"string"==typeof r&&(i=st.filter(r,i)),i=this.length>1&&!It[e]?st.unique(i):i,this.length>1&&Rt.test(e)&&(i=i.reverse()),this.pushStack(i)}}),st.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?st.find.matchesSelector(t[0],e)?[t[0]]:[]:st.find.matches(e,t)},dir:function(e,n,r){for(var i=[],o=e[n];o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!st(o).is(r));)1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});var zt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Xt=/ jQuery\d+="(?:null|\d+)"/g,Ut=RegExp("<(?:"+zt+")[\\s/>]","i"),Vt=/^\s+/,Yt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Jt=/<([\w:]+)/,Gt=/<tbody/i,Qt=/<|&#?\w+;/,Kt=/<(?:script|style|link)/i,Zt=/^(?:checkbox|radio)$/i,en=/checked\s*(?:[^=]|=\s*.checked.)/i,tn=/^$|\/(?:java|ecma)script/i,nn=/^true\/(.*)/,rn=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,on={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:st.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},an=p(V),sn=an.appendChild(V.createElement("div"));on.optgroup=on.option,on.tbody=on.tfoot=on.colgroup=on.caption=on.thead,on.th=on.td,st.fn.extend({text:function(e){return st.access(this,function(e){return e===t?st.text(this):this.empty().append((this[0]&&this[0].ownerDocument||V).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(st.isFunction(e))return this.each(function(t){st(this).wrapAll(e.call(this,t))});if(this[0]){var t=st(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return st.isFunction(e)?this.each(function(t){st(this).wrapInner(e.call(this,t))}):this.each(function(){var t=st(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=st.isFunction(e);return this.each(function(n){st(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){st.nodeName(this,"body")||st(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=0;null!=(n=this[r]);r++)(!e||st.filter(e,[n]).length>0)&&(t||1!==n.nodeType||st.cleanData(b(n)),n.parentNode&&(t&&st.contains(n.ownerDocument,n)&&m(b(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&st.cleanData(b(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&st.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return st.clone(this,e,t)})},html:function(e){return st.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(Xt,""):t;if(!("string"!=typeof e||Kt.test(e)||!st.support.htmlSerialize&&Ut.test(e)||!st.support.leadingWhitespace&&Vt.test(e)||on[(Jt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Yt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(st.cleanData(b(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=st.isFunction(e);return t||"string"==typeof e||(e=st(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;(n&&1===this.nodeType||11===this.nodeType)&&(st(this).remove(),t?t.parentNode.insertBefore(e,t):n.appendChild(e))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=et.apply([],e);var i,o,a,s,u,l,c=0,f=this.length,p=this,m=f-1,y=e[0],v=st.isFunction(y);if(v||!(1>=f||"string"!=typeof y||st.support.checkClone)&&en.test(y))return this.each(function(i){var o=p.eq(i);v&&(e[0]=y.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(f&&(i=st.buildFragment(e,this[0].ownerDocument,!1,this),o=i.firstChild,1===i.childNodes.length&&(i=o),o)){for(n=n&&st.nodeName(o,"tr"),a=st.map(b(i,"script"),h),s=a.length;f>c;c++)u=i,c!==m&&(u=st.clone(u,!0,!0),s&&st.merge(a,b(u,"script"))),r.call(n&&st.nodeName(this[c],"table")?d(this[c],"tbody"):this[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,st.map(a,g),c=0;s>c;c++)u=a[c],tn.test(u.type||"")&&!st._data(u,"globalEval")&&st.contains(l,u)&&(u.src?st.ajax({url:u.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):st.globalEval((u.text||u.textContent||u.innerHTML||"").replace(rn,"")));i=o=null}return this}}),st.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){st.fn[e]=function(e){for(var n,r=0,i=[],o=st(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),st(o[r])[t](n),tt.apply(i,n.get());return this.pushStack(i)}}),st.extend({clone:function(e,t,n){var r,i,o,a,s,u=st.contains(e.ownerDocument,e);if(st.support.html5Clone||st.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">")?s=e.cloneNode(!0):(sn.innerHTML=e.outerHTML,sn.removeChild(s=sn.firstChild)),!(st.support.noCloneEvent&&st.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||st.isXMLDoc(e)))for(r=b(s),i=b(e),a=0;null!=(o=i[a]);++a)r[a]&&v(o,r[a]);if(t)if(n)for(i=i||b(e),r=r||b(s),a=0;null!=(o=i[a]);a++)y(o,r[a]);else y(e,s);return r=b(s,"script"),r.length>0&&m(r,!u&&b(e,"script")),r=i=o=null,s},buildFragment:function(e,t,n,r){for(var i,o,a,s,u,l,c,f=e.length,d=p(t),h=[],g=0;f>g;g++)if(o=e[g],o||0===o)if("object"===st.type(o))st.merge(h,o.nodeType?[o]:o);else if(Qt.test(o)){for(s=s||d.appendChild(t.createElement("div")),a=(Jt.exec(o)||["",""])[1].toLowerCase(),u=on[a]||on._default,s.innerHTML=u[1]+o.replace(Yt,"<$1></$2>")+u[2],c=u[0];c--;)s=s.lastChild;if(!st.support.leadingWhitespace&&Vt.test(o)&&h.push(t.createTextNode(Vt.exec(o)[0])),!st.support.tbody)for(o="table"!==a||Gt.test(o)?"<table>"!==u[1]||Gt.test(o)?0:s:s.firstChild,c=o&&o.childNodes.length;c--;)st.nodeName(l=o.childNodes[c],"tbody")&&!l.childNodes.length&&o.removeChild(l);for(st.merge(h,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=d.lastChild}else h.push(t.createTextNode(o));for(s&&d.removeChild(s),st.support.appendChecked||st.grep(b(h,"input"),x),g=0;o=h[g++];)if((!r||-1===st.inArray(o,r))&&(i=st.contains(o.ownerDocument,o),s=b(d.appendChild(o),"script"),i&&m(s),n))for(c=0;o=s[c++];)tn.test(o.type||"")&&n.push(o);return s=null,d},cleanData:function(e,n){for(var r,i,o,a,s=0,u=st.expando,l=st.cache,c=st.support.deleteExpando,f=st.event.special;null!=(o=e[s]);s++)if((n||st.acceptData(o))&&(i=o[u],r=i&&l[i])){if(r.events)for(a in r.events)f[a]?st.event.remove(o,a):st.removeEvent(o,a,r.handle);l[i]&&(delete l[i],c?delete o[u]:o.removeAttribute!==t?o.removeAttribute(u):o[u]=null,K.push(i))}}});var un,ln,cn,fn=/alpha\([^)]*\)/i,pn=/opacity\s*=\s*([^)]*)/,dn=/^(top|right|bottom|left)$/,hn=/^(none|table(?!-c[ea]).+)/,gn=/^margin/,mn=RegExp("^("+ut+")(.*)$","i"),yn=RegExp("^("+ut+")(?!px)[a-z%]+$","i"),vn=RegExp("^([+-])=("+ut+")","i"),bn={BODY:"block"},xn={position:"absolute",visibility:"hidden",display:"block"},Tn={letterSpacing:0,fontWeight:400},wn=["Top","Right","Bottom","Left"],Nn=["Webkit","O","Moz","ms"];st.fn.extend({css:function(e,n){return st.access(this,function(e,n,r){var i,o,a={},s=0;if(st.isArray(n)){for(i=ln(e),o=n.length;o>s;s++)a[n[s]]=st.css(e,n[s],!1,i);return a}return r!==t?st.style(e,n,r):st.css(e,n)},e,n,arguments.length>1)},show:function(){return N(this,!0)},hide:function(){return N(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:w(this))?st(this).show():st(this).hide()})}}),st.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=un(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":st.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=st.camelCase(n),l=e.style;if(n=st.cssProps[u]||(st.cssProps[u]=T(l,u)),s=st.cssHooks[n]||st.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=vn.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(st.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||st.cssNumber[u]||(r+="px"),st.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=st.camelCase(n);return n=st.cssProps[u]||(st.cssProps[u]=T(e.style,u)),s=st.cssHooks[n]||st.cssHooks[u],s&&"get"in s&&(o=s.get(e,!0,r)),o===t&&(o=un(e,n,i)),"normal"===o&&n in Tn&&(o=Tn[n]),r?(a=parseFloat(o),r===!0||st.isNumeric(a)?a||0:o):o},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(ln=function(t){return e.getComputedStyle(t,null)},un=function(e,n,r){var i,o,a,s=r||ln(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||st.contains(e.ownerDocument,e)||(u=st.style(e,n)),yn.test(u)&&gn.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):V.documentElement.currentStyle&&(ln=function(e){return e.currentStyle},un=function(e,n,r){var i,o,a,s=r||ln(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),yn.test(u)&&!dn.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u}),st.each(["height","width"],function(e,n){st.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&hn.test(st.css(e,"display"))?st.swap(e,xn,function(){return E(e,n,i)}):E(e,n,i):t},set:function(e,t,r){var i=r&&ln(e);return C(e,t,r?k(e,n,r,st.support.boxSizing&&"border-box"===st.css(e,"boxSizing",!1,i),i):0)}}}),st.support.opacity||(st.cssHooks.opacity={get:function(e,t){return pn.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=st.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===st.trim(o.replace(fn,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=fn.test(o)?o.replace(fn,i):o+" "+i)}}),st(function(){st.support.reliableMarginRight||(st.cssHooks.marginRight={get:function(e,n){return n?st.swap(e,{display:"inline-block"},un,[e,"marginRight"]):t}}),!st.support.pixelPosition&&st.fn.position&&st.each(["top","left"],function(e,n){st.cssHooks[n]={get:function(e,r){return r?(r=un(e,n),yn.test(r)?st(e).position()[n]+"px":r):t}}})}),st.expr&&st.expr.filters&&(st.expr.filters.hidden=function(e){return 0===e.offsetWidth&&0===e.offsetHeight||!st.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||st.css(e,"display"))},st.expr.filters.visible=function(e){return!st.expr.filters.hidden(e)}),st.each({margin:"",padding:"",border:"Width"},function(e,t){st.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+wn[r]+t]=o[r]||o[r-2]||o[0];return i}},gn.test(e)||(st.cssHooks[e+t].set=C)});var Cn=/%20/g,kn=/\[\]$/,En=/\r?\n/g,Sn=/^(?:submit|button|image|reset)$/i,An=/^(?:input|select|textarea|keygen)/i;st.fn.extend({serialize:function(){return st.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=st.prop(this,"elements");return e?st.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!st(this).is(":disabled")&&An.test(this.nodeName)&&!Sn.test(e)&&(this.checked||!Zt.test(e))}).map(function(e,t){var n=st(this).val();return null==n?null:st.isArray(n)?st.map(n,function(e){return{name:t.name,value:e.replace(En,"\r\n")}}):{name:t.name,value:n.replace(En,"\r\n")}}).get()}}),st.param=function(e,n){var r,i=[],o=function(e,t){t=st.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=st.ajaxSettings&&st.ajaxSettings.traditional),st.isArray(e)||e.jquery&&!st.isPlainObject(e))st.each(e,function(){o(this.name,this.value)});else for(r in e)j(r,e[r],n,o);return i.join("&").replace(Cn,"+")};var jn,Dn,Ln=st.now(),Hn=/\?/,Mn=/#.*$/,qn=/([?&])_=[^&]*/,_n=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Fn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,On=/^(?:GET|HEAD)$/,Bn=/^\/\//,Pn=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Rn=st.fn.load,Wn={},$n={},In="*/".concat("*");try{Dn=Y.href}catch(zn){Dn=V.createElement("a"),Dn.href="",Dn=Dn.href}jn=Pn.exec(Dn.toLowerCase())||[],st.fn.load=function(e,n,r){if("string"!=typeof e&&Rn)return Rn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),st.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(o="POST"),s.length>0&&st.ajax({url:e,type:o,dataType:"html",data:n}).done(function(e){a=arguments,s.html(i?st("<div>").append(st.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,a||[e.responseText,t,e])}),this},st.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){st.fn[t]=function(e){return this.on(t,e)}}),st.each(["get","post"],function(e,n){st[n]=function(e,r,i,o){return st.isFunction(r)&&(o=o||i,i=r,r=t),st.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),st.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Dn,type:"GET",isLocal:Fn.test(jn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":In,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":st.parseJSON,"text xml":st.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,st.ajaxSettings),t):H(st.ajaxSettings,e)},ajaxPrefilter:D(Wn),ajaxTransport:D($n),ajax:function(e,n){function r(e,n,r,s){var l,f,v,b,T,N=n;2!==x&&(x=2,u&&clearTimeout(u),i=t,a=s||"",w.readyState=e>0?4:0,r&&(b=M(p,w,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=w.getResponseHeader("Last-Modified"),T&&(st.lastModified[o]=T),T=w.getResponseHeader("etag"),T&&(st.etag[o]=T)),304===e?(l=!0,N="notmodified"):(l=q(p,b),N=l.state,f=l.data,v=l.error,l=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),w.status=e,w.statusText=(n||N)+"",l?g.resolveWith(d,[f,N,w]):g.rejectWith(d,[w,N,v]),w.statusCode(y),y=t,c&&h.trigger(l?"ajaxSuccess":"ajaxError",[w,p,l?f:v]),m.fireWith(d,[w,N]),c&&(h.trigger("ajaxComplete",[w,p]),--st.active||st.event.trigger("ajaxStop")))}"object"==typeof e&&(n=e,e=t),n=n||{};var i,o,a,s,u,l,c,f,p=st.ajaxSetup({},n),d=p.context||p,h=p.context&&(d.nodeType||d.jquery)?st(d):st.event,g=st.Deferred(),m=st.Callbacks("once memory"),y=p.statusCode||{},v={},b={},x=0,T="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!s)for(s={};t=_n.exec(a);)s[t[1].toLowerCase()]=t[2];t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=b[n]=b[n]||e,v[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)y[t]=[y[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||T;return i&&i.abort(t),r(0,t),this}};if(g.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,p.url=((e||p.url||Dn)+"").replace(Mn,"").replace(Bn,jn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=st.trim(p.dataType||"*").toLowerCase().match(lt)||[""],null==p.crossDomain&&(l=Pn.exec(p.url.toLowerCase()),p.crossDomain=!(!l||l[1]===jn[1]&&l[2]===jn[2]&&(l[3]||("http:"===l[1]?80:443))==(jn[3]||("http:"===jn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=st.param(p.data,p.traditional)),L(Wn,p,n,w),2===x)return w;c=p.global,c&&0===st.active++&&st.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!On.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(Hn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=qn.test(o)?o.replace(qn,"$1_="+Ln++):o+(Hn.test(o)?"&":"?")+"_="+Ln++)),p.ifModified&&(st.lastModified[o]&&w.setRequestHeader("If-Modified-Since",st.lastModified[o]),st.etag[o]&&w.setRequestHeader("If-None-Match",st.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&w.setRequestHeader("Content-Type",p.contentType),w.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+In+"; q=0.01":""):p.accepts["*"]);for(f in p.headers)w.setRequestHeader(f,p.headers[f]);if(p.beforeSend&&(p.beforeSend.call(d,w,p)===!1||2===x))return w.abort();T="abort";for(f in{success:1,error:1,complete:1})w[f](p[f]);if(i=L($n,p,n,w)){w.readyState=1,c&&h.trigger("ajaxSend",[w,p]),p.async&&p.timeout>0&&(u=setTimeout(function(){w.abort("timeout")},p.timeout));try{x=1,i.send(v,r)}catch(N){if(!(2>x))throw N;r(-1,N)}}else r(-1,"No Transport");return w},getScript:function(e,n){return st.get(e,t,n,"script")},getJSON:function(e,t,n){return st.get(e,t,n,"json")}}),st.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return st.globalEval(e),e}}}),st.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),st.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=V.head||st("head")[0]||V.documentElement;return{send:function(t,i){n=V.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Xn=[],Un=/(=)\?(?=&|$)|\?\?/;st.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xn.pop()||st.expando+"_"+Ln++;return this[e]=!0,e}}),st.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Un.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Un.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=st.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Un,"$1"+o):n.jsonp!==!1&&(n.url+=(Hn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||st.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Xn.push(o)),s&&st.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Vn,Yn,Jn=0,Gn=e.ActiveXObject&&function(){var e;for(e in Vn)Vn[e](t,!0)};st.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&_()||F()}:_,Yn=st.ajaxSettings.xhr(),st.support.cors=!!Yn&&"withCredentials"in Yn,Yn=st.support.ajax=!!Yn,Yn&&st.ajaxTransport(function(n){if(!n.crossDomain||st.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,f,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=st.noop,Gn&&delete Vn[a]),i)4!==u.readyState&&u.abort();else{f={},s=u.status,p=u.responseXML,c=u.getAllResponseHeaders(),p&&p.documentElement&&(f.xml=p),"string"==typeof u.responseText&&(f.text=u.responseText);try{l=u.statusText}catch(d){l=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=f.text?200:404}}catch(h){i||o(-1,h)}f&&o(s,l,f,c)},n.async?4===u.readyState?setTimeout(r):(a=++Jn,Gn&&(Vn||(Vn={},st(e).unload(Gn)),Vn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Qn,Kn,Zn=/^(?:toggle|show|hide)$/,er=RegExp("^(?:([+-])=|)("+ut+")([a-z%]*)$","i"),tr=/queueHooks$/,nr=[W],rr={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=er.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(st.cssNumber[e]?"":"px"),"px"!==r&&s){s=st.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,st.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};st.Animation=st.extend(P,{tweener:function(e,t){st.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],rr[n]=rr[n]||[],rr[n].unshift(t)},prefilter:function(e,t){t?nr.unshift(e):nr.push(e)}}),st.Tween=$,$.prototype={constructor:$,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(st.cssNumber[n]?"":"px")},cur:function(){var e=$.propHooks[this.prop];return e&&e.get?e.get(this):$.propHooks._default.get(this)},run:function(e){var t,n=$.propHooks[this.prop];return this.pos=t=this.options.duration?st.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):$.propHooks._default.set(this),this}},$.prototype.init.prototype=$.prototype,$.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=st.css(e.elem,e.prop,"auto"),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){st.fx.step[e.prop]?st.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[st.cssProps[e.prop]]||st.cssHooks[e.prop])?st.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},$.propHooks.scrollTop=$.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},st.each(["toggle","show","hide"],function(e,t){var n=st.fn[t];st.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(I(t,!0),e,r,i)}}),st.fn.extend({fadeTo:function(e,t,n,r){return this.filter(w).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=st.isEmptyObject(e),o=st.speed(t,n,r),a=function(){var t=P(this,st.extend({},e),o);a.finish=function(){t.stop(!0)},(i||st._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=st.timers,a=st._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&tr.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&st.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=st._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=st.timers,a=r?r.length:0;for(n.finish=!0,st.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),st.each({slideDown:I("show"),slideUp:I("hide"),slideToggle:I("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){st.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),st.speed=function(e,t,n){var r=e&&"object"==typeof e?st.extend({},e):{complete:n||!n&&t||st.isFunction(e)&&e,duration:e,easing:n&&t||t&&!st.isFunction(t)&&t};return r.duration=st.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in st.fx.speeds?st.fx.speeds[r.duration]:st.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){st.isFunction(r.old)&&r.old.call(this),r.queue&&st.dequeue(this,r.queue)},r},st.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},st.timers=[],st.fx=$.prototype.init,st.fx.tick=function(){var e,n=st.timers,r=0;for(Qn=st.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||st.fx.stop(),Qn=t},st.fx.timer=function(e){e()&&st.timers.push(e)&&st.fx.start()},st.fx.interval=13,st.fx.start=function(){Kn||(Kn=setInterval(st.fx.tick,st.fx.interval))},st.fx.stop=function(){clearInterval(Kn),Kn=null},st.fx.speeds={slow:600,fast:200,_default:400},st.fx.step={},st.expr&&st.expr.filters&&(st.expr.filters.animated=function(e){return st.grep(st.timers,function(t){return e===t.elem}).length}),st.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){st.offset.setOffset(this,e,t)});var n,r,i={top:0,left:0},o=this[0],a=o&&o.ownerDocument;if(a)return n=a.documentElement,st.contains(n,o)?(o.getBoundingClientRect!==t&&(i=o.getBoundingClientRect()),r=z(a),{top:i.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:i.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):i},st.offset={setOffset:function(e,t,n){var r=st.css(e,"position");"static"===r&&(e.style.position="relative");var i,o,a=st(e),s=a.offset(),u=st.css(e,"top"),l=st.css(e,"left"),c=("absolute"===r||"fixed"===r)&&st.inArray("auto",[u,l])>-1,f={},p={};c?(p=a.position(),i=p.top,o=p.left):(i=parseFloat(u)||0,o=parseFloat(l)||0),st.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+i),null!=t.left&&(f.left=t.left-s.left+o),"using"in t?t.using.call(e,f):a.css(f)}},st.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===st.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),st.nodeName(e[0],"html")||(n=e.offset()),n.top+=st.css(e[0],"borderTopWidth",!0),n.left+=st.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-st.css(r,"marginTop",!0),left:t.left-n.left-st.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||V.documentElement;e&&!st.nodeName(e,"html")&&"static"===st.css(e,"position");)e=e.offsetParent;return e||V.documentElement})}}),st.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);st.fn[e]=function(i){return st.access(this,function(e,i,o){var a=z(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?st(a).scrollLeft():o,r?o:st(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}}),st.each({Height:"height",Width:"width"},function(e,n){st.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){st.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return st.access(this,function(n,r,i){var o;return st.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?st.css(n,r,s):st.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=st,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return st})})(window); /*http://wiki.kumbiaphp.com/Licencia New BSD License*/ (function(a){a.KumbiaPHP={publicPath:null,plugin:[],cConfirm:function(b){var c=a(this);confirm(c.data("msg"))||b.preventDefault()},cFx:function(b){return function(c){c.preventDefault();c=a(this);a("#"+c.data("to"))[b]()}},cRemote:function(b){var c=a(this),c=a("#"+c.data("to"));b.preventDefault();c.load(this.href)},cRemoteConfirm:function(b){var c=a(this),d=a("#"+c.data("to"));b.preventDefault();confirm(c.data("msg"))&&d.load(this.href)},cFRemote:function(b){b.preventDefault();este=a(this);var c=a("[type=submit]", este);c.attr("disabled","disabled");b=este.attr("action");var d=este.attr("data-to");a.post(b,este.serialize(),function(b){var e=a("#"+d);e.html(b);e.hide();e.show("slow");c.attr("disabled",null)})},cUpdaterSelect:function(){var b=a(this),c=a("#"+b.data("update"));url=b.data("url");c.empty();a.get(url,{id:b.val()},function(b){for(i in b){var f=a("<option />").text(b[i]).val(i);c.append(f)}},"json")},bind:function(){a("a.js-confirm, input.js-confirm").on("click",this.cConfirm);a("a.js-remote").on("click", this.cRemote);a("a.js-remote-confirm").on("click",this.cRemoteConfirm);a("a.js-show").on("click",this.cFx("show"));a("a.js-hide").on("click",this.cFx("hide"));a("a.js-toggle").on("click",this.cFx("toggle"));a("a.js-fade-in").on("click",this.cFx("fadeIn"));a("a.js-fade-out").on("click",this.cFx("fadeOut"));a("form.js-remote").on("submit",this.cFRemote);a("select.js-remote").on("change",this.cUpdaterSelect);a.KumbiaPHP.bindDatePicker()},autoload:function(){var b=a("[class*='jp-']");a.each(b,function(b){var d= a(this).attr("class").split(" ");for(b in d)"jp-"==d[b].substr(0,3)&&-1==a.inArray(d[b].substr(3),a.KumbiaPHP.plugin)&&a.KumbiaPHP.plugin.push(d[b].substr(3))});b=a("head");for(i in a.KumbiaPHP.plugin)a.ajaxSetup({cache:!0}),b.append('<link href="'+a.KumbiaPHP.publicPath+"css/"+a.KumbiaPHP.plugin[i]+'.css" type="text/css" rel="stylesheet"/>'),a.getScript(a.KumbiaPHP.publicPath+"javascript/jquery/jquery."+a.KumbiaPHP.plugin[i]+".js",function(){})},bindDatePicker:function(){var b=a("input.js-datepicker"), c=function(){b.each(function(){var b={monthSelector:!0,yearSelector:!0},c=a(this);void 0!=c.attr("min")&&(b.dateMin=c.attr("min").split("-"));void 0!=c.attr("max")&&(b.dateMax=c.attr("max").split("-"));c.pickadate(b)})};if("undefined"!=typeof a.pickadate)return c();a("head").append('<link href="'+this.publicPath+'css/pickadate.css" type="text/css" rel="stylesheet"/>');jQuery.ajax({dataType:"script",cache:!0,url:this.publicPath+"javascript/jquery/pickadate.js"}).done(function(){c()})},initialize:function(){var b= a("script:last").attr("src");this.publicPath=b.substr(0,b.length-37);a(function(){a.KumbiaPHP.bind();a.KumbiaPHP.autoload()})}};a.KumbiaPHP.initialize()})(jQuery);
clients/packages/admin-client/src/pages/admin/mobilizations/settings/metrics/page.js
nossas/bonde-client
import React from 'react'; // import { MetricsMobilization } from '../../../../../components/metrics' import { Title } from '../../../../../components/title'; const MobilizationsSettingsMetricsPage = () => ( <React.Fragment> <Title>Métricas</Title> <h3>Override MetricsMobilization</h3> {/* <MetricsMobilization mobilizationId={props.mobilization.id} /> */} </React.Fragment> ); export default MobilizationsSettingsMetricsPage;
containers/AddTodo.js
tim-speed/manifold-todo
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }} > <input ref={node => { input = node }} /> <button type='submit'> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) AddTodo.propTypes = { dispatch: PropTypes.func } export default AddTodo
app/javascript/mastodon/features/favourites/index.js
pso2club/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavourites } from '../../actions/interactions'; import { FormattedMessage } from 'react-intl'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ScrollableList from '../../components/scrollable_list'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]), }); export default @connect(mapStateToProps) class Favourites extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, accountIds: ImmutablePropTypes.list, }; componentWillMount () { this.props.dispatch(fetchFavourites(this.props.params.statusId)); } componentWillReceiveProps (nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(nextProps.params.statusId)); } } render () { const { shouldUpdateScroll, accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.favourites' defaultMessage='No one has favourited this toot yet. When someone does, they will show up here.' />; return ( <Column> <ColumnBackButton /> <ScrollableList scrollKey='favourites' shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} > {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} /> )} </ScrollableList> </Column> ); } }
es/components/FooterBar/Eta.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import compose from 'recompose/compose'; import pure from 'recompose/pure'; import formatDuration from 'format-duration'; import timed from '../../utils/timed'; var Eta = function Eta(_ref) { var className = _ref.className, base = _ref.base, currentTime = _ref.currentTime, endTime = _ref.endTime; var currentRemaining = endTime - currentTime; return _jsx("span", { className: cx('Eta', className) }, void 0, formatDuration(base + currentRemaining)); }; Eta.propTypes = process.env.NODE_ENV !== "production" ? { className: PropTypes.string, currentTime: PropTypes.number.isRequired, endTime: PropTypes.number, base: PropTypes.number } : {}; export default compose(timed(), pure)(Eta); //# sourceMappingURL=Eta.js.map
archimate-frontend/src/main/javascript/components/view/nodes/model_m/meaning.js
zhuj/mentha-web-archimate
import React from 'react' import { shape } from 'svg-intersections' import { ModelNodeWidget } from '../BaseNodeWidget' export const TYPE='meaning'; export class MeaningWidget extends ModelNodeWidget { getClassName(node) { return 'a-node model_m meaning'; } borderPath(node) { const w = (node.width || 0)/800.0; const h = (node.height || 0)/600.0; // special thx to https://codepen.io/anthonydugois/pen/mewdyZ return ( `M ${w*50} ${h*250} `+ `Q ${-w*50} ${-h*50} ${w*200} ${h*50} `+ `Q ${w*300} ${-h*50} ${w*500} ${h*50} `+ `Q ${w*900} ${-h*50} ${w*750} ${h*350} `+ `Q ${w*850} ${h*600} ${w*600} ${h*550} `+ `Q ${w*500} ${h*650} ${w*250} ${h*550} `+ `Q ${-w*100} ${h*650} ${w*50} ${h*250}` ); } // TODO: make 'svg-intersections' work with Q-paths // borderShape(node) { // return shape("path", {d: this.borderPath(node) }); // } renderBorder(node) { return ( <svg className="border"> <path d={this.borderPath(node)} stroke="black" strokeWidth={1}/> </svg> ); } }
ajax/libs/vue/2.5.1/vue.esm.js
sufuf3/cdnjs
/*! * Vue.js v2.5.1 * (c) 2014-2017 Evan You * Released under the MIT License. */ /* */ // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value e.g. [object Object] */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind, faster than native */ function bind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ var emptyObject = Object.freeze({}); /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm || {}; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ function handleError (err, vm, info) { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { logError(e, null, 'config.errorHandler'); } } logError(err, vm, info); } function logError (err, vm, info) { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if (inBrowser && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ /* globals MessageChannel */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // An asynchronous deferring mechanism. // In pre 2.4, we used to use microtasks (Promise/MutationObserver) // but microtasks actually has too high a priority and fires in between // supposedly sequential events (e.g. #4521, #6690) or even between // bubbling of the same event (#6566). Technically setImmediate should be // the ideal choice, but it's not available everywhere; and the only polyfill // that consistently queues the callback after all DOM events triggered in the // same loop is by using MessageChannel. /* istanbul ignore if */ if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { timerFunc = function () { setImmediate(nextTickHandler); }; } else if (typeof MessageChannel !== 'undefined' && ( isNative(MessageChannel) || // PhantomJS MessageChannel.toString() === '[object MessageChannelConstructor]' )) { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = nextTickHandler; timerFunc = function () { port.postMessage(1); }; } else /* istanbul ignore next */ if (typeof Promise !== 'undefined' && isNative(Promise)) { // use microtask in non-DOM environments, e.g. Weex var p = Promise.resolve(); timerFunc = function () { p.then(nextTickHandler); }; } else { // fallback to setTimeout timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve, reject) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.functionalOptions = undefined; this.functionalScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode, deep) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.isCloned = true; if (deep && vnode.children) { cloned.children = cloneVNodes(vnode.children); } return cloned } function cloneVNodes (vnodes, deep) { var len = vnodes.length; var res = new Array(len); for (var i = 0; i < len; i++) { res[i] = cloneVNode(vnodes[i], deep); } return res } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src, keys) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (hasOwn(target, key)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this) : childVal, typeof parentVal === 'function' ? parentVal.call(this) : parentVal ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn.call(this, parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { process.env.NODE_ENV !== 'production' && assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && process.env.NODE_ENV !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else if (process.env.NODE_ENV !== 'production') { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else if (process.env.NODE_ENV !== 'production' && inject) { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (process.env.NODE_ENV !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')) + ", got " + (toRawType(value)) + ".", vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isType (type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type) } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true } } /* istanbul ignore next */ return false } /* */ var mark; var measure; if (process.env.NODE_ENV !== 'production') { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { cloned[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments) } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, lastIndex, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } lastIndex = res.length - 1; last = res[lastIndex]; // nested if (Array.isArray(c)) { if (c.length > 0) { c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)); // merge adjacent text nodes if (isTextNode(c[0]) && isTextNode(last)) { res[lastIndex] = createTextVNode(last.text + (c[0]).text); c.shift(); } res.push.apply(res, c); } } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings res[lastIndex] = createTextVNode(last.text + c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[lastIndex] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function ensureCtor (comp, base) { if ( comp.__esModule || (hasSymbol && comp[Symbol.toStringTag] === 'Module') ) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp } function createAsyncPlaceholder ( factory, data, context, children, tag ) { var node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data: data, context: context, children: children, tag: tag }; return node } function resolveAsyncComponent ( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { var contexts = factory.contexts = [context]; var sync = true; var forceRender = function () { for (var i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); var reject = once(function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); var res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function () { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function () { if (isUndef(factory.resolved)) { reject( process.env.NODE_ENV !== 'production' ? ("timeout (" + (res.timeout) + "ms)") : null ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function isAsyncPlaceholder (node) { return node.isComment && node.asyncFactory } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn, once) { if (once) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var this$1 = this; var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var this$1 = this; var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$off(event[i], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } if (fn) { // specific handler var cb; var i$1 = cbs.length; while (i$1--) { cb = cbs[i$1]; if (cb === fn || cb.fn === fn) { cbs.splice(i$1, 1); break } } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; if (process.env.NODE_ENV !== 'production') { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { try { cbs[i].apply(vm, args); } catch (e) { handleError(e, vm, ("event handler for \"" + event + "\"")); } } } return vm }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } var defaultSlot = []; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var data = child.data; // remove slot attribute if the node is resolved as a Vue slot node if (data && data.attrs && data.attrs.slot) { delete data.attrs.slot; } // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && data && data.slot != null ) { var name = child.data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore whitespace if (!defaultSlot.every(isWhitespace)) { slots.default = defaultSlot; } return slots } function isWhitespace (node) { return node.isComment || node.text === ' ' } function resolveScopedSlots ( fns, // see flow/vnode res ) { res = res || {}; for (var i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res } /* */ var activeInstance = null; var isUpdatingChildComponent = false; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null; } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // release circular reference (#6759) if (vm.$vnode) { vm.$vnode.parent = null; } }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure(("vue " + name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure(("vue " + name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } vm._watcher = new Watcher(vm, updateComponent, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren var hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listeners hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = (parentVnode.data && parentVnode.data.attrs) || emptyObject; vm.$listeners = listeners || emptyObject; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; props[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } if (process.env.NODE_ENV !== 'production') { isUpdatingChildComponent = false; } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + " hook")); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } else { throw e } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { var hyphenatedKey = hyphenate(key); if (isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) { warn( ("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive(props, key, value, function () { if (vm.$parent && !isUpdatingChildComponent) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); observerState.shouldConvert = true; } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var methods = vm.$options.methods; var i = keys.length; while (i--) { var key = keys[i]; if (process.env.NODE_ENV !== 'production') { if (methods && hasOwn(methods, key)) { warn( ("Method \"" + key + "\" has already been defined as a data property."), vm ); } } if (props && hasOwn(props, key)) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + key + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(key)) { proxy(vm, "_data", key); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { try { return data.call(vm, vm) } catch (e) { handleError(e, vm, "data()"); return {} } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { var watchers = vm._computedWatchers = Object.create(null); // computed properties are just getters during SSR var isSSR = isServerRendering(); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (process.env.NODE_ENV !== 'production' && getter == null) { warn( ("Getter is missing for computed property \"" + key + "\"."), vm ); } if (!isSSR) { // create internal watcher for the computed property. watchers[key] = new Watcher( vm, getter || noop, noop, computedWatcherOptions ); } // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else if (process.env.NODE_ENV !== 'production') { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed ( target, key, userDef ) { var shouldCache = !isServerRendering(); if (typeof userDef === 'function') { sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : userDef; sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? shouldCache && userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } if (process.env.NODE_ENV !== 'production' && sharedPropertyDefinition.set === noop) { sharedPropertyDefinition.set = function () { warn( ("Computed property \"" + key + "\" was assigned to but it has no setter."), this ); }; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { if (process.env.NODE_ENV !== 'production') { if (methods[key] == null) { warn( "Method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("Method \"" + key + "\" has already been defined as a prop."), vm ); } if ((key in vm) && isReserved(key)) { warn( "Method \"" + key + "\" conflicts with an existing Vue instance method. " + "Avoid defining component methods that start with _ or $." ); } } vm[key] = methods[key] == null ? noop : bind(methods[key], vm); } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher ( vm, keyOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(keyOrFn, handler, options) } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options) } options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { observerState.shouldConvert = false; Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } else { defineReactive(vm, key, result[key]); } }); observerState.shouldConvert = true; } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached var result = Object.create(null); var keys = hasSymbol ? Reflect.ownKeys(inject).filter(function (key) { /* istanbul ignore next */ return Object.getOwnPropertyDescriptor(inject, key).enumerable }) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var provideKey = inject[key].from; var source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break } source = source.$parent; } if (!source) { if ('default' in inject[key]) { var provideDefault = inject[key].default; result[key] = typeof provideDefault === 'function' ? provideDefault.call(vm) : provideDefault; } else if (process.env.NODE_ENV !== 'production') { warn(("Injection \"" + key + "\" not found"), vm); } } } return result } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } props = extend(extend({}, bindObject), props); } return scopedSlotFn(props) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ /** * Runtime helper for checking keyCodes from config. * exposed as Vue.prototype._k * passing in eventKeyName as last argument separately for backwards compat */ function checkKeyCodes ( eventKeyCode, key, builtInAlias, eventKeyName ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (keyCodes) { if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } } else if (eventKeyName) { return hyphenate(eventKeyName) !== key } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; var loop = function ( key ) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; if (isSync) { var on = data.on || (data.on = {}); on[("update:" + key)] = function ($event) { value[key] = $event; }; } } }; for (var key in value) loop( key ); } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { // static trees can be rendered once and cached on the contructor options // so every instance shares the same cached trees var renderFns = this.$options.staticRenderFns; var cached = renderFns.cached || (renderFns.cached = []); var tree = cached[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = cached[index] = renderFns[index].call(this._renderProxy, null, this); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners (data, value) { if (value) { if (!isPlainObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-on without argument expects an Object value', this ); } else { var on = data.on = data.on ? extend({}, data.on) : {}; for (var key in value) { var existing = on[key]; var ours = value[key]; on[key] = existing ? [].concat(existing, ours) : ours; } } } return data } /* */ function installRenderHelpers (target) { target._o = markOnce; target._n = toNumber; target._s = toString; target._l = renderList; target._t = renderSlot; target._q = looseEqual; target._i = looseIndexOf; target._m = renderStatic; target._f = resolveFilter; target._k = checkKeyCodes; target._b = bindObjectProps; target._v = createTextVNode; target._e = createEmptyVNode; target._u = resolveScopedSlots; target._g = bindObjectListeners; } /* */ function FunctionalRenderContext ( data, props, children, parent, Ctor ) { var options = Ctor.options; this.data = data; this.props = props; this.children = children; this.parent = parent; this.listeners = data.on || emptyObject; this.injections = resolveInject(options.inject, parent); this.slots = function () { return resolveSlots(children, parent); }; // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var contextVm = Object.create(parent); var isCompiled = isTrue(options._compiled); var needNormalization = !isCompiled; // support for compiled functional template if (isCompiled) { // exposing $options for renderStatic() this.$options = options; // pre-resolve slots for renderSlot() this.$slots = this.slots(); this.$scopedSlots = data.scopedSlots || emptyObject; } if (options._scopeId) { this._c = function (a, b, c, d) { var vnode = createElement(contextVm, a, b, c, d, needNormalization); if (vnode) { vnode.functionalScopeId = options._scopeId; vnode.functionalContext = parent; } return vnode }; } else { this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); }; } } installRenderHelpers(FunctionalRenderContext.prototype); function createFunctionalComponent ( Ctor, propsData, data, contextVm, children ) { var options = Ctor.options; var props = {}; var propOptions = options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || emptyObject); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } var renderContext = new FunctionalRenderContext( data, props, children, contextVm, Ctor ); var vnode = options.render.call(null, renderContext._c, renderContext); if (vnode instanceof VNode) { vnode.functionalContext = contextVm; vnode.functionalOptions = options; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ // hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component var asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow var slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }, asyncFactory ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = componentVNodeHooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (isDef(vnode)) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns, force) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject ns = undefined; force = true; } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && (isUndef(child.ns) || isTrue(force))) { applyNS(child, ns, force); } } } } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree var options = vm.$options; var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated var parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () { !isUpdatingChildComponent && warn("$attrs is readonly.", vm); }, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, function () { !isUpdatingChildComponent && warn("$listeners is readonly.", vm); }, true); } else { defineReactive(vm, '$attrs', parentData && parentData.attrs || emptyObject, null, true); defineReactive(vm, '$listeners', options._parentListeners || emptyObject, null, true); } } function renderMixin (Vue) { // install runtime convenience helpers installRenderHelpers(Vue.prototype); Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // if the parent didn't update, the slot nodes will be the ones from // last render. They need to be cloned to ensure "freshness" for this render. for (var key in vm.$slots) { var slot = vm.$slots[key]; if (slot._rendered) { vm.$slots[key] = cloneVNodes(slot, true /* deep */); } } } vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject; // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e); } catch (e) { handleError(e, vm, "renderError"); vnode = vm._vnode; } } else { vnode = vm._vnode; } } else { vnode = vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; } /* */ var uid$1 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$1++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-start:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(("vue " + (vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var extended = Ctor.extendOptions; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified } function dedupe (latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { var res = []; sealed = Array.isArray(sealed) ? sealed : [sealed]; extended = Array.isArray(extended) ? extended : [extended]; for (var i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res } else { return latest } } function Vue$3 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$3) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1 } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (keepAliveInstance, filter) { var cache = keepAliveInstance.cache; var keys = keepAliveInstance.keys; var _vnode = keepAliveInstance._vnode; for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cache, key, keys, _vnode); } } } } function pruneCacheEntry ( cache, key, keys, current ) { var cached$$1 = cache[key]; if (cached$$1 && cached$$1 !== current) { cached$$1.componentInstance.$destroy(); } cache[key] = null; remove(keys, key); } var patternTypes = [String, RegExp, Array]; var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, max: [String, Number] }, created: function created () { this.cache = Object.create(null); this.keys = []; }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache, key, this$1.keys); } }, watch: { include: function include (val) { pruneCache(this, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this, function (name) { return !matches(val, name); }); } }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var ref = this; var cache = ref.cache; var keys = ref.keys; var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (cache[key]) { vnode.componentInstance = cache[key].componentInstance; // make current key freshest remove(keys, key); keys.push(key); } else { cache[key] = vnode; keys.push(key); // prune oldest entry if (this.max && keys.length > parseInt(this.max)) { pruneCacheEntry(cache, keys[0], keys, this._vnode); } } vnode.data.keepAlive = true; } return vnode } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue$3.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext } }); Vue$3.version = '2.5.1'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select,progress'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function renderClass ( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (Array.isArray(value)) { return stringifyArray(value) } if (isObject(value)) { return stringifyObject(value) } if (typeof value === 'string') { return value } /* istanbul ignore next */ return '' } function stringifyArray (value) { var res = ''; var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res } function stringifyObject (value) { var res = ''; for (var key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } var isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ref]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ) } function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove () { if (--remove.listeners === 0) { removeNode(childElm); } } remove.listeners = listeners; return remove } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !( config.ignoredElements.length && config.ignoredElements.some(function (ignore) { return isRegExp(ignore) ? ignore.test(tag) : ignore === tag }) ) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (ref$$1.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.functionalScopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } else { var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } ancestor = ancestor.parent; } } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.functionalContext && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, vnodeToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx); if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } else { vnodeToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !vnodeToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(vnodeToMove, newStartVnode)) { patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm); } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); } } newStartVnode = newCh[++newStartIdx]; } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function findIdxInOld (node, oldCh, start, end) { for (var i = start; i < end; i++) { var c = oldCh[i]; if (isDef(c) && sameVnode(node, c)) { return i } } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } var elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.elm = elm; vnode.isAsyncPlaceholder = true; return true } if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { // v-html and domProps: innerHTML if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) { if (i !== elm.innerHTML) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('server innerHTML: ', i); console.warn('client innerHTML: ', elm.innerHTML); } return false } } else { // iterate and compare children lists var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } } if (isDef(data)) { for (var key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode) { if (isDef(vnode.tag)) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); if (isDef(vnode.parent)) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; var patchable = isPatchable(vnode); while (ancestor) { for (var i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](ancestor); } ancestor.elm = vnode.elm; if (patchable) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, ancestor); } // #6513 // invoke insert hooks that may have been merged by create hooks. // e.g. for directives that uses the "inserted" hook. var insert = ancestor.data.hook.insert; if (insert.merged) { // start at index 1 to avoid re-invoking component mounted hook for (var i$2 = 1; i$2 < insert.fns.length; i$2++) { insert.fns[i$2](); } } } else { registerRef(ancestor); } ancestor = ancestor.parent; } } if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { var opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] // #6666: IE/Edge forces progress value down to 1 before setting a max /* istanbul ignore if */ if ((isIE9 || isEdge) && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { // technically allowfullscreen is a boolean attribute for <iframe>, // but Flash expects a value of "true" when used on <embed> tag value = key === 'allowfullscreen' && el.tagName === 'EMBED' ? 'true' : key; el.setAttribute(key, value); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ function baseWarn (msg) { console.error(("[Vue compiler]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important, warn ) { // warn prevent and passive modifier /* istanbul ignore if */ if ( process.env.NODE_ENV !== 'production' && warn && modifiers && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers && modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } var events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value, modifiers: modifiers }; var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } // note: this only removes the attr from the Array (attrsList) so that it // doesn't get processed by processAttrs. // By default it does NOT remove it from the map (attrsMap) because the map is // needed during codegen. function getAndRemoveAttr ( el, name, removeFromMap ) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } if (removeFromMap) { delete el.attrsMap[name]; } return val } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: ("\"" + value + "\""), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var res = parseModel(value); if (res.key === null) { return (value + "=" + assignment) } else { return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")") } } /** * Parse a v-model expression into a base path and a final key segment. * Handles both dot-path and possible square brackets. * * Possible cases: * * - test * - test[key] * - test[test1[key]] * - test["a"][key] * - xxx.test[a[a].test1[key]] * - test.xxx.a["asa"][test1[key]] * */ var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; function parseModel (val) { len = val.length; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { index$1 = val.lastIndexOf('.'); if (index$1 > -1) { return { exp: val.slice(0, index$1), key: '"' + val.slice(index$1 + 1) + '"' } } else { return { exp: val, key: null } } } str = val; index$1 = expressionPos = expressionEndPos = 0; while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.slice(0, expressionPos), key: val.slice(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (process.env.NODE_ENV !== 'production') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'change', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$el.checked){$$i<0&&(" + value + "=$$a.concat([$$v]))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event var event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } // This was originally intended to fix #4521 but no longer necessary // after 2.5. Keeping it for backwards compat with generated code from < 2.4 /* istanbul ignore if */ if (isDef(on[CHECKBOX_RADIO_TOKEN])) { on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function add$1 ( event, handler, once$$1, capture, passive ) { if (once$$1) { var oldHandler = handler; var _target = target$1; // save current target element in closure handler = function (ev) { var res = arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); if (res !== null) { remove$2(event, handler, capture, _target); } }; } target$1.addEventListener( event, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener(event, handler, capture); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } // #6601 work around Chrome version <= 55 bug where single textNode // replaced by innerHTML/textContent retains its parentNode property if (elm.childNodes.length === 1) { elm.removeChild(elm.childNodes[0]); } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue (elm, checkVal) { return (!elm.composing && ( elm.tagName === 'OPTION' || isDirty(elm, checkVal) || isInputChanged(elm, checkVal) )) } function isDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value var notInFocus = true; // #6157 // work around IE bug when accessing document.activeElement in an iframe try { notInFocus = document.activeElement !== elm; } catch (e) {} return notInFocus && elm.value !== checkVal } function isInputChanged (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers) && modifiers.number) { return toNumber(value) !== toNumber(newVal) } if (isDef(modifiers) && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var vendorNames = ['Webkit', 'Moz', 'ms']; var emptyStyle; var normalize = cached(function (prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop } var capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < vendorNames.length; i++) { var name = vendorNames[i] + capName; if (name in emptyStyle) { return name } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likely wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition (def) { if (!def) { return } /* istanbul ignore else */ if (typeof def === 'object') { var res = {}; if (def.css !== false) { extend(res, autoCssTransition(def.name || 'v')); } extend(res, def); return res } else if (typeof def === 'string') { return autoCssTransition(def) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function (fn) { return fn(); }; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { var transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model$1 = { inserted: function inserted (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); el._vOptions = [].map.call(el.options, getValue); } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var prevOptions = el._vOptions; var curOptions = el._vOptions = [].map.call(el.options, getValue); if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) { // trigger change event if // no matching option found for at least one value var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions); if (needReset) { trigger(el, 'change'); } } } } }; function setSelected (el, binding, vm) { actuallySetSelected(el, binding, vm); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(function () { actuallySetSelected(el, binding, vm); }, 0); } } function actuallySetSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { return options.every(function (o) { return !looseEqual(o, value); }) } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition$$1 = vnode.data && vnode.data.transition; if (transition$$1) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: model$1, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$options._renderChildren; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag || isAsyncPlaceholder(c); }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) ) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild.data.transition = extend({}, data); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild } var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position // assign to this to avoid being removed in tree-shaking // $flow-disable-line this._reflow = document.body.offsetHeight; children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.mustUseProp = mustUseProp; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.isReservedAttr = isReservedAttr; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ Vue$3.nextTick(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if (process.env.NODE_ENV !== 'production' && isChrome) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (process.env.NODE_ENV !== 'production' && config.productionTip !== false && inBrowser && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode (content, encoded) { var div = document.createElement('div'); div.innerHTML = "<div a=\"" + content + "\"/>"; return div.innerHTML.indexOf(encoded) > 0 } // #3663 // IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$1 }; /* */ var decoder; var he = { decode: function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } }; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/; // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")"; var startTagOpen = new RegExp(("^<" + qnameCapture)); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>")); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g; // #5992 var isIgnoreNewlineTag = makeMap('pre,textarea', true); var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } continue } } var text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while ( !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var rest$1 = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(he.decode); // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; function createASTElement ( tag, attrs, parent ) { return { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: parent, children: [] } } /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg) { if (!warned) { warned = true; warn$2(msg); } } function endPre (element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldKeepComment: options.comments, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = createASTElement(tag, attrs, currentParent); if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { element = preTransforms[i](element, options) || element; } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else if (!element.processed) { // structural directives processFor(element); processIf(element); processOnce(element); // element-scope stuff processElement(element, options); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { endPre(element); } // apply post-transforms for (var i$1 = 0; i$1 < postTransforms.length; i$1++) { postTransforms[i$1](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; endPre(element); }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } }, comment: function comment (text) { currentParent.children.push({ type: 3, text: text, isComment: true }); } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processElement (element, options) { processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !element.attrsList.length; processRef(element); processSlot(element); processComponent(element); for (var i = 0; i < transforms.length; i++) { element = transforms[i](element, options) || element; } processAttrs(element); } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$2("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { process.env.NODE_ENV !== 'production' && warn$2( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotScope; if (el.tag === 'template') { slotScope = getAndRemoveAttr(el, 'scope'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && slotScope) { warn$2( "the \"scope\" attribute for scoped slots have been deprecated and " + "replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " + "can also be used on plain elements in addition to <template> to " + "denote scoped slots.", true ); } el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope'); } else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) { el.slotScope = slotScope; } var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; // preserve slot as an attribute for native shadow DOM compat // only for non-scoped slots. if (!el.slotScope) { addAttr(el, 'slot', slotTarget); } } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ("update:" + (camelize(name))), genAssignmentCode(value, "$event") ); } } if (isProp || ( !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var expression = parseText(value, delimiters); if (expression) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ /** * Expand input[v-model] with dyanmic type bindings into v-if-else chains * Turn this: * <input v-model="data[type]" :type="type"> * into this: * <input v-if="type === 'checkbox'" type="checkbox" v-model="data[type]"> * <input v-else-if="type === 'radio'" type="radio" v-model="data[type]"> * <input v-else :type="type" v-model="data[type]"> */ function preTransformNode (el, options) { if (el.tag === 'input') { var map = el.attrsMap; if (map['v-model'] && (map['v-bind:type'] || map[':type'])) { var typeBinding = getBindingAttr(el, 'type'); var ifCondition = getAndRemoveAttr(el, 'v-if', true); var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : ""; // 1. checkbox var branch0 = cloneASTElement(el); // process for on the main node processFor(branch0); addRawAttr(branch0, 'type', 'checkbox'); processElement(branch0, options); branch0.processed = true; // prevent it from double-processed branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra; addIfCondition(branch0, { exp: branch0.if, block: branch0 }); // 2. add radio else-if condition var branch1 = cloneASTElement(el); getAndRemoveAttr(branch1, 'v-for', true); addRawAttr(branch1, 'type', 'radio'); processElement(branch1, options); addIfCondition(branch0, { exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra, block: branch1 }); // 3. other var branch2 = cloneASTElement(el); getAndRemoveAttr(branch2, 'v-for', true); addRawAttr(branch2, ':type', typeBinding); processElement(branch2, options); addIfCondition(branch0, { exp: ifCondition, block: branch2 }); return branch0 } } } function cloneASTElement (el) { return createASTElement(el.tag, el.attrsList.slice(), el.parent) } function addRawAttr (el, name, value) { el.attrsMap[name] = value; el.attrsList.push({ name: name, value: value }); } var model$2 = { preTransformNode: preTransformNode }; var modules$1 = [ klass$1, style$1, model$2 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { var block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative, warn ) { var res = isNative ? 'nativeOn:{' : 'on:{'; for (var name in events) { var handler = events[name]; // #5330: warn click.right, since right clicks do not actually fire click events. if (process.env.NODE_ENV !== 'production' && name === 'click' && handler && handler.modifiers && handler.modifiers.right ) { warn( "Use \"contextmenu\" instead of \"click.right\" since right clicks " + "do not actually fire \"click\" events." ); } res += "\"" + name + "\":" + (genHandler(name, handler)) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { return isMethodPath || isFunctionExpression ? handler.value : ("function($event){" + (handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else if (key === 'exact') { var modifiers = (handler.modifiers); genModifierCode += genGuard( ['ctrl', 'shift', 'alt', 'meta'] .filter(function (keyModifier) { return !modifiers[keyModifier]; }) .map(function (keyModifier) { return ("$event." + keyModifier + "Key"); }) .join('||') ); } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? handler.value + '($event)' : isFunctionExpression ? ("(" + (handler.value) + ")($event)") : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var code = keyCodes[key]; return ( "_k($event.keyCode," + (JSON.stringify(key)) + "," + (JSON.stringify(code)) + "," + "$event.key)" ) } /* */ function on (el, dir) { if (process.env.NODE_ENV !== 'production' && dir.modifiers) { warn("v-on without argument does not support modifiers."); } el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); }; } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")") }; } /* */ var baseDirectives = { on: on, bind: bind$1, cloak: noop }; /* */ var CodegenState = function CodegenState (options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); var isReservedTag = options.isReservedTag || no; this.maybeComponent = function (el) { return !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; }; function generate ( ast, options ) { var state = new CodegenState(options); var code = ast ? genElement(ast, state) : '_c("div")'; return { render: ("with(this){return " + code + "}"), staticRenderFns: state.staticRenderFns } } function genElement (el, state) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state) } else if (el.once && !el.onceProcessed) { return genOnce(el, state) } else if (el.for && !el.forProcessed) { return genFor(el, state) } else if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el, state) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el, state) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el, state); } else { var data = el.plain ? undefined : genData$2(el, state); var children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el, state) { el.staticProcessed = true; state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}")); return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && state.warn( "v-once can only be used inside v-for that is keyed. " ); return genElement(el, state) } return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")") } else { return genStatic(el, state) } } function genIf ( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty) } function genIfConditions ( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state) } } function genFor ( el, state, altGen, altHelper ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if (process.env.NODE_ENV !== 'production' && state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + "((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + ((altGen || genElement)(el, state)) + '})' } function genData$2 (el, state) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events, false, state.warn)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, state.warn)) + ","; } // slot target // only for non-scoped slots if (el.slotTarget && !el.slotScope) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots, state)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data } function genDirectives (el, state) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el, state) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length !== 1 || ast.type !== 1 )) { state.warn('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, state.options); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots ( slots, state ) { return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key], state) }).join(',')) + "])") } function genScopedSlot ( key, el, state ) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el, state) } var fn = "function(" + (String(el.slotScope)) + "){" + "return " + (el.tag === 'template' ? el.if ? ((el.if) + "?" + (genChildren(el, state) || 'undefined') + ":undefined") : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}"; return ("{key:" + key + ",fn:" + fn + "}") } function genForScopedSlot ( key, el, state ) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genScopedSlot(key, el, state)) + '})' } function genChildren ( el, state, checkSkip, altGenElement, altGenNode ) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return (altGenElement || genElement)(el$1, state) } var normalizationType = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; var gen = altGenNode || genNode; return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType ( children, maybeComponent ) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function genNode (node, state) { if (node.type === 1) { return genElement(node, state) } if (node.type === 3 && node.isComment) { return genComment(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genComment (comment) { return ("_e(" + (JSON.stringify(comment.text)) + ")") } function genSlot (el, state) { var slotName = el.slotName || '"default"'; var children = genChildren(el, state); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent ( componentName, el, state ) { var children = el.inlineTemplate ? null : genChildren(el, state, true); return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent (exp, text, errors) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim()))); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()) ); } else { errors.push( "invalid expression: " + (e.message) + " in\n\n" + " " + exp + "\n\n" + " Raw expression: " + (text.trim()) + "\n" ); } } } /* */ function createFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompileToFunctionFn (compile) { var cache = Object.create(null); return function compileToFunctions ( template, options, vm ) { options = extend({}, options); var warn$$1 = options.warn || warn; delete options.warn; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn$$1( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips if (process.env.NODE_ENV !== 'production') { if (compiled.errors && compiled.errors.length) { warn$$1( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function (code) { return createFunction(code, fnGenErrors) }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn$$1( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (cache[key] = res) } } /* */ function createCompilerCreator (baseCompile) { return function createCompiler (baseOptions) { function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; finalOptions.warn = function (msg, tip) { (tip ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } var compiled = baseCompile(template, finalOptions); if (process.env.NODE_ENV !== 'production') { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled } return { compile: compile, compileToFunctions: createCompileToFunctionFn(compile) } } } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. var createCompiler = createCompilerCreator(function baseCompile ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } }); /* */ var ref$1 = createCompiler(baseOptions); var compileToFunctions = ref$1.compileToFunctions; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { shouldDecodeNewlines: shouldDecodeNewlines, delimiters: options.delimiters, comments: options.comments }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile end'); measure(("vue " + (this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; export default Vue$3;
client/app/components/NavBar/index.js
yanhao-li/menu-plus
import React from 'react'; import { Link } from 'react-router'; import UserNav from 'components/NavBar/UserNav'; import GuestNav from 'components/NavBar/GuestNav'; import AppBar from 'material-ui/AppBar'; import logo from './logo.svg'; const styles = { navbar: { backgroundColor: 'white', display: 'flex', alignItems: 'center', paddingLeft: '80px', paddingRight: '80px', }, }; class NavBar extends React.PureComponent { render() { const { isAuthenticated } = this.props.auth; return ( <AppBar title={<Link to="/" style={{ fontSize: 18, color: '#a7a7a7' }}>Zarmno</Link>} showMenuIconButton iconElementLeft={ <img src={logo} width={40} alt="logo" /> } iconElementRight={ isAuthenticated ? <UserNav {...this.props} /> : <GuestNav {...this.props} /> } iconStyleLeft={{ marginTop: 0 }} iconStyleRight={{ margin: 0 }} style={styles.navbar} /> ); } } NavBar.propTypes = { auth: React.PropTypes.object.isRequired, }; export default NavBar;
packages/cf-component-page/test/Page.js
mdno/mdno.github.io
import React from 'react'; import renderer from 'react-test-renderer'; import { Page } from '../src/index'; import { felaSnapshot } from 'cf-style-provider'; test('should render', () => { const snapshot = felaSnapshot(<Page>Hello World</Page>); expect(snapshot.component).toMatchSnapshot(); expect(snapshot.styles).toMatchSnapshot(); });
src/components/About/Education/Education.js
jumpalottahigh/jumpalottahigh.github.io
import React from 'react' import styled from 'styled-components' import Img from 'gatsby-image' import { graphql, StaticQuery } from 'gatsby' import H2 from '../../elements/H2/H2.js' import CenteredDiv from '../../elements/CenteredDiv/CenteredDiv.js' const UL = styled.ul` display: grid; grid-gap: 10px; padding-left: 20px; ` const Diploma = styled.div` display: flex; .diploma-image { width: 74px; height: 100px; margin-right: 20px; } p { font-weight: bold; margin: 0; align-self: center; } ` export default () => ( <StaticQuery query={graphql` query { allFile(filter: { relativePath: { regex: "/education/" } }) { edges { node { id name childImageSharp { # Specify the image processing specifications right in the query. # Makes it trivial to update as your page's design changes. fluid(maxWidth: 74) { ...GatsbyImageSharpFluid_withWebp } } } } } } `} render={data => ( <section> <H2>&#123; Education &#125;</H2> <CenteredDiv> <p className="highlight"> I believe strongly in life-long education and therefor regularly partake in different courses </p> <UL> <li> Udacity's Google Developer Challenge Scholarship holder for Mobile Web Specialist nanodegree (2017-2018) </li> <li>Google Analytics certified (2017-2018)</li> <li> React for Beginners on Egghead.io, CSS grid by Wesbos, The Vue book </li> <li> Plethora of tutorials and blog posts closely related to: React, Vue, JavaScript, WebComponents, Stencil, Polymer, etc. </li> </UL> <Diploma> <div className="diploma-image"> <Img fluid={data.allFile.edges[0].node.childImageSharp.fluid} alt="Georgi Yanev Bachelor Diploma from Helsinki Metropolia University of Applied Sciences" /> </div> <p> Bachelor of Engineering (B.E.), Computer Software Engineering <br /> Helsinki Metropolia University of Applied Sciences </p> </Diploma> </CenteredDiv> </section> )} /> )
O3653/O3653-7 Deep Dive into the Office 365 APIs for OneNote services/Labs/Completed/OneNoteDevAad/Scripts/jquery-1.10.2.js
ThomasTrungVo/TrainingContent
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * NUGET: END LICENSE TEXT */ /*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( jQuery.support.ownLast ) { for ( key in obj ) { return core_hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[ 0 ]; if ( !a || !a.style || !all.length ) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( jQuery.support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr( elem, "value" ); return val != null ? val : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; jQuery.expr.attrHandle[ name ] = fn; return ret; } : function( elem, name, isXML ) { return isXML ? undefined : elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function( elem, name, isXML ) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = ret.push( cur ); break; } } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } })( window );
client/src/components/users/user-edit.js
commoncode/ontap
import React from 'react'; import autobind from 'autobind-decorator'; import EditForm from '../generic/edit-form'; @autobind class UserEdit extends EditForm { save(evt) { evt.preventDefault(); this.props.save(this.state.model); } delete(evt) { evt.preventDefault(); this.props.delete(this.props.model.id); } render() { const { state } = this; const { isAdmin, isCurrentUser } = this.props; const { showDelete } = this.state; return ( <div className="user-edit edit-form"> <form onSubmit={this.save}> <label htmlFor="name">Name</label> <input name="name" value={state.model.name} onChange={this.inputChangeHandler} /> <label htmlFor="email">Email</label> <input name="email" value={state.model.email} onChange={this.inputChangeHandler} /> {isAdmin && ( <fieldset> <label htmlFor="admin">Admin</label> <input type="checkbox" name="admin" checked={state.model.admin} onChange={this.checkboxChangeHandler} /> </fieldset> )} <button className="btn" type="submit" >Save</button> <button className="btn" onClick={this.props.reset}>Cancel</button> </form> <div className="edit-form__delete"> <a className="btn-delete" onClick={this.toggleDelete}> Delete { isCurrentUser ? 'my account' : 'this user' } </a> { showDelete && ( <a className="btn-delete-confirm" onClick={this.delete}>I am serious, do it.</a> ) } </div> </div> ); } } export default UserEdit;
docs/src/components/message-input/example.js
anchorchat/anchor-ui
export default ` \`\`\`jsx import React, { Component } from 'react'; import MessageInput from 'anchor-ui/message-input'; class MyComponent extends Component { state = { value: '' } // This is called by both enter and click handleSendMessage = () => { // Assuming there is a function/prop which actually sends the message const { sendMessage } = this.props; // Grab input value from state. This is set by handleChange const { value } = this.state; sendMessage(value); } handleChange = (event) => { this.setState({ value: event.currentTarget.value }); } render() { const { value } = this.state; return ( <MessageInput onChange={this.handleChange} placeholder="Type something..." value={value} sendMessage={this.handleSendMessage} /> ); } } \`\`\` `;
src/Components/Column/Column.js
apiaryio/attributes-kit
import React from 'react'; import PropTypes from 'prop-types'; import Radium from 'radium'; import merge from 'lodash/merge'; @Radium class Column extends React.Component { static propTypes = { style: PropTypes.object, children: PropTypes.oneOfType([ PropTypes.object, PropTypes.array, ]), }; get style() { const style = { height: 'auto', width: '100%', display: 'flex', flexDirection: 'column', flexWrap: 'no-wrap', justifyContent: 'flex-start', alignItems: 'flex-start', }; return merge(style, this.props.style); } render() { return ( <div style={this.style}> {this.props.children} </div> ); } } export default Column;
smsgw/static/js/sent/list.react.js
VojtechBartos/smsgw
'use strict'; import React from 'react'; import {Link} from 'react-router'; import {Table, DropdownButton, MenuItem, Tooltip, OverlayTrigger} from 'react-bootstrap'; import {Map} from 'immutable'; import moment from 'moment'; import * as actions from './actions'; import * as store from './store'; import Component from '../components/component.react'; import Spinner from '../components/spinner.react'; import Application from '../applications/application'; import User from '../users/user'; class List extends Component { componentDidMount() { const { user, application } = this.props; actions.getAll( (user) ? user.uuid : null, (application) ? application.uuid : null ); } onDeleteAction(e, message) { e.preventDefault(); const { user, application } = this.props; actions.remove( message.uuid, (application) ? application.uuid : null, (user) ? user.uuid : null ); } render() { const { application } = this.props; const sentItems = store.getAll((application) ? application.uuid : null); const now = moment(); if (actions.getAll.pending || actions.remove.pending || !sentItems) return <Spinner fullscreen={true} />; return ( <div id="context"> <h1>Sent ({sentItems.size})</h1> <Table responsive> <thead> <tr> <th>To</th> <th>Text</th> <th>Parts</th> <th>Sent at</th> <th>Created</th> <th></th> </tr> </thead> <tbody> {sentItems.toArray().map((message, i) => { const contact = () => { if (!message.contact) return message.destinationNumber; const tooltip = ( <Tooltip id="tooltip"> {message.contact.phoneNumber} </Tooltip> ); return ( <OverlayTrigger placement='right' overlay={tooltip}> <Link to="contact-edit" params={{uuid: message.contact.uuid}}> {message.contact.lastName} {message.contact.firstName} </Link> </OverlayTrigger> ); }; return ( <tr key={i}> <td>{contact()}</td> <td style={{maxWidth: '500px'}}>{message.text}</td> <td>{message.multiparts}</td> <td> <div> {message.sendLocalized} {' '} <small> ({moment.duration(message.sendDatetime.diff(now)).humanize()} ago) </small> </div> </td> <td>{message.createdLocalized}</td> <td> <DropdownButton id="dropdown-1" title="actions" bsStyle="primary" bsSize="xsmall"> <MenuItem eventKey="1" onClick={(e) => this.onDeleteAction(e, message)}> Delete </MenuItem> </DropdownButton> </td> </tr> ); })} </tbody> </Table> </div> ); } } List.propTypes = { router: React.PropTypes.func, user: React.PropTypes.instanceOf(User), application: React.PropTypes.instanceOf(Application), sent: React.PropTypes.instanceOf(Map).isRequired }; export default List;
App/Components/Styles/MapCalloutStyle.js
NomadScience/Sonder
// @flow import { StyleSheet } from 'react-native' export default StyleSheet.create({ callout: { position: 'relative', flex: 1 } })
lens-ui/app/app.js
archanah24/lens
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import React from 'react'; import Router from 'react-router'; import { DefaultRoute, Route } from 'react-router'; import './styles/less/globals.less'; import './styles/css/global.css'; import Login from './components/LoginComponent'; import Logout from './components/LogoutComponent'; import About from './components/AboutComponent'; import App from './components/AppComponent'; import AdhocQuery from './components/AdhocQueryComponent'; import QueryResults from './components/QueryResultsComponent'; import DatabaseComponent from './components/DatabaseComponent'; import CubeSchema from './components/CubeSchemaComponent'; import QueryDetailResult from './components/QueryDetailResultComponent'; import TableSchema from './components/TableSchemaComponent'; import SavedQueries from './components/SavedQueriesComponent'; import SessionList from './components/SessionListComponent' let routes = ( <Route name='app' path='/' handler={App} > <Route name='login' handler={Login}/> <Route name='logout' handler={Logout}/> <Route name='query' path='query' handler={AdhocQuery} > <Route name='results' handler={QueryResults}/> <Route name='savedqueries' handler={SavedQueries}/> <Route name='result' path='/results/:handle' handler={QueryDetailResult}/> </Route> <Route name='schema' path='schema/' handler={AdhocQuery} > <Route name='cubeschema' path='cube/:cubeName' handler={CubeSchema}/> <Route name='tableschema' path='table/:tableName' handler={TableSchema}/> </Route> <Route name='sessions' path='sessions' handler={SessionList}/> <Route name='about' handler={About} /> <DefaultRoute handler={AdhocQuery} /> </Route> ); Router.run(routes, Router.HistoryLocation, (Handler) => { React.render(<Handler/>, document.getElementById('app')); // and hide the loader which was loading in html while JavaScript // was downloading document.getElementById('loader-no-js').style.display = 'none'; });
src/Label.js
gianpaj/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Label = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render() { let classes = this.getBsClassSet(); return ( <span {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </span> ); } }); export default Label;
src/pages/Admin/sagas.js
rajatsharma305/eldritch
import { call, put, cancel, takeLatest, take } from 'redux-saga/effects' import { delay } from 'redux-saga' import { getFirebase } from 'react-redux-firebase' export function* updateFirebase (action) { yield call(delay, 1000) getFirebase().set(`posters/${action.payload.path}/${action.payload.key}`, action.payload.value) yield put({ type: 'SHOWHIDETOASTER', payload: true }) yield call(delay, 1000) yield put({ type: 'SHOWHIDETOASTER', payload: false }) } export function* syncFirebase ({ path, ordered, data, timestamp, requesting, requested }) { if (path === '/posters') { yield put({ path, ordered, data, timestamp, requesting, requested, type: 'FIREABASESYNCED' }) } } export function* rootAdminSaga () { const changeposterwatcher = yield takeLatest('CHANGEPOSTERURL', updateFirebase) const setFirebaseWatcher = yield takeLatest('@@reactReduxFirebase/SET', syncFirebase) yield take('LOCATION_CHANGE') yield cancel(changeposterwatcher) yield cancel(setFirebaseWatcher) } export default [ rootAdminSaga ]
src/components/Paragraph.js
dlindahl/stemcell
import React from 'react' import Text from './Text' const Paragraph = (props) => <Text as="p" block marginVertical={1} {...props}/> export default Paragraph
src/svg-icons/hardware/phonelink-off.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhonelinkOff = (props) => ( <SvgIcon {...props}> <path d="M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"/> </SvgIcon> ); HardwarePhonelinkOff = pure(HardwarePhonelinkOff); HardwarePhonelinkOff.displayName = 'HardwarePhonelinkOff'; HardwarePhonelinkOff.muiName = 'SvgIcon'; export default HardwarePhonelinkOff;
ReactApollo/src/Stocks.js
davidpaulmcintyre/graphql-stockticker
import React from 'react'; import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import {Table, Column, Cell} from 'fixed-data-table'; import TextCell from './TextCell'; import LinkCell from './LinkCell'; import NumericColorCell from './NumericColorCell'; import NumberCell from './NumberCell'; import '../node_modules/fixed-data-table/dist/fixed-data-table.min.css'; const Stocks = ({ data: { loading, stocks } }) => { if (loading) { return <div>Loading...</div>; } else { stocks = stocks || []; const headerHeight = 50; const rowHeight = 50; const height = stocks.length * rowHeight + headerHeight; return ( <div style={{padding: '20px'}}> <h2>{'Stock Ticker'}</h2> <Table rowHeight={rowHeight} rowsCount={stocks.length} width={1000} height={height} headerHeight={headerHeight}> <Column header={<Cell>Symbol</Cell>} cell={<LinkCell data={stocks} field="symbol" /> } width={200} /> <Column header={<Cell>{'Company Name'}</Cell>} cell={<TextCell data={stocks} field="companyName" /> } width={200} /> <Column header={<Cell>Price</Cell>} cell={<NumberCell data={stocks} field="price" /> } width={200} /> <Column header={<Cell>Change</Cell>} cell={<NumericColorCell data={stocks} field="change" /> } width={200} /> <Column header={<Cell>{'% Change'}</Cell>} cell={<NumericColorCell data={stocks} field="changePct" /> } width={200} /> </Table> </div> ); } }; export default graphql(gql` query StocksQuery { stocks { companyName, symbol, price, change, changePct, openPrice, marketCap, exchange } } ` )(Stocks);
client/components/services/FacilityCard.js
JSVillage/military-families-backend
import React from 'react'; const FacilityCard = (props) => { return <div className="col-md-3"> <div className="panel panel-info"> <div className="panel-heading"> <h3>{props.facility.facilityName}</h3> <p>{props.facility.address}</p> </div> <ul className="list-group"> { props.facility.programs.map((program, index) => <li className="list-group-item services-list" key={index} dangerouslySetInnerHTML={{__html: program}}></li>) } </ul> </div> </div> }; export default FacilityCard;
src/ui/components/SelectField.js
dartelvis/zf3
import React from 'react'; import { MenuItem } from 'material-ui'; import SelectFieldOriginal from 'material-ui/SelectField'; class SelectField extends React.Component { constructor(props) { super(props); this.onChange = this.onChange.bind(this); var value = this.props.data.value; // string caso (multiple === false) this.state = {value: (value && typeof value === 'object' ? value : (value || '').toString())}; } componentWillReceiveProps(nextProps) { if (this.state[nextProps.data.name] != nextProps.data.value) { var value = nextProps.data.value; // string caso (multiple === false) this.setState({value: (value && typeof value === 'object' ? value : (value || '').toString())}); } } onChange(value) { this.props.onChange(this.props.data.name, value); this.setState({value: value}); } render() { var select = this.props.data, value = this.state.value, menusElm = []; if (typeof value === 'object' && !value.length) { value = ''; } select.items.map((item) => { item.id = item.id.toString(); menusElm.push( <MenuItem key={item.id} value={item.id} insetChildren={true} primaryText={item.name} checked={(item.id && value && value.includes(item.id)) || false} /> ); }); return ( <SelectFieldOriginal fullWidth={true} value={value || ''} floatingLabelText={select.label} multiple={select.multiple || false} required={select.required || false} disabled={select.disabled || false} errorText={select.required ? ' ' : ''} onChange={(a, b, v) => this.onChange(v)} > {menusElm} </SelectFieldOriginal> ); } } export default SelectField;
ajax/libs/highcharts/4.0.4/highcharts.src.js
gasolin/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v4.0.4 (2014-09-02) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (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, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, error, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highcharts', VERSION = '4.0.4', // 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', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace if (win.Highcharts) { error(16, true); } else { Highcharts = win.Highcharts = {}; } /** * 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. If the first argument is * true, the contents of the second object is copied into the first 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, args = arguments, len, 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]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * 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 obj && 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, 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 (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 && !hasSVG) { // #2686 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 () { return UNDEFINED; }; 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 externalFn = Highcharts.numberFormat, 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 externalFn !== numberFormat ? externalFn(number, decimals, decPoint, thousandsSep) : (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 - timezoneOffset), 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; if (val !== null) { 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, allowDecimals) { 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 (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; } /** * 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 */ error = function (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 */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 31 * 24 * 3600000, year: 31556952000 }; /** * 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; /*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 = Fx.step, base; // 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 = $.Tween.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) { var elem; // 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($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', 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)); }); /** * 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, len = arr.length; for (i = 0; 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 (this[0]) { 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; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * 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 returnValue (#2790), 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; delete eventArguments.returnValue; } 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.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(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: '#606060', cursor: 'default', fontSize: '11px' } }; defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'], 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, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/4.0.4/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/4.0.4/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: 0, 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: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, 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, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', //defer: true, 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, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <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: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // 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: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .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}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //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'; Date = defaultOptions.global.Date || window.Date; timezoneOffset = ((useUTC && defaultOptions.global.timezoneOffset) || 0) * 60000; 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) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created 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 = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow', 'HcTextStroke'], /** * 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; }, /** * 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, {}); //#2625 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(); } } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (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].attr('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 (stop[1].indexOf('rgba') === 0) { 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); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * 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 (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width); // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ 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; }, /** * 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, element = wrapper.element, 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 + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('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, textStr = wrapper.textStr, cacheKey; // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num.' + textStr.toString().length + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); } //else { // This code block made demo/waterfall fail, related to buildText // Caching all strings reduces rendering time by 4-5%. // TODO: Check how this affects places where bBox is found on the element //cacheKey = textStr + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : ''); //} if (cacheKey) { bBox = renderer.cache[cacheKey]; } // No cache found 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, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { 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)); } } // Cache it wrapper.bBox = bBox; if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); } else { this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } return this; }, /** * 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.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * 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, element = this.element, zIndex = this.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 childNodes = parentNode.childNodes; 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 if (this.onAdd) { this.onAdd(); } 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, #2697). while (parentToClean && parentToClean.div && 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; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); 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]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = pick(value, '').replace(/<[^>]*>/g, ''); // #3276 }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key, element) { element.setAttribute(key, value); this[key] = value; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * 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, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); 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.cache = {}; // Cache for numerical bounding boxes 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); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * 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, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textStroke = textStyles && textStyles.HcTextStroke, i = childNodes.length, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textStroke && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(textStr)); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .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); } else { lines = [textStr]; } // 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(/&lt;/g, '<') .replace(/&gt;/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 if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // 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', getLineHeight(tspan) ); } // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, actualWidth, hcHeight = textStyles.HcHeight, rest = [], dy = getLineHeight(tspan), softLineNo = 1, bBox; while (hasWhiteSpace && (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 (hcHeight && softLineNo * dy > hcHeight) { 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, '-'))); } } } spanNo++; } } }); }); } }, /** * 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, 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 }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.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'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * 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] || (options && options.width && options.height && [options.width, options.height]); // 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 ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors; x += normalizer; y += normalizer; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * 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; }, /** * 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, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { fontSize = fontSize || this.style.fontSize; if (elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement fontSize = win.getComputedStyle(elem, "").fontSize; } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // 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, f: fontSize }; }, /** * 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, 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.textStr && 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, text).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.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(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) && bBox && (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); if (y !== UNDEFINED) { text.attr('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; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // 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(wrapper.textProps, 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 () { // 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 = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * 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], 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, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * 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 wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: this.style.fontFamily, fontSize: this.style.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, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: 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; } }); /* **************************************************************************** * * * 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. */ 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; }, /** * 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 if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // 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://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * 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 = []; 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 or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // 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'; }, /** * 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; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.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) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * 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, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; 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) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. 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 wrapper.onAdd = 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; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * 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. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; 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'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return 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, rotation = labelOptions.rotation, 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 }; // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(rotation)) { attr.rotation = rotation; } if (width && labelOptions.ellipsis) { css.HcHeight = axis.len / tickPositions.length; } tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(extend(css, labelOptions.style)) .add(axis.labelGroup) : null; // Set the tick baseline and correct for rotation (#1764) axis.tickBaseline = chart.renderer.fontMetrics(labelOptions.style.fontSize, label).b; if (rotation && axis.side === 2) { axis.tickBaseline *= mathCos(rotation * deg2rad); } // update } else if (label) { label.attr({ text: str }) .css(css); } tick.yOffset = label ? pick(labelOptions.y, axis.tickBaseline + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))) : 0; }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? 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.label.getBBox(), axis = this.axis, horiz = axis.horiz, options = axis.options, labelOptions = options.labels, size = horiz ? bBox.width : bBox.height, leftSide = horiz ? labelOptions.x - size * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] : 0, rightSide = horiz ? size + leftSide : size; return [leftSide, rightSide]; }, /** * 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, isFirst = this.isFirst, isLast = this.isLast, horiz = axis.horiz, pxPos = horiz ? xy.x : xy.y, reversed = axis.reversed, tickPositions = axis.tickPositions, sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], axisLeft, axisRight, neighbour, neighbourEdge, line = this.label.line, lineIndex = line || 0, labelEdge = axis.labelEdge, justifyLabel = axis.justifyLabels && (isFirst || isLast), justifyToPlot; // Hide it if it now overlaps the neighbour label if (labelEdge[lineIndex] === UNDEFINED || pxPos + leftSide > labelEdge[lineIndex]) { labelEdge[lineIndex] = pxPos + rightSide; } else if (!justifyLabel) { show = false; } if (justifyLabel) { justifyToPlot = axis.justifyToPlot; axisLeft = justifyToPlot ? axis.pos : 0; axisRight = justifyToPlot ? axisLeft + axis.len : axis.chart.chartWidth; // Find the firsth neighbour on the same line do { index += (isFirst ? 1 : -1); neighbour = axis.ticks[tickPositions[index]]; } while (tickPositions[index] && (!neighbour || !neighbour.label || neighbour.label.line !== line)); // #3044 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 (pxPos + leftSide < axisLeft) { // Align it to plot left pxPos = axisLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (pxPos + rightSide > axisRight) { // Align it to plot right pxPos = axisRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && pxPos + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = pxPos; } 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; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + this.yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { label.line = (index / (step || 1) % staggerLines); y += label.line * (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 opacity = pick(opacity, 1); 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 (!axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { show = tick.handleOverflow(index, xy); } // 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 */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.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); if (color) { 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) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? 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); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * 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; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return 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 Highcharts.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; }, /** * 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]); } } }); } }; /** * 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: 10, 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: '#707070' } //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: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -15 // 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.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.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' && pick(options.tickInterval, 1) === 1) ? 0.5 : 0; // #3202 // Major ticks axis.ticks = {}; axis.labelEdge = []; // 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 = {}; // 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, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].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.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * 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 (mathAbs(value) >= 10000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1, UNDEFINED, ''); // #2466 } } 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 properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null; if (axis.buildStacks) { 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, 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 = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // 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, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); 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 || 1); }, /** * 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 = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // 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; }, /** * 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( axis.getTimeTicks( axis.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 = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (axis.isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 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, startOnTick = options.startOnTick, endOnTick = options.endOnTick, 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[axis.coll][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 && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; 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.axisPointRange && !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; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // 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 && !this.isLog && !categories && startOnTick && endOnTick) { 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), // If the tick interval is between 1 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 1 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)) ); } } // 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.getTimeTicks( axis.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 (startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } // 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 0 or 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 = mathAbs(axis.max) > 10e12 ? 1 : 0.001; // The lowest possible number to avoid extra padding on columns (#2619, #2846) 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.coll, 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 && this.min !== UNDEFINED) { 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) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, 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 = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseInt(height, 10) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseInt(top, 10) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; 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); }, /** * 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 labelOffsetPadded, 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, lineHeightCorrection; // 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 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .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] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // 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]); lineHeightCorrection = side === 2 ? axis.tickBaseline : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickBaseline + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); 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, horiz = axis.horiz, reversed = axis.reversed, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, sortedPositions, axisTitle = axis.axisTitle, 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, overflow = options.labels.overflow, justifyLabels = axis.justifyLabels = horiz && overflow !== false, to; // Reset axis.labelEdge.length = 0; axis.justifyToPlot = overflow === 'justify'; // 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 sortedPositions = tickPositions.slice(); if ((horiz && reversed) || (!horiz && !reversed)) { sortedPositions.reverse(); } if (justifyLabels) { sortedPositions = sortedPositions.slice(1).concat([sortedPositions[0]]); } each(sortedPositions, function (pos, i) { // Reorganize the indices if (justifyLabels) { i = (i === sortedPositions.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, 0.1); } ticks[pos].render(i); } }); // 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 Highcharts.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) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * 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', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too. if ((defined(point) || !pick(this.crosshair.snap, true)) === false) { this.hideCrosshair(); return; } var path, options = this.crosshair, animation = options.animation, pos; // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY; /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)); } else { path = this.getPlotLinePath(null, null, null, null, pos); } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { var attribs = { 'stroke-width': options.width || 1, stroke: options.color || '#C0C0C0', zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * 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 */ Axis.prototype.getTimeTicks = function (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 - timezoneOffset), 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; if (timezoneOffset) { minDate = new Date(minDate.getTime() + timezoneOffset); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? timezoneOffset : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // 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 === localTimezoneOffset; }), 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; }; /** * 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. */ Axis.prototype.normalizeTimeTickInterval = function (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] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.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) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 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; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { 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 || 'callout', 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: -9999 }); // #2301, #2657 // 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 () { // 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 && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : 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) { // 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 (delay) { 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(delay, this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * 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) { var chart = this.chart, distance = this.distance, ret = {}, swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = point.ttBelow || (chart.inverted && !point.negative) || (!chart.inverted && point.negative), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft; } else if (roomRight) { ret[dim] = alignedRight; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * 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 = [tooltip.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, 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; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // 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, negative: point.negative, ttBelow: point.ttBelow }); this.isHidden = false; } 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 ); }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = point.series, tooltipOptions = series.tooltipOptions, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), 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 || // If the point is placed every day at 23:59, we need to show // the minutes as well. This logic only works for time units less than // a day, since all higher time units are dividable by those. #2637. (timeUnits[n] <= timeUnits.day && point.key % timeUnits[n] > 0)) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } xDateFormat = xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 } // Insert the header date format if any if (isDateTime && xDateFormat) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * 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 */ var Pointer = Highcharts.Pointer = function (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); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = options.tooltip.followTouchMove; } 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 || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[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, followPointer, 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].singularTooltips !== true && 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 followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (hoverSeries && hoverSeries.tracker && !followPointer) { // #2584, #2830 // 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 && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Draw independent crosshairs each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(point, hoverPoint)); }); }, /** * 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, delay) { 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); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); 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); }, /** * 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, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // 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 && !panKey) { 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.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, 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, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.coll].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) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.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 () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.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; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 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, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; 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')) { // 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); } } } }, /** * 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; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { 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 = self.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.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(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, 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); } }); self.res = true; // reset on next move // 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(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)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, onContainerTouchStart: function (e) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // 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) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom || this.followTouchMove) { css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (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.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; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // 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.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { 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 symbolAttr.stroke = symbolColor; 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.checkboxOffset + 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 = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 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.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.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); // 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 || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { 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 ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * 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 = legend.getAllItems(); // 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({ width: legendWidth, height: 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, 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, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 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 pages = this.pages, pageCount = pages.length, 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 + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + 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 = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || 12; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 5 - (symbolHeight / 2), legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * 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 */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).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 !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue 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 this.userOptions = userOptions; 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); chartCount++; // 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 = chart.colorCounter = chart.symbolCounter = 0; 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; }, /** * 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, hasCartesianSeries = chart.hasCartesianSeries, 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 (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); } chart.getMargins(); // #3098 if (hasCartesianSeries) { // 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(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(); }); }, /** * 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, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { 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(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // 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 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } 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. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { 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. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !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; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); 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, 20), 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(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // 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(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; 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)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); 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.layOutTitles(); // #2857 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: mathMax(0, 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) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: 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, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // 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 series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); if (serie.setTooltipPoints) { serie.setTooltipPoints(); } serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.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; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; // 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(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * 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; chartCount--; 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 if (Highcharts.Pointer) { 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 = []; var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * 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); }); } }; /** * 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.options.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 }; }, /** * 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 }); }, /** * 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); } };/** * @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' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; 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 each(series.parallelArrays, function (key) { series[key + '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, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } 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; each(series.axisTypes || [], 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] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * 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, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.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( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (!this.options.colorByPoint) { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, tooltipPoints = series.tooltipPoints, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData) { each(data, function (point, i) { oldData[i].update(point, false, null, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // 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]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.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.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } if (tooltipPoints) { // #2594 tooltipPoints.length = 0; } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * 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, activePointCount = 0, isCartesian = series.isCartesian, xExtremes, min, max; // 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; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // 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; activePointCount = processedXData.length; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (!cropped && processedXData[i] > min && processedXData[i] < max) { activePointCount++; } 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; series.activePointCount = activePointCount; 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]))); } points[i].index = cursor; // For faster access in Point.update } // 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; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, 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; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; 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 = stacking && 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; error(10); } // 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 + ',' + i]; 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 = pointStack.total && (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(); }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = series.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, clipBox.height].join(','); // 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); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group, clipBox = this.clipBox; if (group && this.options.clip !== false) { if (!sharedClipKey || !clipBox) { group.clip(clipBox ? chart.renderer.clipRect(clipBox) : chart.clipRect); } this.markerGroup.clip(); // no clip } fireEvent(this, 'afterAnimate'); // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { if (!clipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { 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, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, globallyEnabled = pick( seriesMarkerOptions.enabled, !series.requireSorting || series.activePointCount < (0.5 * series.xAxis.len / seriesMarkerOptions.radius) ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && 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] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .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, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .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 = series.hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, attr, 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 + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } 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; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { 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. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover.color) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, 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; } } }, /** * 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(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // 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]; } }, /** * 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, fill: NONE, 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)); if (translatedThreshold < 0) { chartSizeMax -= translatedThreshold; // #2534 } 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 () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : 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, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, 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 (animDuration) { 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(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && 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 (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { 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(); if (series.setTooltipPoints) { series.setTooltipPoints(true); } series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { 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 and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // 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, null, null, 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(axis.usePercentage ? 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[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, 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); } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.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, pointKey, 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]; pointKey = series.index + ',' + 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); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[pointKey] = [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 = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = (stack.cum || 0) + (y || 0); stack.points[pointKey].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 */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index + ',' + i]; 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]; } } }); }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * 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); } }, /** * 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, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // 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 ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * 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; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * 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, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); 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); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * 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.updateParallelArrays(point, 'splice', i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * 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, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, 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--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { 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(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * 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; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, 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, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // 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); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 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.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].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(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * 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 series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, 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) { var y = 0, stackPoint; 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 { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackPoint = stack[x].points[i + ',' + x]; if (stackPoint) { y = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.toPixels(y, 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); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); 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: LegendSymbolMixin.drawRectangle }); 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, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 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 || xAxis.tickInterval || 1), // #2610 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 = series.borderWidth = pick( options.borderWidth, series.activePointCount > 0.5 * series.xAxis.len ? 0 : 1 ), 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 = mathMax(pointWidth, 1 + 2 * borderWidth), // 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; } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } 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, 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; // Fix the tooltip on center of grouped columns (#1216, #424) point.tooltipPos = chart.inverted ? [yAxis.len - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop]; // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694) 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 edges are exceptions 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: LegendSymbolMixin.drawRectangle, /** * 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, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(pointAttr) .attr(borderAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * 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="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 singularTooltips: true, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); 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 () { // #2945 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; // 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 // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); 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); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, singularTooltips: true, /** * 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, animation, updatePoints) { Series.prototype.setData.call(this, data, false, animation, updatePoints); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(animation); } }, /** * 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; } }, /** * 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 * ((pick(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(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); 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 }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice 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 ]; } }, 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[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' //zIndex: 1 // #2722 (reversed) }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility (#2430) if (point.visible !== undefined) { point.setVisible(point.visible); } }); }, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, 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', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // 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 */ Series.prototype.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(), // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, 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 dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } 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 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.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); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.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 && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* 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, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // 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 = mathMin(mathMax(0, naturalY), chart.plotHeight); } } 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(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? 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 //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.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 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * 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. */ seriesTypes.pie.prototype.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 } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.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); }; } /** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: 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; } }, /** * 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. */ drawTrackerGraph: 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(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * 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) + ')'; // 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 TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.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); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * 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' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * 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; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * 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, move) { 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, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // 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 === false))) || // 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.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } 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) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(series.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * 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; }, /** * 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 + (stateOptions[state].lineWidthPlus || 0); } 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); }, /** * Memorize 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 || series.singularTooltips) { 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; }, /** * 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'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Point: Point, Tick: Tick, 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 }); }());